PrintersPage.tsx 495 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { mapModelCode } from '../utils/printerModel';
  5. import { formatPrintName } from '../utils/printName';
  6. import { isBedSlinger } from '../utils/bedSlinger';
  7. import { computePopoverPosition, type PopoverPosition } from '../utils/popoverPosition';
  8. import {
  9. openCameraWindow,
  10. readStoredCameraViewMode,
  11. storeCameraViewMode,
  12. type CameraViewMode,
  13. } from '../utils/camera';
  14. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  15. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  16. import {
  17. isExternalSpoolHidden,
  18. setExternalSpoolHidden as persistExternalSpoolHidden,
  19. } from '../utils/printerCardPrefs';
  20. import {
  21. BED_TEMP_DEFAULTS,
  22. CHAMBER_TEMP_DEFAULTS,
  23. FAN_SPEED_DEFAULTS,
  24. NOZZLE_TEMP_DEFAULTS,
  25. buildPresetOptions,
  26. parsePresetTriple,
  27. } from '../utils/temperatureFanPresets';
  28. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  29. // covers header + filament select + temp slider + duration + rotate-tray
  30. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  31. // earlier); under-estimating leaves the popover clipped off the bottom (the
  32. // original bug at #1447).
  33. const DRYING_POPOVER_WIDTH = 240;
  34. // Height in "now" mode plus the tallest start-mode control; a conservative
  35. // over-estimate just flips the popover above the trigger sooner.
  36. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  37. // Delay presets for the "After delay" drying start mode, in minutes.
  38. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  39. // Every printer card reads the same fleet-wide scheduled-drying list.
  40. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  41. // Why a due run has not started yet: every waiting_reason the scheduler can
  42. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  43. // for ..." with no hint why nothing is happening.
  44. const WAITING_REASON_KEYS: Record<string, string> = {
  45. ams_power_required: 'printers.drying.powerRequired',
  46. ams_retract_filament: 'printers.drying.retractFilament',
  47. ams_blocked: 'printers.drying.cannotDryNow',
  48. ams_not_found: 'printers.drying.waitingAmsNotFound',
  49. printer_offline: 'printers.drying.waitingOffline',
  50. printer_busy: 'printers.drying.waitingPrinterBusy',
  51. already_drying: 'printers.drying.waitingAlreadyDrying',
  52. interrupted: 'printers.drying.waitingInterrupted',
  53. };
  54. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  55. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  56. }
  57. // Why a scheduled drying failed, by the code the scheduler stores. A row with
  58. // no code (failed before codes existed) or an unknown one shows the backend's
  59. // English error_message instead.
  60. const FAILED_REASON_KEYS: Record<string, string> = {
  61. screen_only: 'printers.drying.screenOnly',
  62. unsupported: 'printers.drying.notSupported',
  63. did_not_start: 'printers.drying.scheduleFailedDidNotStart',
  64. };
  65. function failedReasonKey(code: string | null | undefined): string | undefined {
  66. return code ? FAILED_REASON_KEYS[code] : undefined;
  67. }
  68. // Which cannot-dry code to name when the firmware reports several at once.
  69. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  70. // button's tooltip and a scheduled row's waiting reason describe one blocked
  71. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  72. // left at the outlet, and both need the user to go and do something. The rest
  73. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  74. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  75. const codes = (reasons ?? []).map(r => Number(r));
  76. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  77. if (codes.includes(3)) return 'printers.drying.retractFilament';
  78. return 'printers.drying.cannotDryNow';
  79. }
  80. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  81. import { useTranslation } from 'react-i18next';
  82. import { useTheme } from '../contexts/ThemeContext';
  83. import { useAuth } from '../contexts/AuthContext';
  84. import {
  85. Plus,
  86. Link,
  87. Unlink,
  88. Signal,
  89. Clock,
  90. MoreVertical,
  91. Trash2,
  92. RefreshCw,
  93. RotateCw,
  94. Box,
  95. HardDrive,
  96. AlertTriangle,
  97. AlertCircle,
  98. Terminal,
  99. Power,
  100. Zap,
  101. Wrench,
  102. ChevronDown,
  103. Eye,
  104. EyeOff,
  105. Filter,
  106. Pencil,
  107. ArrowLeft,
  108. ArrowRight,
  109. ArrowUp,
  110. ArrowDown,
  111. Layers,
  112. Video,
  113. Search,
  114. Loader2,
  115. Square,
  116. Pause,
  117. Play,
  118. X,
  119. Fan,
  120. Wind,
  121. AirVent,
  122. Download,
  123. ScanSearch,
  124. CheckCircle,
  125. CheckSquare,
  126. XCircle,
  127. User,
  128. Home,
  129. Printer as PrinterIcon,
  130. Info,
  131. Cable,
  132. Flame,
  133. Hourglass,
  134. Repeat,
  135. Snowflake,
  136. Gauge,
  137. DoorOpen,
  138. DoorClosed,
  139. Move,
  140. LogIn,
  141. LogOut,
  142. MoreHorizontal,
  143. SlidersHorizontal,
  144. Stethoscope,
  145. ScanEye,
  146. LineChart as LineChartIcon,
  147. LayoutGrid,
  148. MonitorPlay,
  149. ExternalLink,
  150. PictureInPicture2,
  151. ThumbsUp,
  152. ThumbsDown,
  153. } from 'lucide-react';
  154. import { ConfirmOutcomeDialog } from '../components/ConfirmOutcomeDialog';
  155. // Aliased: lucide-react already exports a `Link` icon into this module.
  156. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  157. import { api, discoveryApi, firmwareApi, withMediaToken, ApiError } from '../api/client';
  158. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  159. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  160. import { Card, CardContent } from '../components/Card';
  161. import { Button } from '../components/Button';
  162. import { ConfirmModal } from '../components/ConfirmModal';
  163. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  164. import { FileManagerModal } from '../components/FileManagerModal';
  165. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  166. import { CameraWall } from '../components/CameraWall';
  167. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  168. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  169. import { HMSErrorModal, filterKnownHMSErrors, isSevereHMSError } from '../components/HMSErrorModal';
  170. import { AiDetectionModal } from '../components/AiDetectionModal';
  171. import { aiDetectionClass, type AiDetection } from '../utils/aiDetection';
  172. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  173. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  174. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  175. import { AmsBackupModal } from '../components/AmsBackupModal';
  176. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  177. import type { HeaterSensorKind } from '../api/client';
  178. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  179. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  180. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  181. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  182. import { useToast } from '../contexts/ToastContext';
  183. import { ChamberLight } from '../components/icons/ChamberLight';
  184. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  185. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  186. import { FileUploadModal } from '../components/FileUploadModal';
  187. import { PrintModal } from '../components/PrintModal';
  188. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  189. import { FeedDirectionModal } from '../components/FeedDirectionModal';
  190. import { getAmsLabel, getEmptySlotKind, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, installedNozzleDiameters, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, formatSlotLabel, slotPresetDescribesTray, FTS_INLET_SIDE } from '../utils/amsHelpers';
  191. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  192. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  193. import { Collapsible } from '../components/Collapsible';
  194. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  195. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  196. import { NumberInput } from '../components/NumberInput';
  197. // The status filter's options, and the only values it may hold. One list so a
  198. // saved filter cannot be validated against a set the dropdown has since moved
  199. // on from (#2833). Labels stay literal so they remain greppable.
  200. const STATUS_FILTER_OPTIONS = [
  201. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  202. { value: 'printing', labelKey: 'printers.status.printing' },
  203. { value: 'paused', labelKey: 'printers.status.paused' },
  204. { value: 'idle', labelKey: 'printers.status.idle' },
  205. { value: 'finished', labelKey: 'printers.status.finished' },
  206. { value: 'error', labelKey: 'printers.status.error' },
  207. { value: 'offline', labelKey: 'printers.status.offline' },
  208. ] as const;
  209. function isKnownStatusFilter(value: string | null): boolean {
  210. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  211. }
  212. export interface SpoolmanSlotAssignmentRow {
  213. printer_id: number;
  214. ams_id: number;
  215. tray_id: number;
  216. spoolman_spool_id: number;
  217. }
  218. // Color names resolve via getColorName() which reads the backend color_catalog
  219. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  220. // Format K value with 3 decimal places, default to 0.020 if null
  221. function formatKValue(k: number | null | undefined): string {
  222. const value = k ?? 0.020;
  223. return value.toFixed(3);
  224. }
  225. // K-profile value shown on the slot card itself (#2532) rather than only inside
  226. // the hover popup, the way BambuStudio shows it per slot.
  227. //
  228. // `k` arrives already gated on the slot being loaded; falsy means the printer
  229. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  230. // missing value, which is captioned inside the hover card but would read as a
  231. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  232. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  233. // reported 0 makes that expression evaluate to the number 0, and React renders
  234. // numbers, putting a bare "0" under the material name.
  235. //
  236. // `reserve` holds the row's height open on the slots without a value whenever
  237. // some other slot on the same card has one, so every fill bar stays on one line.
  238. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  239. const { t } = useTranslation();
  240. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  241. if (!k) {
  242. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  243. }
  244. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  245. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  246. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  247. // family per browser and so measured differently in Safari.
  248. return (
  249. <div className={className} title={t('ams.kFactor')}>
  250. {t('ams.kFactorShort')} {formatKValue(k)}
  251. </div>
  252. );
  253. }
  254. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  255. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  256. const { mode } = useTheme();
  257. const { t } = useTranslation();
  258. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  259. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  260. return (
  261. <span
  262. 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"
  263. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  264. title={side === 'L' ? t('common.left') : t('common.right')}
  265. >
  266. {side}
  267. </span>
  268. );
  269. }
  270. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  271. // deliberately a different colour, because it means something different: this
  272. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  273. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  274. const { mode } = useTheme();
  275. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  276. return (
  277. <span
  278. 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"
  279. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  280. title={title}
  281. >
  282. {FTS_INLET_SIDE[inlet]}
  283. </span>
  284. );
  285. }
  286. /**
  287. * Which side indicator, if any, belongs on an AMS card header.
  288. *
  289. * Three sources, in descending authority:
  290. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  291. * through the switch, so the inlet is the only meaningful label.
  292. * 2. A real extruder id from ams_extruder_map.
  293. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  294. * never reported a map. This one is only a guess, and it is suppressed
  295. * when a switch is installed: with an FTS every unit reports extruder
  296. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  297. * nothing but their unit numbers.
  298. */
  299. function amsSideBadge(
  300. amsId: number,
  301. amsExtruderMap: Record<string, number>,
  302. amsSwitchInlet: Record<string, 'A' | 'B'>,
  303. ftsInstalled: boolean
  304. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  305. const inlet = amsSwitchInlet[String(amsId)];
  306. if (inlet) return { kind: 'inlet', inlet };
  307. const mapped = amsExtruderMap[String(amsId)];
  308. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  309. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  310. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  311. return null;
  312. }
  313. // Expand nozzle type codes to material names
  314. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  315. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  316. function nozzleTypeName(type: string, t: (key: string) => string): string {
  317. if (!type) return '';
  318. // Full text names (from main nozzle info)
  319. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  320. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  321. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  322. // 4-char codes (e.g. "HS01"): last 2 digits = material
  323. if (type.length >= 4) {
  324. const material = type.slice(2, 4);
  325. if (material === '00') return t('printers.nozzleStainlessSteel');
  326. if (material === '01') return t('printers.nozzleHardenedSteel');
  327. if (material === '05') return t('printers.nozzleTungstenCarbide');
  328. }
  329. // 2-digit numeric codes
  330. if (type === '00') return t('printers.nozzleStainlessSteel');
  331. if (type === '01') return t('printers.nozzleHardenedSteel');
  332. if (type === '05') return t('printers.nozzleTungstenCarbide');
  333. // 2-char alpha codes: H prefix = hardened steel
  334. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  335. return type;
  336. }
  337. // Parse flow type from nozzle type code
  338. // HH = high flow, HS = standard/normal
  339. function nozzleFlowName(type: string, t: (key: string) => string): string {
  340. if (!type) return '';
  341. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  342. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  343. return '';
  344. }
  345. // Per-slot hover card for nozzle rack
  346. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  347. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  348. slot: import('../api/client').NozzleRackSlot;
  349. index: number;
  350. activeStatus?: boolean;
  351. filamentName?: string;
  352. children: React.ReactNode;
  353. }) {
  354. const { t } = useTranslation();
  355. const [isVisible, setIsVisible] = useState(false);
  356. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  357. const triggerRef = useRef<HTMLDivElement>(null);
  358. const cardRef = useRef<HTMLDivElement>(null);
  359. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  360. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  361. const isMounted = slot.stat === 1;
  362. useEffect(() => {
  363. if (isVisible && triggerRef.current && cardRef.current) {
  364. const triggerRect = triggerRef.current.getBoundingClientRect();
  365. const cardHeight = cardRef.current.offsetHeight;
  366. const headerHeight = 56;
  367. const spaceAbove = triggerRect.top - headerHeight;
  368. const spaceBelow = window.innerHeight - triggerRect.bottom;
  369. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  370. setPosition('bottom');
  371. } else {
  372. setPosition('top');
  373. }
  374. }
  375. }, [isVisible]);
  376. const handleMouseEnter = () => {
  377. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  378. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  379. };
  380. const handleMouseLeave = () => {
  381. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  382. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  383. };
  384. useEffect(() => {
  385. return () => {
  386. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  387. };
  388. }, []);
  389. const filamentCss = parseFilamentColor(slot.filament_color);
  390. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  391. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  392. return (
  393. <div
  394. ref={triggerRef}
  395. className="relative"
  396. onMouseEnter={handleMouseEnter}
  397. onMouseLeave={handleMouseLeave}
  398. >
  399. {children}
  400. {isVisible && (
  401. <div
  402. ref={cardRef}
  403. className={`
  404. absolute left-1/2 -translate-x-1/2 z-50
  405. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  406. animate-in fade-in-0 zoom-in-95 duration-150
  407. `}
  408. style={{ maxWidth: 'calc(100vw - 24px)' }}
  409. >
  410. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  411. {isEmpty ? (
  412. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  413. Slot {index + 1} — Empty
  414. </div>
  415. ) : (
  416. <div className="p-2.5 space-y-1.5">
  417. {/* Diameter */}
  418. <div className="flex items-center justify-between">
  419. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  420. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  421. </div>
  422. {/* Type */}
  423. {typeFull && (
  424. <div className="flex items-center justify-between">
  425. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  426. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  427. </div>
  428. )}
  429. {/* Flow (hide if empty) */}
  430. {flowFull && (
  431. <div className="flex items-center justify-between">
  432. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  433. <span className="text-xs text-white font-semibold">{flowFull}</span>
  434. </div>
  435. )}
  436. {/* Status badge */}
  437. <div className="flex items-center justify-between">
  438. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  439. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  440. activeStatus || isMounted
  441. ? 'bg-green-900/50 text-green-400'
  442. : 'bg-bambu-dark-tertiary text-bambu-gray'
  443. }`}>
  444. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  445. </span>
  446. </div>
  447. {/* Wear (hide if null) */}
  448. {slot.wear != null && (
  449. <div className="flex items-center justify-between">
  450. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  451. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  452. </div>
  453. )}
  454. {/* Max Temp (hide if 0) */}
  455. {slot.max_temp > 0 && (
  456. <div className="flex items-center justify-between">
  457. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  458. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  459. </div>
  460. )}
  461. {/* Serial (hide if empty) */}
  462. {slot.serial_number && (
  463. <div className="flex items-center justify-between">
  464. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  465. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  466. </div>
  467. )}
  468. {/* Filament: material type + color swatch (hide if no color) */}
  469. {(filamentCss || slot.filament_type) && (
  470. <div className="flex items-center justify-between">
  471. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  472. <div className="flex items-center gap-1">
  473. {filamentCss && (
  474. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  475. )}
  476. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  477. </div>
  478. </div>
  479. )}
  480. </div>
  481. )}
  482. </div>
  483. {/* Arrow pointer */}
  484. <div
  485. className={`
  486. absolute left-1/2 -translate-x-1/2 w-0 h-0
  487. border-l-[6px] border-l-transparent
  488. border-r-[6px] border-r-transparent
  489. ${position === 'top'
  490. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  491. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  492. `}
  493. />
  494. </div>
  495. )}
  496. </div>
  497. );
  498. }
  499. // Dual-nozzle hover card showing L and R nozzle details side by side
  500. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  501. leftSlot?: import('../api/client').NozzleRackSlot;
  502. rightSlot?: import('../api/client').NozzleRackSlot;
  503. activeNozzle: 'L' | 'R';
  504. filamentInfo?: Record<string, { name: string; k: number | null }>;
  505. children: React.ReactNode;
  506. }) {
  507. const { t } = useTranslation();
  508. const [isVisible, setIsVisible] = useState(false);
  509. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  510. const triggerRef = useRef<HTMLDivElement>(null);
  511. const cardRef = useRef<HTMLDivElement>(null);
  512. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  513. useEffect(() => {
  514. if (isVisible && triggerRef.current && cardRef.current) {
  515. const triggerRect = triggerRef.current.getBoundingClientRect();
  516. const cardHeight = cardRef.current.offsetHeight;
  517. const headerHeight = 56;
  518. const spaceAbove = triggerRect.top - headerHeight;
  519. const spaceBelow = window.innerHeight - triggerRect.bottom;
  520. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  521. setPosition('bottom');
  522. } else {
  523. setPosition('top');
  524. }
  525. }
  526. }, [isVisible]);
  527. const handleMouseEnter = () => {
  528. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  529. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  530. };
  531. const handleMouseLeave = () => {
  532. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  533. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  534. };
  535. useEffect(() => {
  536. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  537. }, []);
  538. if (!leftSlot && !rightSlot) return <>{children}</>;
  539. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  540. const isActive = activeNozzle === side;
  541. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  542. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  543. const filamentCss = parseFilamentColor(slot.filament_color);
  544. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  545. return (
  546. <div className="flex-1 space-y-1.5">
  547. <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'}`}>
  548. {side === 'L' ? t('common.left') : t('common.right')}
  549. </div>
  550. {slot.nozzle_diameter && (
  551. <div className="flex items-center justify-between">
  552. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  553. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  554. </div>
  555. )}
  556. {typeFull && (
  557. <div className="flex items-center justify-between">
  558. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  559. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  560. </div>
  561. )}
  562. {flowFull && (
  563. <div className="flex items-center justify-between">
  564. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  565. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  566. </div>
  567. )}
  568. <div className="flex items-center justify-between">
  569. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  570. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  571. isActive
  572. ? 'bg-green-900/50 text-green-400'
  573. : 'bg-bambu-dark-tertiary text-bambu-gray'
  574. }`}>
  575. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  576. </span>
  577. </div>
  578. {slot.wear != null && (
  579. <div className="flex items-center justify-between">
  580. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  581. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  582. </div>
  583. )}
  584. {/* Serial and max temp only available on the right (removable) nozzle */}
  585. {side === 'R' && slot.max_temp > 0 && (
  586. <div className="flex items-center justify-between">
  587. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  588. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  589. </div>
  590. )}
  591. {side === 'R' && slot.serial_number && (
  592. <div className="flex items-center justify-between">
  593. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  594. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  595. </div>
  596. )}
  597. {(filamentCss || slot.filament_type || slot.filament_id) && (
  598. <div className="flex items-center justify-between">
  599. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  600. <div className="flex items-center gap-1">
  601. {filamentCss && (
  602. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  603. )}
  604. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  605. {filamentName || slot.filament_type || slot.filament_id || ''}
  606. </span>
  607. </div>
  608. </div>
  609. )}
  610. </div>
  611. );
  612. };
  613. return (
  614. <div
  615. ref={triggerRef}
  616. className="relative flex-1"
  617. onMouseEnter={handleMouseEnter}
  618. onMouseLeave={handleMouseLeave}
  619. >
  620. {children}
  621. {isVisible && (
  622. <div
  623. ref={cardRef}
  624. className={`
  625. absolute left-1/2 -translate-x-1/2 z-50
  626. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  627. animate-in fade-in-0 zoom-in-95 duration-150
  628. `}
  629. style={{ maxWidth: 'calc(100vw - 24px)' }}
  630. >
  631. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  632. <div className="p-2.5 flex gap-3">
  633. {leftSlot && renderColumn(leftSlot, 'L')}
  634. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  635. {rightSlot && renderColumn(rightSlot, 'R')}
  636. </div>
  637. </div>
  638. {/* Arrow pointer */}
  639. <div
  640. className={`
  641. absolute left-1/2 -translate-x-1/2 w-0 h-0
  642. border-l-[6px] border-l-transparent
  643. border-r-[6px] border-r-transparent
  644. ${position === 'top'
  645. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  646. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  647. `}
  648. />
  649. </div>
  650. )}
  651. </div>
  652. );
  653. }
  654. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  655. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  656. const { t } = useTranslation();
  657. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  658. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  659. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  660. // base — computing it from min(present IDs) shifts everything left when slot 16
  661. // is the one currently mounted (#943).
  662. const rackNozzles = slots.filter(s => s.id >= 2);
  663. const RACK_SIZE = 6;
  664. const RACK_BASE_ID = 16;
  665. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  666. { length: RACK_SIZE },
  667. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  668. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  669. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  670. },
  671. );
  672. return (
  673. // Sized to its contents rather than growing: the six chips are a fixed
  674. // width at any one card size, so extra width would be dead space taken
  675. // from the temperature cards beside it — which are flex-1 with a 0 basis
  676. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  677. // stays enabled so the card still gives way on a narrow printer card
  678. // instead of overflowing.
  679. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  680. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  681. <div className="flex gap-[3px] justify-center">
  682. {rackSlots.map((slot, i) => {
  683. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  684. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  685. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  686. return (
  687. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  688. <div className="flex flex-col items-center gap-0.5">
  689. <div
  690. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  691. isEmpty
  692. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  693. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  694. }`}
  695. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  696. >
  697. <span
  698. data-rack-diameter
  699. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  700. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  701. >
  702. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  703. </span>
  704. </div>
  705. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  706. acted on without counting chips. Sits below the chip rather
  707. than inside it: the chip is barely wider than its own
  708. diameter text and already carries that over a
  709. filament-coloured background. */}
  710. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  711. {i + 1}
  712. </span>
  713. </div>
  714. </NozzleSlotHoverCard>
  715. );
  716. })}
  717. </div>
  718. </div>
  719. );
  720. }
  721. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  722. function WaterDropEmpty({ className }: { className?: string }) {
  723. return (
  724. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  725. <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"/>
  726. </svg>
  727. );
  728. }
  729. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  730. function WaterDropHalf({ className }: { className?: string }) {
  731. return (
  732. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  733. <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"/>
  734. <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"/>
  735. </svg>
  736. );
  737. }
  738. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  739. function WaterDropFull({ className }: { className?: string }) {
  740. return (
  741. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  742. <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"/>
  743. <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"/>
  744. </svg>
  745. );
  746. }
  747. // Thermometer SVG - empty outline
  748. function ThermometerEmpty({ className }: { className?: string }) {
  749. return (
  750. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  751. <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"/>
  752. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  753. </svg>
  754. );
  755. }
  756. // Thermometer SVG - half filled (gold - same as humidity fair)
  757. function ThermometerHalf({ className }: { className?: string }) {
  758. return (
  759. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  760. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  761. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  762. <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"/>
  763. </svg>
  764. );
  765. }
  766. // Thermometer SVG - fully filled (red - same as humidity bad)
  767. function ThermometerFull({ className }: { className?: string }) {
  768. return (
  769. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  770. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  771. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  772. <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"/>
  773. </svg>
  774. );
  775. }
  776. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  777. // Added for visual parity with the thermometer icons on the dual-nozzle card
  778. // that previously had no icon at all (#1115, design by @m4rtini2).
  779. function NozzleIcon({ className }: { className?: string }) {
  780. return (
  781. <svg
  782. className={className}
  783. viewBox="0 0 24 24"
  784. fill="none"
  785. xmlns="http://www.w3.org/2000/svg"
  786. stroke="currentColor"
  787. strokeWidth="1.5"
  788. strokeLinecap="round"
  789. strokeLinejoin="round"
  790. >
  791. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  792. <rect x="6" y="11.5" width="12.1" height="3.7" />
  793. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  794. </svg>
  795. );
  796. }
  797. // Heater thermometer icon - filled when heating, outline when off
  798. interface HeaterThermometerProps {
  799. className?: string;
  800. color: string; // The color class (e.g., "text-orange-400")
  801. isHeating: boolean;
  802. }
  803. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  804. // Extract the actual color from Tailwind class for SVG fill
  805. const colorMap: Record<string, string> = {
  806. 'text-orange-400': '#fb923c',
  807. 'text-blue-400': '#60a5fa',
  808. 'text-green-400': '#4ade80',
  809. };
  810. const fillColor = colorMap[color] || '#888';
  811. // Glow style when heating
  812. const glowStyle = isHeating ? {
  813. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  814. } : {};
  815. if (isHeating) {
  816. // Filled thermometer with glow - heater is ON
  817. return (
  818. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  819. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  820. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  821. <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"/>
  822. </svg>
  823. );
  824. }
  825. // Empty thermometer - heater is OFF
  826. return (
  827. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  828. <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"/>
  829. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  830. </svg>
  831. );
  832. }
  833. // AMS Filament Backup tri-state indicator + toggle.
  834. // state=true → ON, click to disable
  835. // state=false → OFF, click opens modal
  836. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  837. interface AmsBackupBadgeProps {
  838. state: boolean | null;
  839. onClick: () => void;
  840. }
  841. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  842. const { t } = useTranslation();
  843. const known = state !== null;
  844. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  845. let title: string;
  846. if (state === true) {
  847. className += known
  848. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  849. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  850. title = t('printers.amsBackup.titleOn');
  851. } else if (state === false) {
  852. className += known
  853. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  854. : 'bg-bambu-dark text-bambu-gray cursor-default';
  855. title = t('printers.amsBackup.titleOff');
  856. } else {
  857. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  858. title = t('printers.amsBackup.titleUnknown');
  859. }
  860. return (
  861. <button
  862. type="button"
  863. disabled={!known}
  864. onClick={() => known && onClick()}
  865. className={className}
  866. title={title}
  867. aria-label={title}
  868. >
  869. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  870. </button>
  871. );
  872. }
  873. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  874. // like AmsBackupBadge so the two sit together in the section header, but
  875. // pinned to the right-hand end of the rule: this is a view preference for the
  876. // row, not a property of the printer.
  877. interface ExternalSpoolToggleProps {
  878. hidden: boolean;
  879. onClick: () => void;
  880. }
  881. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  882. const { t } = useTranslation();
  883. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  884. return (
  885. <button
  886. type="button"
  887. onClick={onClick}
  888. aria-pressed={hidden}
  889. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  890. hidden
  891. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  892. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  893. }`}
  894. title={title}
  895. aria-label={title}
  896. >
  897. {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)]" />}
  898. </button>
  899. );
  900. }
  901. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  902. // Reference: https://github.com/theicedmango/bambu-humidity
  903. interface HumidityIndicatorProps {
  904. humidity: number | string;
  905. goodThreshold?: number; // <= this is green
  906. fairThreshold?: number; // <= this is orange, > is red
  907. onClick?: () => void;
  908. compact?: boolean; // Smaller version for grid layout
  909. }
  910. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  911. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  912. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  913. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  914. // Status thresholds (configurable via settings)
  915. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  916. let textColor: string;
  917. let statusText: string;
  918. if (isNaN(humidityValue)) {
  919. textColor = '#C3C2C1';
  920. statusText = 'Unknown';
  921. } else if (humidityValue <= good) {
  922. textColor = '#22a352'; // Green - Good
  923. statusText = 'Good';
  924. } else if (humidityValue <= fair) {
  925. textColor = '#d4a017'; // Gold - Fair
  926. statusText = 'Fair';
  927. } else {
  928. textColor = '#c62828'; // Red - Bad
  929. statusText = 'Bad';
  930. }
  931. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  932. let DropComponent: React.FC<{ className?: string }>;
  933. if (isNaN(humidityValue)) {
  934. DropComponent = WaterDropEmpty;
  935. } else if (humidityValue <= good) {
  936. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  937. } else if (humidityValue <= fair) {
  938. DropComponent = WaterDropHalf; // Fair - half filled
  939. } else {
  940. DropComponent = WaterDropFull; // Bad - full (too humid)
  941. }
  942. return (
  943. <button
  944. type="button"
  945. onClick={onClick}
  946. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  947. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  948. >
  949. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  950. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  951. </button>
  952. );
  953. }
  954. // Temperature indicator with dynamic icon and coloring
  955. interface TemperatureIndicatorProps {
  956. temp: number;
  957. goodThreshold?: number; // <= this is blue
  958. fairThreshold?: number; // <= this is orange, > is red
  959. onClick?: () => void;
  960. compact?: boolean; // Smaller version for grid layout
  961. }
  962. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  963. // Ensure thresholds are numbers
  964. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  965. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  966. let textColor: string;
  967. let statusText: string;
  968. let ThermoComponent: React.FC<{ className?: string }>;
  969. if (temp <= good) {
  970. textColor = '#22a352'; // Green - good (same as humidity)
  971. statusText = 'Good';
  972. ThermoComponent = ThermometerEmpty;
  973. } else if (temp <= fair) {
  974. textColor = '#d4a017'; // Gold - fair (same as humidity)
  975. statusText = 'Fair';
  976. ThermoComponent = ThermometerHalf;
  977. } else {
  978. textColor = '#c62828'; // Red - bad (same as humidity)
  979. statusText = 'Bad';
  980. ThermoComponent = ThermometerFull;
  981. }
  982. return (
  983. <button
  984. type="button"
  985. onClick={onClick}
  986. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  987. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  988. >
  989. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  990. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  991. </button>
  992. );
  993. }
  994. // How long to wait for an AMS to report a live drying cycle after the printer
  995. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  996. // within a couple of seconds; 30s covers the slowest observed push cadence
  997. // without leaving the user waiting on a verdict.
  998. const DRY_START_CONFIRM_MS = 30_000;
  999. export function CoverImage({
  1000. url,
  1001. printName,
  1002. className = 'w-20 h-20',
  1003. radiusClass = 'rounded-lg',
  1004. }: {
  1005. url: string | null;
  1006. printName?: string;
  1007. className?: string;
  1008. radiusClass?: string;
  1009. }) {
  1010. const { t } = useTranslation();
  1011. const [loaded, setLoaded] = useState(false);
  1012. const [error, setError] = useState(false);
  1013. const [showOverlay, setShowOverlay] = useState(false);
  1014. const imgRef = useRef<HTMLImageElement>(null);
  1015. // Cache-bust the image URL when the print name changes so the browser
  1016. // fetches the new cover instead of serving the stale cached image.
  1017. const cacheBustedUrl = useMemo(() => {
  1018. if (!url) return null;
  1019. const sep = url.includes('?') ? '&' : '?';
  1020. return withMediaToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1021. }, [url, printName]);
  1022. // Re-evaluate load state when the image URL changes, and ask the element
  1023. // whether it is already showing something rather than assuming it is not.
  1024. //
  1025. // `onLoad` used to be the only thing that could set `loaded`, and this
  1026. // effect reset it to false unconditionally. That is right when the URL
  1027. // really changes, but it also runs on mount — and the two are not the same
  1028. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1029. // constant for the duration of a print, so navigating away from the
  1030. // printers page and back re-mounts with a byte-identical src that the
  1031. // browser serves from its in-memory cache. The `load` event for a cache hit
  1032. // and React's passive-effect flush are both plain tasks with no ordering
  1033. // between them, so when `load` won, this effect ran afterwards and undid
  1034. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1035. // sat there until a full reload. Nothing recovered it, because the URL
  1036. // never changes again during the print and so this effect never re-runs.
  1037. //
  1038. // Being a race, it reproduced every time for #2826's reporter and not at
  1039. // all here, which is also why the network panel showed no request: there
  1040. // was no request to show.
  1041. //
  1042. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1043. // which of the two ran first. It is also correct for the case the reporter
  1044. // proposed (a `load` that fires before React's handler is live), so the
  1045. // fix stands whichever mechanism is really at work.
  1046. useEffect(() => {
  1047. setError(false);
  1048. const el = imgRef.current;
  1049. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1050. }, [cacheBustedUrl]);
  1051. return (
  1052. <>
  1053. <div
  1054. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1055. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1056. >
  1057. {cacheBustedUrl && !error ? (
  1058. <>
  1059. <img
  1060. ref={imgRef}
  1061. src={cacheBustedUrl}
  1062. alt={t('printers.printPreview')}
  1063. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1064. onLoad={() => setLoaded(true)}
  1065. onError={() => setError(true)}
  1066. />
  1067. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1068. </>
  1069. ) : (
  1070. <Box className="w-8 h-8 text-bambu-gray" />
  1071. )}
  1072. </div>
  1073. {/* Cover Image Overlay */}
  1074. {showOverlay && cacheBustedUrl && (
  1075. <div
  1076. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1077. onClick={() => setShowOverlay(false)}
  1078. >
  1079. <div className="relative max-w-2xl max-h-full">
  1080. <img
  1081. src={cacheBustedUrl}
  1082. alt={t('printers.printPreview')}
  1083. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1084. />
  1085. {printName && (
  1086. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1087. )}
  1088. </div>
  1089. </div>
  1090. )}
  1091. </>
  1092. );
  1093. }
  1094. interface PrinterMaintenanceInfo {
  1095. due_count: number;
  1096. warning_count: number;
  1097. total_print_hours: number;
  1098. }
  1099. // Status summary bar component - uses queryClient to read cached statuses
  1100. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1101. const { t } = useTranslation();
  1102. const queryClient = useQueryClient();
  1103. // Subscribe to query cache changes to re-render when status updates
  1104. // Throttled to prevent rapid re-renders from causing tab crashes
  1105. const [cacheTick, setCacheTick] = useState(0);
  1106. useEffect(() => {
  1107. let pending = false;
  1108. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1109. if (!pending) {
  1110. pending = true;
  1111. requestAnimationFrame(() => {
  1112. setCacheTick(t => t + 1);
  1113. pending = false;
  1114. });
  1115. }
  1116. });
  1117. return () => unsubscribe();
  1118. }, [queryClient]);
  1119. const { counts, nextFinish } = useMemo(() => {
  1120. let printing = 0;
  1121. let paused = 0;
  1122. let finished = 0;
  1123. let idle = 0;
  1124. let offline = 0;
  1125. let loading = 0;
  1126. let error = 0;
  1127. let nextPrinterName: string | null = null;
  1128. let nextRemainingMin: number | null = null;
  1129. let nextProgress: number = 0;
  1130. printers?.forEach((printer) => {
  1131. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1132. if (status === undefined) {
  1133. // Status not yet loaded - don't count as offline yet
  1134. loading++;
  1135. } else if (!status.connected) {
  1136. offline++;
  1137. } else {
  1138. // Count printers with active HMS errors as problems
  1139. const knownHmsCount =
  1140. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1141. if (knownHmsCount > 0) {
  1142. error++;
  1143. }
  1144. switch (status.state) {
  1145. case 'RUNNING':
  1146. printing++;
  1147. if (status.remaining_time != null && status.remaining_time > 0) {
  1148. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1149. nextRemainingMin = status.remaining_time;
  1150. nextPrinterName = printer.name;
  1151. nextProgress = status.progress || 0;
  1152. }
  1153. }
  1154. break;
  1155. case 'PAUSE':
  1156. paused++;
  1157. break;
  1158. case 'FINISH':
  1159. finished++;
  1160. break;
  1161. case 'FAILED':
  1162. // FAILED is the printer's terminal gcode_state after a print stops —
  1163. // including user cancellations, where there's no actual fault. Only
  1164. // count it as a "problem" when an HMS error is also active; otherwise
  1165. // it's just a print that ended unsuccessfully and the plate needs
  1166. // clearing (same as FINISH from the operator's perspective).
  1167. if (knownHmsCount > 0) {
  1168. // Already counted above
  1169. } else {
  1170. finished++;
  1171. }
  1172. break;
  1173. default:
  1174. idle++;
  1175. break;
  1176. }
  1177. }
  1178. });
  1179. return {
  1180. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1181. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1182. };
  1183. // eslint-disable-next-line react-hooks/exhaustive-deps
  1184. }, [printers, queryClient, cacheTick]);
  1185. if (!printers?.length) return null;
  1186. const badges: { count: number; dot: string; label: string }[] = [
  1187. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1188. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1189. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1190. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1191. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1192. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1193. ];
  1194. return (
  1195. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1196. {badges.map(({ count, dot, label }) => count > 0 && (
  1197. <div key={label} className="flex items-center gap-1.5">
  1198. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1199. <span className="text-bambu-gray">
  1200. <span className="text-white font-medium">{count}</span> {label}
  1201. </span>
  1202. </div>
  1203. ))}
  1204. {nextFinish && (
  1205. <>
  1206. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1207. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1208. <div className="flex items-center gap-2">
  1209. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1210. <span className="text-white font-medium">{nextFinish.name}</span>
  1211. </div>
  1212. <div className="flex items-center gap-2 w-full sm:w-auto">
  1213. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1214. <div
  1215. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1216. style={{ width: `${nextFinish.progress}%` }}
  1217. />
  1218. </div>
  1219. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1220. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1221. </div>
  1222. </div>
  1223. </>
  1224. )}
  1225. </div>
  1226. );
  1227. }
  1228. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1229. type ViewMode = 'expanded' | 'compact';
  1230. type ToolbarDropdownOption<T extends string> = {
  1231. value: T;
  1232. label: string;
  1233. };
  1234. function ToolbarDropdown<T extends string>({
  1235. value,
  1236. options,
  1237. onChange,
  1238. fullWidth = false,
  1239. }: {
  1240. value: T;
  1241. options: ToolbarDropdownOption<T>[];
  1242. onChange: (value: T) => void;
  1243. fullWidth?: boolean;
  1244. }) {
  1245. const [isOpen, setIsOpen] = useState(false);
  1246. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1247. return (
  1248. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1249. <button
  1250. type="button"
  1251. onClick={() => setIsOpen(open => !open)}
  1252. 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'}`}
  1253. >
  1254. <span className="truncate">{selectedOption?.label}</span>
  1255. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1256. </button>
  1257. {isOpen && (
  1258. <>
  1259. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1260. <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">
  1261. {options.map(option => (
  1262. <button
  1263. key={option.value}
  1264. type="button"
  1265. onClick={() => {
  1266. onChange(option.value);
  1267. setIsOpen(false);
  1268. }}
  1269. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1270. option.value === value ? 'text-bambu-green' : 'text-white'
  1271. }`}
  1272. >
  1273. {option.label}
  1274. </button>
  1275. ))}
  1276. </div>
  1277. </>
  1278. )}
  1279. </div>
  1280. );
  1281. }
  1282. function ToolbarMenu({
  1283. label,
  1284. icon,
  1285. children,
  1286. }: {
  1287. label: string;
  1288. icon: React.ReactNode;
  1289. children: React.ReactNode;
  1290. }) {
  1291. const [isOpen, setIsOpen] = useState(false);
  1292. return (
  1293. <div className="relative">
  1294. <button
  1295. type="button"
  1296. onClick={() => setIsOpen(open => !open)}
  1297. 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"
  1298. aria-label={label}
  1299. title={label}
  1300. >
  1301. {icon}
  1302. </button>
  1303. {isOpen && (
  1304. <>
  1305. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1306. <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">
  1307. {children}
  1308. </div>
  1309. </>
  1310. )}
  1311. </div>
  1312. );
  1313. }
  1314. function IndicatorControlPopover({
  1315. title,
  1316. options = [],
  1317. unit,
  1318. customMin,
  1319. customMax,
  1320. customStep = 1,
  1321. widthClass = 'w-[240px]',
  1322. popoverWidth = 240,
  1323. popoverHeight = 280,
  1324. isPending,
  1325. onClose,
  1326. onSubmit,
  1327. children,
  1328. }: {
  1329. title: string;
  1330. options?: Array<{ label: string; value: number }>;
  1331. unit?: string;
  1332. customMin?: number;
  1333. customMax?: number;
  1334. customStep?: number;
  1335. widthClass?: string;
  1336. popoverWidth?: number;
  1337. popoverHeight?: number;
  1338. isPending?: boolean;
  1339. onClose: () => void;
  1340. onSubmit?: (value: number) => void;
  1341. children?: React.ReactNode;
  1342. }) {
  1343. const anchorRef = useRef<HTMLSpanElement>(null);
  1344. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1345. const [customValue, setCustomValue] = useState('');
  1346. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1347. // can position via fixed coords. Portaling to document.body escapes
  1348. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1349. // own contexts and would otherwise cover the popover even at z-[60].
  1350. useLayoutEffect(() => {
  1351. const trigger = anchorRef.current?.parentElement;
  1352. if (!trigger) return;
  1353. const measure = () => {
  1354. const rect = trigger.getBoundingClientRect();
  1355. setCoords(computePopoverPosition({
  1356. triggerRect: rect,
  1357. popoverWidth,
  1358. estimatedHeight: popoverHeight,
  1359. horizontalAlign: 'center',
  1360. }));
  1361. };
  1362. measure();
  1363. window.addEventListener('resize', measure);
  1364. window.addEventListener('scroll', measure, true);
  1365. return () => {
  1366. window.removeEventListener('resize', measure);
  1367. window.removeEventListener('scroll', measure, true);
  1368. };
  1369. }, [popoverWidth, popoverHeight]);
  1370. const showCustomInput = unit !== undefined;
  1371. const submitCustom = () => {
  1372. const value = Number(customValue);
  1373. if (!Number.isFinite(value)) return;
  1374. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1375. onSubmit?.(Math.round(bounded));
  1376. };
  1377. return (
  1378. <>
  1379. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1380. {createPortal(
  1381. <>
  1382. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1383. <div
  1384. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1385. style={{
  1386. top: coords?.top ?? -9999,
  1387. left: coords?.left ?? -9999,
  1388. visibility: coords ? 'visible' : 'hidden',
  1389. }}
  1390. onClick={e => e.stopPropagation()}
  1391. >
  1392. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1393. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1394. {options.length > 0 && (
  1395. <div className="px-3 py-2.5">
  1396. <div className="grid grid-cols-2 gap-1.5">
  1397. {options.map(option => (
  1398. <button
  1399. key={`${option.label}-${option.value}`}
  1400. type="button"
  1401. disabled={isPending}
  1402. onClick={() => onSubmit?.(option.value)}
  1403. 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"
  1404. >
  1405. {option.label}
  1406. </button>
  1407. ))}
  1408. </div>
  1409. </div>
  1410. )}
  1411. {children}
  1412. {showCustomInput && (
  1413. <>
  1414. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1415. <form
  1416. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1417. onSubmit={(e) => {
  1418. e.preventDefault();
  1419. submitCustom();
  1420. }}
  1421. >
  1422. <input
  1423. type="number"
  1424. min={customMin}
  1425. max={customMax}
  1426. step={customStep}
  1427. value={customValue}
  1428. onChange={e => setCustomValue(e.target.value)}
  1429. placeholder="Custom"
  1430. 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"
  1431. />
  1432. <button
  1433. type="submit"
  1434. disabled={isPending || customValue.trim() === ''}
  1435. 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"
  1436. >
  1437. Set
  1438. </button>
  1439. </form>
  1440. </>
  1441. )}
  1442. </div>
  1443. </>,
  1444. document.body
  1445. )}
  1446. </>
  1447. );
  1448. }
  1449. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1450. function NozzleTemperatureControlBox({
  1451. label,
  1452. current,
  1453. target,
  1454. isActive,
  1455. isPending,
  1456. onSubmit,
  1457. options = NOZZLE_TEMPERATURE_OPTIONS,
  1458. }: {
  1459. label: string;
  1460. current?: number;
  1461. target?: number;
  1462. isActive: boolean;
  1463. isPending?: boolean;
  1464. onSubmit: (value: number) => void;
  1465. options?: Array<{ label: string; value: number }>;
  1466. }) {
  1467. const [customValue, setCustomValue] = useState('');
  1468. const submitCustom = () => {
  1469. const value = Number(customValue);
  1470. if (!Number.isFinite(value)) return;
  1471. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1472. };
  1473. return (
  1474. <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'}`}>
  1475. <div className="mb-1.5 flex items-center justify-between gap-2">
  1476. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1477. <span className="text-[10px] text-bambu-gray">
  1478. {Math.round(current ?? 0)}°C
  1479. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1480. </span>
  1481. </div>
  1482. <div className="grid grid-cols-2 gap-1">
  1483. {options.map(option => (
  1484. <button
  1485. key={`${label}-${option.value}`}
  1486. type="button"
  1487. disabled={isPending}
  1488. onClick={() => onSubmit(option.value)}
  1489. 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"
  1490. >
  1491. {option.label}
  1492. </button>
  1493. ))}
  1494. </div>
  1495. <form
  1496. className="mt-1.5 flex gap-1"
  1497. onSubmit={(e) => {
  1498. e.preventDefault();
  1499. submitCustom();
  1500. }}
  1501. >
  1502. <input
  1503. type="number"
  1504. min={0}
  1505. max={320}
  1506. step={1}
  1507. value={customValue}
  1508. onChange={e => setCustomValue(e.target.value)}
  1509. placeholder="Custom"
  1510. 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"
  1511. />
  1512. <button
  1513. type="submit"
  1514. disabled={isPending || customValue.trim() === ''}
  1515. 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"
  1516. >
  1517. Set
  1518. </button>
  1519. </form>
  1520. </div>
  1521. );
  1522. }
  1523. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1524. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1525. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1526. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1527. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1528. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1529. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1530. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1531. };
  1532. /** Classify a printer into one of the UI status buckets. */
  1533. function classifyPrinterStatus(
  1534. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1535. ): PrinterState {
  1536. if (!status?.connected) return 'offline';
  1537. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1538. if (hmsErrors.length > 0) return 'error';
  1539. switch (status.state) {
  1540. case 'RUNNING': return 'printing';
  1541. case 'PAUSE': return 'paused';
  1542. case 'FINISH': return 'finished';
  1543. // FAILED without an active HMS error is the printer's terminal state after
  1544. // any unsuccessful end — including user-cancellations. Treat the same as
  1545. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1546. // HMS code is actually attached (handled by the early-return above).
  1547. case 'FAILED': return 'finished';
  1548. default: return 'idle';
  1549. }
  1550. }
  1551. /**
  1552. * Get human-readable status display text for a printer.
  1553. * Uses stg_cur_name for detailed calibration/preparation stages,
  1554. * otherwise formats the gcode_state nicely.
  1555. */
  1556. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1557. // If we have a specific stage name (calibration, heating, etc.), use it
  1558. if (stg_cur_name) {
  1559. return stg_cur_name;
  1560. }
  1561. // Format the gcode_state nicely
  1562. switch (state) {
  1563. case 'RUNNING':
  1564. return 'Printing';
  1565. case 'PAUSE':
  1566. return 'Paused';
  1567. case 'FINISH':
  1568. return 'Finished';
  1569. case 'FAILED':
  1570. return 'Failed';
  1571. case 'IDLE':
  1572. return 'Idle';
  1573. default:
  1574. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1575. }
  1576. }
  1577. // Bambu models that ship with an enclosure chamber fan (firmware field
  1578. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1579. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1580. // widget is hidden in fanItems instead of rendered greyed-out.
  1581. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1582. 'X1C',
  1583. 'X1',
  1584. 'X1E',
  1585. 'X2D',
  1586. 'P1S',
  1587. 'P2S',
  1588. 'H2D',
  1589. 'H2D Pro',
  1590. 'H2C',
  1591. 'H2S',
  1592. ]);
  1593. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1594. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1595. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1596. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1597. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1598. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1599. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1600. 'P2S',
  1601. 'X2D',
  1602. ]);
  1603. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1604. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1605. // • User-defined friendly name (editable, protected by printers:update)
  1606. // • AMS serial number
  1607. // • AMS firmware version
  1608. export function AmsNameHoverCard({
  1609. ams,
  1610. printerId,
  1611. label,
  1612. amsLabels,
  1613. canEdit,
  1614. onSaved,
  1615. children,
  1616. }: {
  1617. ams: import('../api/client').AMSUnit;
  1618. printerId: number;
  1619. label: string; // auto-generated label, e.g. "AMS-A"
  1620. amsLabels?: Record<number, string>;
  1621. canEdit: boolean;
  1622. onSaved: () => void;
  1623. children: React.ReactNode;
  1624. }) {
  1625. const { t } = useTranslation();
  1626. const [isVisible, setIsVisible] = useState(false);
  1627. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1628. const [editValue, setEditValue] = useState('');
  1629. const [isSaving, setIsSaving] = useState(false);
  1630. const [saveError, setSaveError] = useState<string | null>(null);
  1631. const [isInputFocused, setIsInputFocused] = useState(false);
  1632. const triggerRef = useRef<HTMLDivElement>(null);
  1633. const cardRef = useRef<HTMLDivElement>(null);
  1634. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1635. useEffect(() => {
  1636. if (isVisible) {
  1637. setEditValue(amsLabels?.[ams.id] ?? '');
  1638. setSaveError(null);
  1639. requestAnimationFrame(() => {
  1640. if (triggerRef.current && cardRef.current) {
  1641. const rect = triggerRef.current.getBoundingClientRect();
  1642. const spaceAbove = rect.top - 56;
  1643. const spaceBelow = window.innerHeight - rect.bottom;
  1644. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1645. }
  1646. });
  1647. }
  1648. }, [isVisible, amsLabels, ams.id]);
  1649. const handleMouseEnter = () => {
  1650. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1651. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1652. };
  1653. const handleMouseLeave = () => {
  1654. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1655. if (!isInputFocused) {
  1656. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1657. }
  1658. };
  1659. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1660. const handleSave = async () => {
  1661. if (!canEdit) return;
  1662. setIsSaving(true);
  1663. setSaveError(null);
  1664. try {
  1665. const trimmed = editValue.trim();
  1666. if (trimmed) {
  1667. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1668. } else {
  1669. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1670. }
  1671. onSaved();
  1672. setIsVisible(false);
  1673. } catch (err) {
  1674. setSaveError(err instanceof Error ? err.message : String(err));
  1675. } finally {
  1676. setIsSaving(false);
  1677. }
  1678. };
  1679. const handleClear = async () => {
  1680. if (!canEdit) return;
  1681. setIsSaving(true);
  1682. setSaveError(null);
  1683. try {
  1684. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1685. onSaved();
  1686. setIsVisible(false);
  1687. } catch (err) {
  1688. setSaveError(err instanceof Error ? err.message : String(err));
  1689. } finally {
  1690. setIsSaving(false);
  1691. }
  1692. };
  1693. return (
  1694. <div
  1695. ref={triggerRef}
  1696. className="relative inline-block"
  1697. onMouseEnter={handleMouseEnter}
  1698. onMouseLeave={handleMouseLeave}
  1699. >
  1700. {children}
  1701. {isVisible && (
  1702. <div
  1703. ref={cardRef}
  1704. className={`
  1705. absolute left-0 z-50
  1706. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1707. animate-in fade-in-0 zoom-in-95 duration-150
  1708. `}
  1709. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1710. onMouseEnter={handleMouseEnter}
  1711. onMouseLeave={handleMouseLeave}
  1712. >
  1713. <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">
  1714. {/* AMS auto-label */}
  1715. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1716. {/* Serial number */}
  1717. <div className="flex items-center justify-between gap-2">
  1718. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1719. {t('printers.amsPopup.serialNumber')}
  1720. </span>
  1721. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1722. </div>
  1723. {/* Firmware version */}
  1724. <div className="flex items-center justify-between gap-2">
  1725. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1726. {t('printers.amsPopup.firmwareVersion')}
  1727. </span>
  1728. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1729. </div>
  1730. {/* Friendly name editor */}
  1731. <div className="space-y-1">
  1732. <div className="flex items-center gap-2">
  1733. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1734. {t('printers.amsPopup.friendlyName')}
  1735. </span>
  1736. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1737. </div>
  1738. <input
  1739. type="text"
  1740. value={editValue}
  1741. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1742. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1743. onFocus={() => setIsInputFocused(true)}
  1744. onBlur={() => {
  1745. setIsInputFocused(false);
  1746. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1747. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1748. }}
  1749. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1750. disabled={!canEdit}
  1751. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1752. 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"
  1753. maxLength={100}
  1754. />
  1755. {canEdit && (
  1756. <div className="space-y-1">
  1757. {saveError && (
  1758. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1759. )}
  1760. <div className="flex gap-1 justify-end">
  1761. <button
  1762. onClick={handleSave}
  1763. disabled={isSaving}
  1764. 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"
  1765. >
  1766. {t('printers.amsPopup.save')}
  1767. </button>
  1768. {amsLabels?.[ams.id] && (
  1769. <button
  1770. onClick={handleClear}
  1771. disabled={isSaving}
  1772. 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"
  1773. >
  1774. {t('printers.amsPopup.clear')}
  1775. </button>
  1776. )}
  1777. </div>
  1778. </div>
  1779. )}
  1780. </div>
  1781. </div>
  1782. </div>
  1783. )}
  1784. </div>
  1785. );
  1786. }
  1787. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1788. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1789. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1790. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1791. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1792. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1793. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1794. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1795. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1796. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1797. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1798. };
  1799. // How much the printer card's body type and icons grow at each card size
  1800. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1801. // 1.0 and an existing install looks identical until the user picks L or XL --
  1802. // the same control the request asked to have this follow.
  1803. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1804. // The scaled sizes, handed to the card subtree as custom properties. Every
  1805. // converted class names its old fixed value as the fallback, so anything that
  1806. // renders outside a card root -- the portalled temperature popover -- keeps
  1807. // exactly the size it has today.
  1808. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1809. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1810. // Rounded to a tenth so the values stay readable in devtools.
  1811. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1812. return {
  1813. '--pc-t8': px(8),
  1814. '--pc-t9': px(9),
  1815. '--pc-t10': px(10),
  1816. '--pc-t11': px(11),
  1817. '--pc-i2': px(8),
  1818. '--pc-i25': px(10),
  1819. '--pc-i3': px(12),
  1820. '--pc-i35': px(14),
  1821. '--pc-i4': px(16),
  1822. '--pc-i5': px(20),
  1823. '--pc-i7': px(28),
  1824. } as React.CSSProperties;
  1825. }
  1826. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1827. const { t } = useTranslation();
  1828. const queryClient = useQueryClient();
  1829. const { showToast } = useToast();
  1830. // One fleet-wide query shared by every card, not one per card: the list is
  1831. // nearly always empty and a 20-printer fleet would otherwise make 20
  1832. // requests every 30s. React Query dedupes on the key.
  1833. const { data: scheduled = [] } = useQuery({
  1834. queryKey: SCHEDULED_DRYINGS_KEY,
  1835. queryFn: () => api.listScheduledDryings(),
  1836. refetchInterval: 30_000,
  1837. });
  1838. // The live AMS status reports a starting cycle well before the next poll;
  1839. // refetch so a just-dispatched schedule doesn't linger as pending.
  1840. useEffect(() => {
  1841. if (dryingActive) {
  1842. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1843. }
  1844. }, [dryingActive, queryClient]);
  1845. const cancelMutation = useMutation({
  1846. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1847. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1848. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1849. });
  1850. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1851. // old firmware on a printer that was offline at schedule time), and without
  1852. // this the run just vanishes with only the backend log saying why.
  1853. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1854. if (rows.length === 0) return null;
  1855. return (
  1856. <div className="mt-2 space-y-1">
  1857. {rows.map(s => {
  1858. const failed = s.status === 'failed';
  1859. const reasonKey = waitingReasonKey(s.waiting_reason);
  1860. const failedKey = failedReasonKey(s.error_code);
  1861. return (
  1862. <div
  1863. key={s.id}
  1864. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1865. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1866. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1867. }`}
  1868. >
  1869. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1870. {failed ? (
  1871. t('printers.drying.scheduleFailedReason', {
  1872. reason: failedKey ? t(failedKey) : s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1873. })
  1874. ) : (
  1875. <>
  1876. {s.start_after
  1877. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1878. : t('printers.drying.scheduledAsap')}
  1879. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1880. </>
  1881. )}
  1882. </span>
  1883. <button
  1884. onClick={() => cancelMutation.mutate(s.id)}
  1885. disabled={cancelMutation.isPending}
  1886. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1887. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1888. >
  1889. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1890. </button>
  1891. </div>
  1892. );
  1893. })}
  1894. </div>
  1895. );
  1896. }
  1897. function PrinterCard({
  1898. printer,
  1899. hideIfDisconnected,
  1900. maintenanceInfo,
  1901. viewMode = 'expanded',
  1902. cardSize = 2,
  1903. amsThresholds,
  1904. spoolmanEnabled = false,
  1905. linkedSpools,
  1906. spoolmanUrl,
  1907. spoolmanSyncMode,
  1908. onGetAssignment,
  1909. onUnassignSpool,
  1910. spoolmanSpools,
  1911. spoolmanSlotAssignments,
  1912. spoolmanLoading = false,
  1913. onUnassignSpoolmanSpool,
  1914. timeFormat = 'system',
  1915. cameraViewMode = 'window',
  1916. onOpenEmbeddedCamera,
  1917. onSelectCameraViewMode,
  1918. checkPrinterFirmware = true,
  1919. dryingPresets = DRYING_PRESETS,
  1920. requirePlateClear = false,
  1921. selectionMode = false,
  1922. isSelected = false,
  1923. onToggleSelect,
  1924. onOpenCompactCard,
  1925. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1926. bedTempPresets = BED_TEMP_DEFAULTS,
  1927. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1928. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1929. aiDetectionEnabled = false,
  1930. aiDetection,
  1931. aiLastError = null,
  1932. }: {
  1933. printer: Printer;
  1934. hideIfDisconnected?: boolean;
  1935. maintenanceInfo?: PrinterMaintenanceInfo;
  1936. viewMode?: ViewMode;
  1937. cardSize?: number;
  1938. amsThresholds?: {
  1939. humidityGood: number;
  1940. humidityFair: number;
  1941. tempGood: number;
  1942. tempFair: number;
  1943. };
  1944. spoolmanEnabled?: boolean;
  1945. hasUnlinkedSpools?: boolean;
  1946. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1947. spoolmanUrl?: string | null;
  1948. spoolmanSyncMode?: string | null;
  1949. spoolAssignments?: SpoolAssignment[];
  1950. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1951. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1952. spoolmanSpools?: InventorySpool[];
  1953. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1954. spoolmanLoading?: boolean;
  1955. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1956. timeFormat?: 'system' | '12h' | '24h';
  1957. cameraViewMode?: CameraViewMode;
  1958. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1959. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1960. checkPrinterFirmware?: boolean;
  1961. dryingPresets?: Record<string, DryingPreset>;
  1962. requirePlateClear?: boolean;
  1963. selectionMode?: boolean;
  1964. isSelected?: boolean;
  1965. onToggleSelect?: (id: number) => void;
  1966. onOpenCompactCard?: (id: number) => void;
  1967. nozzleTempPresets?: readonly [number, number, number];
  1968. bedTempPresets?: readonly [number, number, number];
  1969. chamberTempPresets?: readonly [number, number, number];
  1970. fanSpeedPresets?: readonly [number, number, number];
  1971. aiDetectionEnabled?: boolean;
  1972. aiDetection?: AiDetection;
  1973. aiLastError?: string | null;
  1974. }) {
  1975. const { t } = useTranslation();
  1976. const queryClient = useQueryClient();
  1977. const navigate = useNavigate();
  1978. const { showToast } = useToast();
  1979. const { hasPermission, canModify } = useAuth();
  1980. const [showMenu, setShowMenu] = useState(false);
  1981. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1982. const [deleteArchives, setDeleteArchives] = useState(true);
  1983. const [showEditModal, setShowEditModal] = useState(false);
  1984. const [showFileManager, setShowFileManager] = useState(false);
  1985. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1986. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1987. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1988. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1989. const [showHMSModal, setShowHMSModal] = useState(false);
  1990. // #1546: AI failure detection modal — opens from the AI badge.
  1991. const [showAiModal, setShowAiModal] = useState(false);
  1992. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1993. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1994. // External spool visibility (#1782) — browser-local, per printer. Read once
  1995. // per card; the toggle that writes it is the only thing that changes it.
  1996. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  1997. isExternalSpoolHidden(printer.id),
  1998. );
  1999. const toggleExternalSpool = useCallback(() => {
  2000. setExternalSpoolHidden((prev) => {
  2001. const next = !prev;
  2002. persistExternalSpoolHidden(printer.id, next);
  2003. return next;
  2004. });
  2005. }, [printer.id]);
  2006. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2007. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2008. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2009. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2010. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2011. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2012. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2013. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2014. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2015. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2016. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2017. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2018. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2019. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2020. // AMS drying popover state: which AMS unit has the popover open
  2021. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2022. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2023. const [dryingFilament, setDryingFilament] = useState('PLA');
  2024. const [dryingTemp, setDryingTemp] = useState(50);
  2025. const [dryingDuration, setDryingDuration] = useState(4);
  2026. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2027. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2028. // go through scheduleDryingMutation.
  2029. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2030. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2031. const [dryingStartAt, setDryingStartAt] = useState('');
  2032. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2033. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2034. // Reset every field the popover owns, including the start mode. Leaving the
  2035. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2036. // the next open, by then in the past, and the POST rejected it.
  2037. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2038. const firstTray = ams.tray.find(t => t.tray_type);
  2039. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2040. // Only reachable if a custom preset set dropped PLA itself.
  2041. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2042. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2043. setDryingFilament(filType);
  2044. setDryingTemp(preset[moduleType] || preset.n3f);
  2045. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2046. setDryingRotateTray(false);
  2047. setDryingStartMode('now');
  2048. setDryingDelayMinutes(120);
  2049. setDryingStartAt('');
  2050. setDryingPopoverModuleType(ams.module_type);
  2051. setDryingPopoverAmsId(ams.id);
  2052. setDryingPopoverAnchor(trigger);
  2053. }, [dryingPresets]);
  2054. // Re-measure on resize/scroll so the popover and its arrow track the
  2055. // flame button, like IndicatorControlPopover.
  2056. useLayoutEffect(() => {
  2057. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2058. const measure = () => {
  2059. setDryingPopoverPos(computePopoverPosition({
  2060. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2061. popoverWidth: DRYING_POPOVER_WIDTH,
  2062. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2063. horizontalAlign: 'center',
  2064. }));
  2065. };
  2066. measure();
  2067. window.addEventListener('resize', measure);
  2068. window.addEventListener('scroll', measure, true);
  2069. return () => {
  2070. window.removeEventListener('resize', measure);
  2071. window.removeEventListener('scroll', measure, true);
  2072. };
  2073. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2074. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2075. // Whether the click hitting the backdrop is the one that dismissed the
  2076. // native datetime picker (see the backdrop's onMouseDown).
  2077. const dryingBackdropSkipCloseRef = useRef(false);
  2078. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2079. // an object rather than a bare id so restarting drying on the SAME unit produces
  2080. // a new identity and rearms the timeout below.
  2081. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2082. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2083. const [isDropUploading, setIsDropUploading] = useState(false);
  2084. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2085. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2086. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2087. // inside the card would have to open upward into the card body; anchored to
  2088. // the viewport it escapes the card and the grid's scroll container both.
  2089. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2090. const dragCounterRef = useRef(0);
  2091. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2092. amsId: number;
  2093. amsLabel: string;
  2094. mode: 'humidity' | 'temperature';
  2095. } | null>(null);
  2096. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2097. initialKind: HeaterSensorKind;
  2098. availableKinds: HeaterSensorKind[];
  2099. } | null>(null);
  2100. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2101. tagUid: string;
  2102. trayUuid: string;
  2103. printerId: number;
  2104. amsId: number;
  2105. trayId: number;
  2106. } | null>(null);
  2107. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2108. printerId: number;
  2109. amsId: number;
  2110. trayId: number;
  2111. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2112. } | null>(null);
  2113. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2114. amsId: number;
  2115. trayId: number;
  2116. trayCount: number;
  2117. trayType?: string;
  2118. trayColor?: string;
  2119. traySubBrands?: string;
  2120. trayInfoIdx?: string;
  2121. extruderId?: number;
  2122. caliIdx?: number | null;
  2123. savedPresetId?: string;
  2124. } | null>(null);
  2125. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2126. const [plateCheckResult, setPlateCheckResult] = useState<{
  2127. is_empty: boolean;
  2128. confidence: number;
  2129. difference_percent: number;
  2130. message: string;
  2131. debug_image_url?: string;
  2132. needs_calibration: boolean;
  2133. light_warning?: boolean;
  2134. reference_count?: number;
  2135. max_references?: number;
  2136. roi?: { x: number; y: number; w: number; h: number };
  2137. } | null>(null);
  2138. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2139. const [isCalibrating, setIsCalibrating] = useState(false);
  2140. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2141. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2142. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2143. const { data: status } = useQuery({
  2144. queryKey: ['printerStatus', printer.id],
  2145. queryFn: () => api.getPrinterStatus(printer.id),
  2146. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2147. });
  2148. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2149. const { data: firmwareInfo } = useQuery({
  2150. queryKey: ['firmwareUpdate', printer.id],
  2151. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2152. staleTime: 5 * 60 * 1000,
  2153. refetchInterval: 5 * 60 * 1000,
  2154. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2155. });
  2156. // Collect unique tray_info_idx values for cloud filament info lookup
  2157. const trayInfoIds = useMemo(() => {
  2158. const ids = new Set<string>();
  2159. if (status?.ams) {
  2160. for (const ams of status.ams) {
  2161. for (const tray of ams.tray || []) {
  2162. if (tray.tray_info_idx) {
  2163. ids.add(tray.tray_info_idx);
  2164. }
  2165. }
  2166. }
  2167. }
  2168. for (const vt of status?.vt_tray ?? []) {
  2169. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2170. }
  2171. if (status?.nozzle_rack) {
  2172. for (const slot of status.nozzle_rack) {
  2173. if (slot.filament_id) {
  2174. ids.add(slot.filament_id);
  2175. }
  2176. }
  2177. }
  2178. return Array.from(ids);
  2179. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2180. // Collect loaded filament types for queue widget filtering
  2181. const loadedFilamentTypes = useMemo(() => {
  2182. const types = new Set<string>();
  2183. if (status?.ams) {
  2184. for (const ams of status.ams) {
  2185. for (const tray of ams.tray || []) {
  2186. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2187. }
  2188. }
  2189. }
  2190. for (const vt of status?.vt_tray ?? []) {
  2191. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2192. }
  2193. return types;
  2194. }, [status?.ams, status?.vt_tray]);
  2195. // Collect loaded filament type+color pairs for queue widget override matching
  2196. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2197. const loadedFilaments = useMemo(() => {
  2198. const filaments = new Set<string>();
  2199. if (status?.ams) {
  2200. for (const ams of status.ams) {
  2201. for (const tray of ams.tray || []) {
  2202. if (tray.tray_type && tray.tray_color) {
  2203. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2204. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2205. }
  2206. }
  2207. }
  2208. }
  2209. for (const vt of status?.vt_tray ?? []) {
  2210. if (vt.tray_type && vt.tray_color) {
  2211. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2212. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2213. }
  2214. }
  2215. return filaments;
  2216. }, [status?.ams, status?.vt_tray]);
  2217. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2218. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2219. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2220. const loadedVariants = useMemo(() => {
  2221. const variants = new Set<string>();
  2222. if (status?.ams) {
  2223. for (const ams of status.ams) {
  2224. for (const tray of ams.tray || []) {
  2225. if (tray.tray_type && tray.tray_color) {
  2226. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2227. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. for (const vt of status?.vt_tray ?? []) {
  2233. if (vt.tray_type && vt.tray_color) {
  2234. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2235. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2236. }
  2237. }
  2238. return variants;
  2239. }, [status?.ams, status?.vt_tray]);
  2240. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2241. const { data: filamentInfo } = useQuery({
  2242. queryKey: ['filamentInfo', trayInfoIds],
  2243. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2244. enabled: trayInfoIds.length > 0,
  2245. staleTime: 5 * 60 * 1000, // 5 minutes
  2246. });
  2247. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2248. const { data: slotPresets } = useQuery({
  2249. queryKey: ['slotPresets', printer.id],
  2250. queryFn: () => api.getSlotPresets(printer.id),
  2251. staleTime: 2 * 60 * 1000, // 2 minutes
  2252. });
  2253. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2254. // Only queried when there's a running print backed by an archive; shared
  2255. // React Query cache with the Queue / Archives pages keeps it cheap.
  2256. const activeArchiveId =
  2257. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2258. const { data: activeArchivePlates } = useQuery({
  2259. queryKey: ['archive-plates', activeArchiveId],
  2260. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2261. enabled: activeArchiveId != null,
  2262. staleTime: 5 * 60 * 1000,
  2263. });
  2264. const activePlateLabel = (() => {
  2265. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2266. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2267. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2268. })();
  2269. // Fetch user-defined AMS friendly names from the database
  2270. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2271. queryKey: ['amsLabels', printer.id],
  2272. queryFn: () => api.getAmsLabels(printer.id),
  2273. staleTime: 5 * 60 * 1000, // 5 minutes
  2274. });
  2275. // Cache WiFi signal to prevent it disappearing on updates
  2276. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2277. useEffect(() => {
  2278. if (status?.wifi_signal != null) {
  2279. setCachedWifiSignal(status.wifi_signal);
  2280. }
  2281. }, [status?.wifi_signal]);
  2282. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2283. // Cache connected state to prevent flicker when status briefly becomes undefined
  2284. const cachedConnected = useRef<boolean | undefined>(undefined);
  2285. useEffect(() => {
  2286. if (status?.connected !== undefined) {
  2287. cachedConnected.current = status.connected;
  2288. }
  2289. }, [status?.connected]);
  2290. const isConnected = status?.connected ?? cachedConnected.current;
  2291. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2292. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2293. useEffect(() => {
  2294. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2295. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2296. }
  2297. }, [status?.ams_extruder_map]);
  2298. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2299. ? status.ams_extruder_map
  2300. : cachedAmsExtruderMap.current;
  2301. // Same caching for the Filament Track Switch inlet bindings, for the same
  2302. // reason: a partial MQTT frame briefly empties the map and the badges would
  2303. // otherwise blink out.
  2304. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2305. useEffect(() => {
  2306. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2307. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2308. }
  2309. }, [status?.ams_switch_inlet]);
  2310. const ftsInstalled = status?.fila_switch?.installed === true;
  2311. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2312. ? status.ams_switch_inlet
  2313. : cachedAmsSwitchInlet.current;
  2314. // Cache AMS data to prevent it disappearing on idle/offline printers
  2315. const cachedAmsData = useRef<AMSUnit[]>([]);
  2316. useEffect(() => {
  2317. if (status?.ams && status.ams.length > 0) {
  2318. cachedAmsData.current = status.ams;
  2319. }
  2320. }, [status?.ams]);
  2321. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2322. // #2532: the K-profile line only exists on slots the printer has actually
  2323. // calibrated. The AMS units and the external-spool group are flex siblings in
  2324. // one row, so on a card that shows a value anywhere, the slots without one
  2325. // reserve the same height -- otherwise their fill bars sit a line above their
  2326. // neighbours'. A card with no calibrated slot at all is unaffected.
  2327. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2328. || (status?.vt_tray ?? []).some(tray => tray.k);
  2329. // Confirm a drying cycle actually started (#2533). Firmware answers
  2330. // ams_filament_drying with result=success even when it then silently declines,
  2331. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2332. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2333. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2334. // means the printer took the command and dropped it.
  2335. useEffect(() => {
  2336. if (!dryStartWatch) return;
  2337. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2338. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2339. }, [dryStartWatch, amsData]);
  2340. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2341. // otherwise rearm the timeout on every frame, so it would never elapse.
  2342. useEffect(() => {
  2343. if (!dryStartWatch) return;
  2344. const timer = setTimeout(() => {
  2345. setDryStartWatch(null);
  2346. showToast(t('printers.drying.toastNotStarted'), 'error');
  2347. }, DRY_START_CONFIRM_MS);
  2348. return () => clearTimeout(timer);
  2349. }, [dryStartWatch, showToast, t]);
  2350. // Cache tray_now to prevent flickering when undefined values come in
  2351. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2352. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2353. const cachedTrayNow = useRef<number | undefined>(undefined);
  2354. const currentTrayNow = status?.tray_now;
  2355. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2356. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2357. cachedTrayNow.current = currentTrayNow;
  2358. } else if (currentTrayNow === 255) {
  2359. cachedTrayNow.current = undefined;
  2360. }
  2361. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2362. ? currentTrayNow
  2363. : cachedTrayNow.current;
  2364. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2365. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2366. // expectedTray = the slot the firmware now expects filament in
  2367. // previousTray = the slot that ran out
  2368. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2369. // so these are often different — the graphic highlights the expected one.
  2370. const expectedTray = status?.expected_tray ?? null;
  2371. const previousTray = status?.previous_tray ?? null;
  2372. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2373. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2374. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2375. if (globalId === null) return null;
  2376. if (globalId === 254) return t('printers.expectedSlot.external');
  2377. if (globalId >= 128 && globalId <= 135) {
  2378. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2379. }
  2380. const amsId = Math.floor(globalId / 4);
  2381. const slot = globalId % 4;
  2382. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2383. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2384. };
  2385. const runoutGuidance = status?.state === 'PAUSE'
  2386. ? {
  2387. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2388. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2389. }
  2390. : null;
  2391. // Fetch smart plug for this printer
  2392. const { data: smartPlug } = useQuery({
  2393. queryKey: ['smartPlugByPrinter', printer.id],
  2394. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2395. });
  2396. // Fetch script plugs for this printer (for multi-device control)
  2397. const { data: scriptPlugs } = useQuery({
  2398. queryKey: ['scriptPlugsByPrinter', printer.id],
  2399. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2400. });
  2401. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2402. const { data: plugStatus } = useQuery({
  2403. queryKey: ['smartPlugStatus', smartPlug?.id],
  2404. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2405. enabled: !!smartPlug,
  2406. refetchInterval: 10000, // 10 seconds for real-time power display
  2407. });
  2408. // Fetch queue count for this printer
  2409. const { data: queueItems } = useQuery({
  2410. queryKey: ['queue', printer.id, 'pending'],
  2411. queryFn: () => api.getQueue(printer.id, 'pending'),
  2412. });
  2413. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2414. // so the badge only shows on printers that can actually run the queued jobs.
  2415. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2416. const queueCount = useMemo(() => {
  2417. if (!queueItems?.length) return 0;
  2418. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2419. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2420. // Fetch currently printing queue item to show who started it (Issue #206)
  2421. const { data: printingQueueItems } = useQuery({
  2422. queryKey: ['queue', printer.id, 'printing'],
  2423. queryFn: () => api.getQueue(printer.id, 'printing'),
  2424. enabled: status?.state === 'RUNNING',
  2425. });
  2426. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2427. const { data: reprintUser } = useQuery({
  2428. queryKey: ['currentPrintUser', printer.id],
  2429. queryFn: () => api.getCurrentPrintUser(printer.id),
  2430. enabled: status?.state === 'RUNNING',
  2431. });
  2432. // Combine both sources: queue item user takes precedence, then reprint user
  2433. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2434. // Fetch last completed print for this printer
  2435. const { data: lastPrints } = useQuery({
  2436. queryKey: ['archives', printer.id, 'last'],
  2437. queryFn: () => api.getArchives(printer.id, 1, 0),
  2438. enabled: status?.connected && status?.state !== 'RUNNING',
  2439. });
  2440. const lastPrint = lastPrints?.[0];
  2441. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2442. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2443. // Post-print outcome confirmation on the card (#1898): while the plate-clear
  2444. // gate is up and the just-finished print asked for a verdict, offer
  2445. // Good/Reject right where the operator releases the plate. Releasing the
  2446. // plate without answering stays possible — the two are orthogonal (though
  2447. // the confirm_default_good_on_plate_clear setting can couple them).
  2448. // Only offered to whoever may record it: the PATCH checks archives:update
  2449. // against the archive's owner, so for anyone else the pair could only fail.
  2450. const pendingConfirmArchive =
  2451. lastPrint &&
  2452. lastPrint.status === 'completed' &&
  2453. lastPrint.confirm_requested &&
  2454. lastPrint.user_verdict == null &&
  2455. canModify('archives', 'update', lastPrint.created_by_id)
  2456. ? lastPrint
  2457. : null;
  2458. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2459. // Auto Power Off the printer is powered down exactly when the operator clears the
  2460. // plate. Hiding the control there left no way to release the gate (#2864).
  2461. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2462. const activePrintName = status?.current_print && isPrintingOrPaused
  2463. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2464. : null;
  2465. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2466. useEffect(() => {
  2467. if (activePrintName) {
  2468. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2469. } else if (!needsPlateClear) {
  2470. setRetainedPrintJob(null);
  2471. }
  2472. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2473. const plateStatus = (() => {
  2474. // Connected-only because the pill's only render site sits inside the live-status
  2475. // panel. For a powered-down printer the plate-clear button itself carries the
  2476. // state — see the standalone slot below the status block (#2864).
  2477. if (!requirePlateClear || !status?.connected) return null;
  2478. if (isPrintingOrPaused) {
  2479. return {
  2480. label: t('printers.plateStatus.inUse'),
  2481. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2482. };
  2483. }
  2484. if (status.awaiting_plate_clear) {
  2485. return {
  2486. label: t('printers.plateStatus.notCleared'),
  2487. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2488. };
  2489. }
  2490. return {
  2491. label: t('printers.plateStatus.cleared'),
  2492. className: 'bg-status-ok/20 text-status-ok',
  2493. };
  2494. })();
  2495. const plateStatusPill = plateStatus ? (
  2496. <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}`}>
  2497. {plateStatus.label}
  2498. </span>
  2499. ) : null;
  2500. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2501. const shouldHide = hideIfDisconnected && isConnected === false;
  2502. const deleteMutation = useMutation({
  2503. mutationFn: (options: { deleteArchives: boolean }) =>
  2504. api.deletePrinter(printer.id, options.deleteArchives),
  2505. onSuccess: () => {
  2506. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2507. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2508. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2509. },
  2510. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2511. });
  2512. const connectMutation = useMutation({
  2513. mutationFn: () => api.connectPrinter(printer.id),
  2514. onSuccess: () => {
  2515. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2516. },
  2517. });
  2518. const forceRefreshMutation = useMutation({
  2519. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2520. onSuccess: () => {
  2521. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2522. showToast(t('printers.forceRefreshSuccess'), 'success');
  2523. },
  2524. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2525. });
  2526. const unlinkSpoolMutation = useMutation({
  2527. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2528. onSuccess: (result) => {
  2529. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2530. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2531. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2532. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2533. },
  2534. onError: (error: Error) => {
  2535. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2536. },
  2537. });
  2538. // AMS drying mutations
  2539. const startDryingMutation = useMutation({
  2540. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2541. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2542. onSuccess: (_data, { amsId }) => {
  2543. setDryingPopoverAmsId(null);
  2544. setDryStartWatch({ amsId });
  2545. // "Command sent", not "drying started" — at this point the printer has only
  2546. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2547. // the cycle is genuinely live; the watcher below covers the case where it
  2548. // never appears.
  2549. showToast(t('printers.drying.toastCommandSent'), 'success');
  2550. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2551. },
  2552. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2553. });
  2554. // Scheduled (delayed / at-time) drying runs (#2638)
  2555. const scheduleDryingMutation = useMutation({
  2556. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2557. api.createScheduledDrying({
  2558. printer_id: printer.id,
  2559. ams_id: params.amsId,
  2560. temp: params.temp,
  2561. duration_hours: params.duration,
  2562. filament: params.filament,
  2563. rotate_tray: params.rotateTray,
  2564. start_after: params.startAfter,
  2565. }),
  2566. onSuccess: () => {
  2567. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2568. setDryingPopoverAmsId(null);
  2569. },
  2570. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2571. });
  2572. const stopDryingMutation = useMutation({
  2573. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2574. onSuccess: () => {
  2575. setDryStartWatch(null);
  2576. showToast(t('printers.drying.toastStopped'), 'success');
  2577. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2578. },
  2579. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2580. });
  2581. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2582. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2583. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2584. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2585. // showing the old backup state until the user reopens it.
  2586. const setAmsBackupMutation = useMutation({
  2587. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2588. onSuccess: (_data, enabled) => {
  2589. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2590. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2591. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2592. },
  2593. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2594. });
  2595. // Smart plug control mutations
  2596. const powerControlMutation = useMutation({
  2597. mutationFn: (action: 'on' | 'off') =>
  2598. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2599. onSuccess: () => {
  2600. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2601. },
  2602. });
  2603. const toggleAutoOffMutation = useMutation({
  2604. mutationFn: (enabled: boolean) =>
  2605. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2606. onSuccess: () => {
  2607. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2608. // Also invalidate the smart-plugs list to keep Settings page in sync
  2609. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2610. },
  2611. });
  2612. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2613. const runScriptMutation = useMutation({
  2614. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2615. onSuccess: () => {
  2616. showToast(t('printers.toast.scriptTriggered'));
  2617. },
  2618. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2619. });
  2620. // Print control mutations
  2621. const stopPrintMutation = useMutation({
  2622. mutationFn: () => api.stopPrint(printer.id),
  2623. onSuccess: () => {
  2624. showToast(t('printers.toast.printStopped'));
  2625. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2626. },
  2627. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2628. });
  2629. const pausePrintMutation = useMutation({
  2630. mutationFn: () => api.pausePrint(printer.id),
  2631. onSuccess: () => {
  2632. showToast(t('printers.toast.printPaused'));
  2633. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2634. },
  2635. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2636. });
  2637. const resumePrintMutation = useMutation({
  2638. mutationFn: () => api.resumePrint(printer.id),
  2639. onSuccess: () => {
  2640. showToast(t('printers.toast.printResumed'));
  2641. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2642. },
  2643. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2644. });
  2645. const clearPlateMutation = useMutation({
  2646. mutationFn: () => api.clearPlate(printer.id),
  2647. onSuccess: () => {
  2648. showToast(t('queue.clearPlateSuccess'));
  2649. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2650. old ? { ...old, awaiting_plate_clear: false } : old
  2651. );
  2652. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2653. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2654. },
  2655. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2656. });
  2657. // Post-print outcome confirmation (#1898): one-tap "good" from the card,
  2658. // reject goes through the dialog for the optional reason + reprint.
  2659. const [showConfirmOutcome, setShowConfirmOutcome] = useState(false);
  2660. // Only "good" is answered on the card. A reject wants a reason and possibly
  2661. // a reprint, so that button opens the dialog instead — and the parameter
  2662. // says as much, rather than accepting a verdict this path cannot send and
  2663. // then reporting it as good.
  2664. const cardVerdictMutation = useMutation({
  2665. mutationFn: (verdict: 'good') =>
  2666. api.updateArchive(pendingConfirmArchive!.id, {
  2667. user_verdict: verdict,
  2668. user_verdict_source: 'printer_card',
  2669. }),
  2670. onSuccess: () => {
  2671. showToast(t('confirmOutcome.savedGood'), 'success');
  2672. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2673. },
  2674. onError: (error: Error) => showToast(error.message || t('confirmOutcome.saveFailed'), 'error'),
  2675. });
  2676. // Rendered from two places: inside the live-status block for a connected printer,
  2677. // and standalone below it for a powered-down one, whose status block isn't rendered
  2678. // at all (#2864). Shared so the two can't drift apart.
  2679. const expandedClearPlateButton = (
  2680. <>
  2681. {pendingConfirmArchive && (
  2682. <div className="mt-2 flex items-center gap-1.5">
  2683. <span
  2684. className="flex-1 min-w-0 truncate text-xs text-bambu-gray"
  2685. title={pendingConfirmArchive.print_name || pendingConfirmArchive.filename}
  2686. >
  2687. {t('confirmOutcome.cardPrompt')}
  2688. </span>
  2689. <button
  2690. type="button"
  2691. onClick={() => setShowConfirmOutcome(true)}
  2692. disabled={cardVerdictMutation.isPending}
  2693. className="p-1.5 rounded-lg border border-red-500/40 text-red-500 hover:bg-red-500/10 transition-colors"
  2694. title={t('confirmOutcome.reject')}
  2695. >
  2696. <ThumbsDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2697. </button>
  2698. <button
  2699. type="button"
  2700. onClick={() => cardVerdictMutation.mutate('good')}
  2701. disabled={cardVerdictMutation.isPending}
  2702. className="p-1.5 rounded-lg border border-bambu-green/50 text-bambu-green hover:bg-bambu-green/10 transition-colors"
  2703. title={t('confirmOutcome.good')}
  2704. >
  2705. <ThumbsUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2706. </button>
  2707. </div>
  2708. )}
  2709. <button
  2710. type="button"
  2711. onClick={() => clearPlateMutation.mutate()}
  2712. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2713. 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"
  2714. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2715. >
  2716. {clearPlateMutation.isPending ? (
  2717. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2718. ) : (
  2719. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2720. )}
  2721. {t('printers.plateStatus.markCleared')}
  2722. </button>
  2723. {showConfirmOutcome && pendingConfirmArchive && (
  2724. <ConfirmOutcomeDialog
  2725. archiveId={pendingConfirmArchive.id}
  2726. onClose={() => setShowConfirmOutcome(false)}
  2727. />
  2728. )}
  2729. </>
  2730. );
  2731. const nozzleTemperatureMutation = useMutation({
  2732. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2733. api.setNozzleTemperature(printer.id, target, nozzle),
  2734. onSuccess: (result) => {
  2735. setStatusControlMenu(null);
  2736. showToast(result.message);
  2737. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2738. },
  2739. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2740. });
  2741. const bedTemperatureMutation = useMutation({
  2742. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2743. onSuccess: (result) => {
  2744. setStatusControlMenu(null);
  2745. showToast(result.message);
  2746. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2747. },
  2748. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2749. });
  2750. const chamberTemperatureMutation = useMutation({
  2751. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2752. onSuccess: (result) => {
  2753. setStatusControlMenu(null);
  2754. showToast(result.message);
  2755. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2756. },
  2757. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2758. });
  2759. const fanSpeedMutation = useMutation({
  2760. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2761. api.setFanSpeed(printer.id, fan, speed),
  2762. onMutate: async ({ fan, speed }) => {
  2763. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2764. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2765. const fanField = {
  2766. part: 'cooling_fan_speed',
  2767. aux: 'big_fan1_speed',
  2768. aux2: 'left_aux_fan_speed',
  2769. chamber: 'big_fan2_speed',
  2770. }[fan];
  2771. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2772. old ? { ...old, [fanField]: speed } : old
  2773. );
  2774. return { previousStatus };
  2775. },
  2776. onSuccess: (result) => {
  2777. setStatusControlMenu(null);
  2778. showToast(result.message);
  2779. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2780. },
  2781. onError: (error: Error, _variables, context) => {
  2782. if (context?.previousStatus) {
  2783. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2784. }
  2785. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2786. },
  2787. });
  2788. const selectExtruderMutation = useMutation({
  2789. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2790. onMutate: async (extruder) => {
  2791. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2792. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2793. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2794. old ? { ...old, active_extruder: extruder } : old
  2795. );
  2796. return { previousStatus };
  2797. },
  2798. onSuccess: (result) => {
  2799. setStatusControlMenu(null);
  2800. showToast(result.message);
  2801. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2802. },
  2803. onError: (error: Error, _extruder, context) => {
  2804. if (context?.previousStatus) {
  2805. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2806. }
  2807. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2808. },
  2809. });
  2810. // Chamber light mutation with optimistic update
  2811. const chamberLightMutation = useMutation({
  2812. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2813. onMutate: async (on) => {
  2814. // Cancel any outgoing refetches
  2815. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2816. // Snapshot the previous value
  2817. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2818. // Optimistically update
  2819. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2820. ...old,
  2821. chamber_light: on,
  2822. }));
  2823. return { previousStatus };
  2824. },
  2825. onSuccess: (_, on) => {
  2826. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2827. },
  2828. onError: (error: Error, _, context) => {
  2829. // Rollback on error
  2830. if (context?.previousStatus) {
  2831. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2832. }
  2833. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2834. },
  2835. });
  2836. // Print speed mutation with optimistic update
  2837. const printSpeedMutation = useMutation({
  2838. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2839. onMutate: async (mode) => {
  2840. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2841. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2842. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2843. ...old,
  2844. speed_level: mode,
  2845. }));
  2846. return { previousStatus };
  2847. },
  2848. onError: (error: Error, _, context) => {
  2849. if (context?.previousStatus) {
  2850. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2851. }
  2852. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2853. },
  2854. });
  2855. const airductMutation = useMutation({
  2856. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2857. onMutate: async (mode) => {
  2858. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2859. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2860. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2861. ...old,
  2862. airduct_mode: mode === 'cooling' ? 0 : 1,
  2863. }));
  2864. return { previousStatus };
  2865. },
  2866. onError: (error: Error, _, context) => {
  2867. if (context?.previousStatus) {
  2868. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2869. }
  2870. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2871. },
  2872. });
  2873. const bedJogMutation = useMutation({
  2874. mutationFn: ({ distance }: { distance: number }) =>
  2875. api.bedJog(printer.id, distance),
  2876. onError: (error: Error) =>
  2877. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2878. });
  2879. const xyJogMutation = useMutation({
  2880. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2881. api.xyJog(printer.id, x, y),
  2882. onError: (error: Error) =>
  2883. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2884. });
  2885. const extruderJogMutation = useMutation({
  2886. mutationFn: (distance: number) =>
  2887. api.extruderJog(printer.id, distance),
  2888. onError: (error: Error) =>
  2889. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2890. });
  2891. const homeAxesMutation = useMutation({
  2892. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2893. onSuccess: () => {
  2894. showToast(t('printers.bedJog.homingStarted'));
  2895. },
  2896. onError: (error: Error) =>
  2897. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2898. });
  2899. // Plate detection setting mutation
  2900. const plateDetectionMutation = useMutation({
  2901. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2902. onSuccess: () => {
  2903. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2904. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2905. },
  2906. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2907. });
  2908. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2909. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2910. // metrics, and the print picker — so flipping this flag puts the printer
  2911. // out of service across every consumer in one place. Used from the
  2912. // overflow menu and EditPrinterModal.
  2913. const maintenanceMutation = useMutation({
  2914. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2915. onSuccess: (_data, isActive) => {
  2916. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2917. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2918. showToast(
  2919. isActive
  2920. ? t('printers.maintenance.toastExited', { name: printer.name })
  2921. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2922. 'success',
  2923. );
  2924. },
  2925. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2926. });
  2927. // Confirm before entering maintenance on a printing printer (entering mode
  2928. // disconnects MQTT, which stops progress tracking + completion notifications
  2929. // for the in-flight job).
  2930. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2931. const handleEnterMaintenance = () => {
  2932. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2933. setConfirmMaintenanceEnter(true);
  2934. } else {
  2935. maintenanceMutation.mutate(false);
  2936. }
  2937. };
  2938. // Query for printable objects (for skip functionality)
  2939. // Fetch when printing with 2+ objects OR when modal is open
  2940. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2941. const { data: objectsData } = useQuery({
  2942. queryKey: ['printableObjects', printer.id],
  2943. queryFn: () => api.getPrintableObjects(printer.id),
  2944. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2945. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2946. });
  2947. // State for tracking which AMS slot is being refreshed
  2948. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2949. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2950. const seenBusyStateRef = useRef<boolean>(false);
  2951. // Fallback timeout ref
  2952. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2953. // Minimum display time passed
  2954. const minTimePassedRef = useRef<boolean>(false);
  2955. // AMS slot refresh mutation
  2956. const refreshAmsSlotMutation = useMutation({
  2957. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2958. api.refreshAmsSlot(printer.id, amsId, slotId),
  2959. onMutate: ({ amsId, slotId }) => {
  2960. // Clear any existing timeout
  2961. if (refreshTimeoutRef.current) {
  2962. clearTimeout(refreshTimeoutRef.current);
  2963. }
  2964. // Reset state
  2965. seenBusyStateRef.current = false;
  2966. minTimePassedRef.current = false;
  2967. setRefreshingSlot({ amsId, slotId });
  2968. // Minimum display time (2 seconds)
  2969. setTimeout(() => {
  2970. minTimePassedRef.current = true;
  2971. }, 2000);
  2972. // Fallback timeout (30 seconds max)
  2973. refreshTimeoutRef.current = setTimeout(() => {
  2974. setRefreshingSlot(null);
  2975. }, 30000);
  2976. },
  2977. onSuccess: (data) => {
  2978. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2979. },
  2980. onError: (error: Error) => {
  2981. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2982. if (refreshTimeoutRef.current) {
  2983. clearTimeout(refreshTimeoutRef.current);
  2984. }
  2985. setRefreshingSlot(null);
  2986. },
  2987. });
  2988. // AMS load/unload mutations (#891)
  2989. const loadAmsTrayMutation = useMutation({
  2990. mutationFn: ({ trayId, extruderId }: { trayId: number; extruderId?: number }) =>
  2991. api.loadAmsTray(printer.id, trayId, extruderId),
  2992. onSuccess: (data) => {
  2993. setFeedDirectionRequest(null);
  2994. showToast(data.message || t('printers.toast.loadInitiated'));
  2995. },
  2996. onError: (error: Error) => {
  2997. setFeedDirectionRequest(null);
  2998. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2999. },
  3000. });
  3001. const unloadAmsMutation = useMutation({
  3002. mutationFn: ({ trayId }: { trayId?: number }) => api.unloadAms(printer.id, trayId),
  3003. onSuccess: (data) => {
  3004. showToast(data.message || t('printers.toast.unloadInitiated'));
  3005. },
  3006. onError: (error: Error) => {
  3007. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  3008. },
  3009. });
  3010. // Pending "which hotend?" question, non-null only while the dialog is open.
  3011. // A Filament Track Switch makes both hotends reachable from every slot, so the
  3012. // load command has to name one — see FeedDirectionModal.
  3013. const [feedDirectionRequest, setFeedDirectionRequest] = useState<{
  3014. trayId: number;
  3015. amsId: number;
  3016. slotId: number;
  3017. slotLabel: string;
  3018. } | null>(null);
  3019. // Whether a load from this printer has to ask which hotend to feed.
  3020. const ftsNeedsFeedDirection = Boolean(status?.fila_switch?.installed);
  3021. const startAmsLoad = (amsId: number, slotId: number, trayId: number) => {
  3022. // The external holder needs no question: its two tray ids name the side
  3023. // outright (254 = Ext-L, 255 = Ext-R). A switch cannot be fitted alongside
  3024. // it anyway — Bambu's own guidance is to remove the switch to print from an
  3025. // external spool, because it would occupy an extruder channel permanently.
  3026. //
  3027. // An AMS-HT slot skips the question for a blunter reason: the id this menu
  3028. // carries does not address an HT unit, so the load is refused whatever the
  3029. // answer. Asking first would only put a dialog in front of the same error.
  3030. const isExternal = amsId === 255;
  3031. if (!ftsNeedsFeedDirection || isExternal || amsId >= 128) {
  3032. loadAmsTrayMutation.mutate({ trayId });
  3033. return;
  3034. }
  3035. // Nothing can be routed until every AMS is bound to an inlet, so refuse up
  3036. // front rather than sending a command the firmware will drop. BambuStudio
  3037. // shows the same message and returns without publishing anything.
  3038. if (!status?.fila_switch?.ready) {
  3039. showToast(t('printers.ams.switchNotReady'), 'warning');
  3040. return;
  3041. }
  3042. setFeedDirectionRequest({
  3043. trayId,
  3044. amsId,
  3045. slotId,
  3046. slotLabel: formatSlotLabel(amsId, slotId, false, false),
  3047. });
  3048. };
  3049. // Plate references state
  3050. const [plateReferences, setPlateReferences] = useState<{
  3051. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  3052. max_references: number;
  3053. } | null>(null);
  3054. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  3055. // Fetch plate references
  3056. const fetchPlateReferences = async () => {
  3057. try {
  3058. const data = await api.getPlateReferences(printer.id);
  3059. setPlateReferences(data);
  3060. } catch {
  3061. // Ignore errors - references will show as empty
  3062. }
  3063. };
  3064. // Toggle plate detection enabled/disabled
  3065. const handleTogglePlateDetection = () => {
  3066. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3067. };
  3068. // Open plate detection management modal (for calibration/references)
  3069. const handleOpenPlateManagement = async () => {
  3070. setIsCheckingPlate(true);
  3071. setPlateCheckResult(null);
  3072. // Auto-turn on light if it's off
  3073. const lightWasOff = status?.chamber_light === false;
  3074. setPlateCheckLightWasOff(lightWasOff);
  3075. if (lightWasOff) {
  3076. await api.setChamberLight(printer.id, true);
  3077. // Wait for light to physically turn on and camera to adjust exposure
  3078. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3079. await new Promise(resolve => setTimeout(resolve, 2500));
  3080. }
  3081. try {
  3082. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3083. setPlateCheckResult(result);
  3084. fetchPlateReferences();
  3085. } catch (error) {
  3086. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3087. // Restore light if check failed
  3088. if (lightWasOff) {
  3089. await api.setChamberLight(printer.id, false);
  3090. setPlateCheckLightWasOff(false);
  3091. }
  3092. } finally {
  3093. setIsCheckingPlate(false);
  3094. }
  3095. };
  3096. // Close plate check modal and restore light state
  3097. const closePlateCheckModal = useCallback(async () => {
  3098. setPlateCheckResult(null);
  3099. // Restore light to original state if we turned it on
  3100. if (plateCheckLightWasOff) {
  3101. await api.setChamberLight(printer.id, false);
  3102. setPlateCheckLightWasOff(false);
  3103. }
  3104. }, [plateCheckLightWasOff, printer.id]);
  3105. // Calibrate plate detection handler
  3106. const handleCalibratePlate = async (label?: string) => {
  3107. setIsCalibrating(true);
  3108. try {
  3109. const result = await api.calibratePlateDetection(printer.id, { label });
  3110. if (result.success) {
  3111. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3112. // Refresh references and re-check
  3113. fetchPlateReferences();
  3114. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3115. setPlateCheckResult(checkResult);
  3116. } else {
  3117. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3118. }
  3119. } catch (error) {
  3120. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3121. } finally {
  3122. setIsCalibrating(false);
  3123. }
  3124. };
  3125. // Update reference label
  3126. const handleUpdateRefLabel = async (index: number, label: string) => {
  3127. try {
  3128. await api.updatePlateReferenceLabel(printer.id, index, label);
  3129. setEditingRefLabel(null);
  3130. fetchPlateReferences();
  3131. } catch (error) {
  3132. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3133. }
  3134. };
  3135. // Delete reference
  3136. const handleDeleteRef = async (index: number) => {
  3137. try {
  3138. await api.deletePlateReference(printer.id, index);
  3139. showToast(t('printers.toast.referenceDeleted'), 'success');
  3140. fetchPlateReferences();
  3141. // Re-check to update counts
  3142. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3143. setPlateCheckResult(checkResult);
  3144. } catch (error) {
  3145. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3146. }
  3147. };
  3148. // Save ROI settings
  3149. const handleSaveRoi = async () => {
  3150. if (!editingRoi) return;
  3151. setIsSavingRoi(true);
  3152. try {
  3153. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3154. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3155. setEditingRoi(null);
  3156. // Re-check to see new ROI in action
  3157. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3158. setPlateCheckResult(checkResult);
  3159. } catch (error) {
  3160. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3161. } finally {
  3162. setIsSavingRoi(false);
  3163. }
  3164. };
  3165. // Close plate check modal on Escape key
  3166. useEffect(() => {
  3167. const handleEscape = (e: KeyboardEvent) => {
  3168. if (e.key === 'Escape' && plateCheckResult) {
  3169. closePlateCheckModal();
  3170. }
  3171. };
  3172. window.addEventListener('keydown', handleEscape);
  3173. return () => window.removeEventListener('keydown', handleEscape);
  3174. }, [plateCheckResult, closePlateCheckModal]);
  3175. // Watch ams_status_main to detect when RFID read completes
  3176. // ams_status_main: 0=idle, 2=rfid_identifying
  3177. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3178. useEffect(() => {
  3179. if (!refreshingSlot) return;
  3180. const amsStatus = status?.ams_status_main ?? 0;
  3181. // Track when we see non-idle state (printer is working)
  3182. if (amsStatus !== 0) {
  3183. seenBusyStateRef.current = true;
  3184. // Cancel any deferred clear since we're back to busy
  3185. if (deferredClearRef.current) {
  3186. clearTimeout(deferredClearRef.current);
  3187. deferredClearRef.current = null;
  3188. }
  3189. }
  3190. // When we've seen busy and now idle, clear (with min time check)
  3191. if (seenBusyStateRef.current && amsStatus === 0) {
  3192. if (minTimePassedRef.current) {
  3193. // Min time passed - clear now
  3194. if (refreshTimeoutRef.current) {
  3195. clearTimeout(refreshTimeoutRef.current);
  3196. }
  3197. setRefreshingSlot(null);
  3198. } else {
  3199. // Schedule clear after min time (2 seconds from start)
  3200. if (!deferredClearRef.current) {
  3201. deferredClearRef.current = setTimeout(() => {
  3202. if (refreshTimeoutRef.current) {
  3203. clearTimeout(refreshTimeoutRef.current);
  3204. }
  3205. setRefreshingSlot(null);
  3206. }, 2000);
  3207. }
  3208. }
  3209. }
  3210. return () => {
  3211. if (deferredClearRef.current) {
  3212. clearTimeout(deferredClearRef.current);
  3213. }
  3214. };
  3215. }, [status?.ams_status_main, refreshingSlot]);
  3216. useEffect(() => {
  3217. if (!showMenu) return;
  3218. const handleClickOutside = (event: MouseEvent) => {
  3219. const target = event.target as Node;
  3220. if (!printerActionsMenuRef.current?.contains(target)) {
  3221. setShowMenu(false);
  3222. }
  3223. };
  3224. document.addEventListener('mousedown', handleClickOutside);
  3225. return () => document.removeEventListener('mousedown', handleClickOutside);
  3226. }, [showMenu]);
  3227. if (shouldHide) {
  3228. return null;
  3229. }
  3230. // Size-based styling helpers
  3231. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3232. // width, its thumbnail and the printer name, but every label inside the
  3233. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3234. // S one -- the disparity was worst exactly where someone asking for more
  3235. // room ends up. These custom properties carry the scaled sizes into the
  3236. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3237. // unless they reach for a size that is already asking for more space.
  3238. // Plain computation rather than useMemo: this sits after the card's early
  3239. // returns, where a hook would break the rules-of-hooks ordering, and
  3240. // building ten strings per render costs nothing.
  3241. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3242. const getImageSize = () => {
  3243. switch (cardSize) {
  3244. case 1: return 'w-10 h-10';
  3245. case 2: return 'w-14 h-14';
  3246. case 3: return 'w-16 h-16';
  3247. case 4: return 'w-20 h-20';
  3248. default: return 'w-14 h-14';
  3249. }
  3250. };
  3251. const getTitleSize = () => {
  3252. switch (cardSize) {
  3253. case 1: return 'text-base truncate';
  3254. case 2: return 'text-lg';
  3255. case 3: return 'text-xl';
  3256. case 4: return 'text-2xl';
  3257. default: return 'text-lg';
  3258. }
  3259. };
  3260. const getSpacing = () => {
  3261. switch (cardSize) {
  3262. case 1: return 'mb-2';
  3263. case 2: return 'mb-4';
  3264. case 3: return 'mb-5';
  3265. case 4: return 'mb-6';
  3266. default: return 'mb-4';
  3267. }
  3268. };
  3269. // A dropped file always becomes a queue item, so a printer that is busy,
  3270. // offline or mid-drying is no reason to refuse the drop — it only means the
  3271. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3272. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3273. // what this would have done for them.
  3274. //
  3275. // What remains is what the flow actually performs: upload the file, then
  3276. // create a queue item. It never touches printers:control, which is what this
  3277. // used to check — so someone holding that but neither of these had the file
  3278. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3279. // button below has always checked this pair.
  3280. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3281. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3282. // and the modal's own "will start later" toast cannot disagree.
  3283. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3284. const handleCardDragEnter = (e: React.DragEvent) => {
  3285. e.preventDefault();
  3286. dragCounterRef.current++;
  3287. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3288. };
  3289. const handleCardDragOver = (e: React.DragEvent) => {
  3290. e.preventDefault();
  3291. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3292. };
  3293. const handleCardDragLeave = (e: React.DragEvent) => {
  3294. e.preventDefault();
  3295. dragCounterRef.current--;
  3296. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3297. };
  3298. const handleCardDrop = async (e: React.DragEvent) => {
  3299. e.preventDefault();
  3300. dragCounterRef.current = 0;
  3301. setIsDraggingFile(false);
  3302. if (!canDrop) return;
  3303. const droppedFiles = Array.from(e.dataTransfer.files);
  3304. const file = droppedFiles[0];
  3305. if (!file) return;
  3306. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3307. const lower = file.name.toLowerCase();
  3308. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3309. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3310. return;
  3311. }
  3312. setIsDropUploading(true);
  3313. try {
  3314. const result = await api.uploadLibraryFile(file, null);
  3315. // Check printer compatibility if sliced_for_model is available in metadata
  3316. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3317. const printerModel = mapModelCode(printer.model);
  3318. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3319. await api.deleteLibraryFile(result.id).catch(() => {});
  3320. showToast(
  3321. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3322. 'error'
  3323. );
  3324. return;
  3325. }
  3326. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3327. } catch {
  3328. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3329. } finally {
  3330. setIsDropUploading(false);
  3331. }
  3332. };
  3333. const handleCardClick = (e: React.MouseEvent) => {
  3334. if (viewMode !== 'compact' || selectionMode) return;
  3335. const target = e.target as HTMLElement;
  3336. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3337. onOpenCompactCard?.(printer.id);
  3338. };
  3339. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3340. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3341. // Opening a camera in a given mode, without touching which mode is remembered
  3342. // -- the split button's two halves want the same action but disagree about
  3343. // whether the choice was deliberate enough to keep.
  3344. const openCameraIn = (mode: CameraViewMode) => {
  3345. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3346. onOpenEmbeddedCamera(printer.id, printer.name);
  3347. } else {
  3348. openCameraWindow(printer.id);
  3349. }
  3350. };
  3351. // Picking a mode both opens the camera that way and makes it the mode the
  3352. // plain icon uses from now on. A menu that only changed a preference would
  3353. // leave the user with a second click to do the thing they already asked for.
  3354. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3355. [
  3356. {
  3357. mode: 'window' as const,
  3358. icon: <ExternalLink className="w-4 h-4" />,
  3359. label: t('settings.newWindow'),
  3360. title: t('settings.cameraWindowDescription'),
  3361. },
  3362. {
  3363. mode: 'embedded' as const,
  3364. icon: <PictureInPicture2 className="w-4 h-4" />,
  3365. label: t('settings.embeddedOverlay'),
  3366. title: t('settings.cameraOverlayDescription'),
  3367. },
  3368. ]
  3369. ).map(({ mode, icon, label, title }) => ({
  3370. icon,
  3371. // The remembered mode is marked in the label itself: the icon slot already
  3372. // carries the mode's own icon, and a separate tick column would push both
  3373. // entries out of line with every other card menu.
  3374. label: mode === cameraViewMode ? `${label} ✓` : label,
  3375. title,
  3376. onClick: () => {
  3377. onSelectCameraViewMode?.(mode);
  3378. openCameraIn(mode);
  3379. },
  3380. }));
  3381. const renderAmsSlotActions = ({
  3382. amsId,
  3383. slotId,
  3384. loadTrayId,
  3385. isRefreshing,
  3386. includeRfid = true,
  3387. }: {
  3388. amsId: number;
  3389. slotId: number;
  3390. loadTrayId: number;
  3391. isRefreshing?: boolean;
  3392. includeRfid?: boolean;
  3393. }) => {
  3394. const printerBusy = status?.state === 'RUNNING';
  3395. // An AMS-HT unit is addressed by its unit id alone (128-135), not by
  3396. // ams*4+slot, so the id this menu carries does not name it to the load and
  3397. // unload endpoints — they reject it. Sending no slot falls back to the
  3398. // printer-wide unload, which is what this menu did for every slot before
  3399. // the per-slot form existed. Load has never worked on an HT slot for the
  3400. // same addressing reason; fixing that is a separate change.
  3401. const unloadTrayId = amsId >= 128 && amsId !== 255 ? undefined : loadTrayId;
  3402. return (
  3403. <>
  3404. {includeRfid && (
  3405. <button
  3406. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3407. hasPermission('printers:ams_rfid')
  3408. ? 'text-white hover:bg-bambu-dark-tertiary'
  3409. : 'text-bambu-gray/50 cursor-not-allowed'
  3410. }`}
  3411. onClick={(e) => {
  3412. e.stopPropagation();
  3413. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3414. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3415. }}
  3416. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3417. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3418. >
  3419. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3420. {t('printers.rfid.reread')}
  3421. </button>
  3422. )}
  3423. <button
  3424. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3425. hasPermission('printers:control')
  3426. ? 'text-white hover:bg-bambu-dark-tertiary'
  3427. : 'text-bambu-gray/50 cursor-not-allowed'
  3428. }`}
  3429. onClick={(e) => {
  3430. e.stopPropagation();
  3431. if (printerBusy || !hasPermission('printers:control')) return;
  3432. startAmsLoad(amsId, slotId, loadTrayId);
  3433. }}
  3434. disabled={printerBusy || !hasPermission('printers:control')}
  3435. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3436. >
  3437. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3438. {t('printers.ams.load')}
  3439. </button>
  3440. <button
  3441. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3442. hasPermission('printers:control')
  3443. ? 'text-white hover:bg-bambu-dark-tertiary'
  3444. : 'text-bambu-gray/50 cursor-not-allowed'
  3445. }`}
  3446. onClick={(e) => {
  3447. e.stopPropagation();
  3448. if (printerBusy || !hasPermission('printers:control')) return;
  3449. unloadAmsMutation.mutate({ trayId: unloadTrayId });
  3450. }}
  3451. disabled={printerBusy || !hasPermission('printers:control')}
  3452. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3453. >
  3454. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3455. {t('printers.ams.unload')}
  3456. </button>
  3457. </>
  3458. );
  3459. };
  3460. const printerActionsMenu = (
  3461. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3462. <Button
  3463. variant="secondary"
  3464. size="sm"
  3465. onClick={() => setShowMenu(!showMenu)}
  3466. title={t('common.more', 'More')}
  3467. className={footerIconButtonClass}
  3468. >
  3469. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3470. </Button>
  3471. {showMenu && (
  3472. <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">
  3473. <button
  3474. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3475. hasPermission('printers:update')
  3476. ? 'hover:bg-bambu-dark-tertiary'
  3477. : 'opacity-50 cursor-not-allowed'
  3478. }`}
  3479. onClick={() => {
  3480. if (!hasPermission('printers:update')) return;
  3481. setShowEditModal(true);
  3482. setShowMenu(false);
  3483. }}
  3484. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3485. >
  3486. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3487. {t('common.edit')}
  3488. </button>
  3489. <button
  3490. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3491. onClick={() => {
  3492. setShowPrinterInfo(true);
  3493. setShowMenu(false);
  3494. }}
  3495. >
  3496. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3497. {t('printers.printerInformation')}
  3498. </button>
  3499. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3500. <button
  3501. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3502. hasPermission('printers:update')
  3503. ? 'hover:bg-bambu-dark-tertiary'
  3504. : 'opacity-50 cursor-not-allowed'
  3505. }`}
  3506. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3507. onClick={() => {
  3508. if (!hasPermission('printers:update')) return;
  3509. setShowMenu(false);
  3510. if (printer.is_active !== false) {
  3511. handleEnterMaintenance();
  3512. } else {
  3513. maintenanceMutation.mutate(true);
  3514. }
  3515. }}
  3516. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3517. >
  3518. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3519. {printer.is_active !== false
  3520. ? t('printers.maintenance.menuEnter')
  3521. : t('printers.maintenance.menuExit')}
  3522. </button>
  3523. <button
  3524. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3525. onClick={() => {
  3526. connectMutation.mutate();
  3527. setShowMenu(false);
  3528. }}
  3529. >
  3530. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3531. {t('printers.reconnect')}
  3532. </button>
  3533. <button
  3534. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3535. disabled={forceRefreshMutation.isPending}
  3536. onClick={() => {
  3537. forceRefreshMutation.mutate();
  3538. setShowMenu(false);
  3539. }}
  3540. >
  3541. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3542. {t('printers.forceRefresh')}
  3543. </button>
  3544. <button
  3545. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3546. onClick={() => {
  3547. setShowMQTTDebug(true);
  3548. setShowMenu(false);
  3549. }}
  3550. >
  3551. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3552. {t('printers.mqttDebug')}
  3553. </button>
  3554. <button
  3555. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3556. onClick={() => {
  3557. setShowDiagnostic(true);
  3558. setShowMenu(false);
  3559. }}
  3560. >
  3561. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3562. {t('diagnostic.runButton')}
  3563. </button>
  3564. <button
  3565. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3566. hasPermission('printers:delete')
  3567. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3568. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3569. }`}
  3570. onClick={() => {
  3571. if (!hasPermission('printers:delete')) return;
  3572. setShowDeleteConfirm(true);
  3573. setShowMenu(false);
  3574. }}
  3575. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3576. >
  3577. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3578. {t('common.delete')}
  3579. </button>
  3580. </div>
  3581. )}
  3582. </div>
  3583. );
  3584. return (
  3585. <Card
  3586. id={`printer-card-${printer.id}`}
  3587. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3588. style={cardScaleStyle}
  3589. onClick={handleCardClick}
  3590. onDragEnter={handleCardDragEnter}
  3591. onDragOver={handleCardDragOver}
  3592. onDragLeave={handleCardDragLeave}
  3593. onDrop={handleCardDrop}
  3594. >
  3595. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3596. {selectionMode && (
  3597. <div
  3598. className="absolute inset-0 z-20 flex items-start p-2"
  3599. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3600. >
  3601. {isSelected ? (
  3602. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3603. ) : (
  3604. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3605. )}
  3606. </div>
  3607. )}
  3608. {/* Drop zone overlay */}
  3609. {(isDraggingFile || isDropUploading) && (
  3610. <div
  3611. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3612. isDropUploading
  3613. ? 'bg-bambu-green/10 border-bambu-green/50'
  3614. : canDrop
  3615. ? 'bg-bambu-green/10 border-bambu-green'
  3616. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3617. }`}
  3618. >
  3619. <div className="text-center">
  3620. {isDropUploading ? (
  3621. <>
  3622. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3623. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3624. </>
  3625. ) : canDrop ? (
  3626. <>
  3627. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3628. <p className="text-sm font-medium text-bambu-green">
  3629. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3630. </p>
  3631. </>
  3632. ) : (
  3633. <>
  3634. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3635. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3636. {!hasPermission('library:upload')
  3637. ? t('fileManager.noPermissionUpload')
  3638. : t('fileManager.noPermissionAddToQueue')}
  3639. </p>
  3640. </>
  3641. )}
  3642. </div>
  3643. </div>
  3644. )}
  3645. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3646. {/* Header */}
  3647. <div className={getSpacing()}>
  3648. {/* Top row: Image, Name, Menu */}
  3649. <div className="flex items-start justify-between gap-2">
  3650. <div className="flex items-center gap-3 min-w-0 flex-1">
  3651. {/* Printer Model Image */}
  3652. <img
  3653. src={getPrinterImage(printer.model)}
  3654. alt={printer.model || t('common.printer')}
  3655. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3656. />
  3657. <div className="min-w-0 flex-1">
  3658. <div className="flex items-center justify-between gap-2">
  3659. <div className="flex min-w-0 items-center gap-2">
  3660. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3661. {/* Connection indicator dot for compact mode */}
  3662. {viewMode === 'compact' && (() => {
  3663. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3664. const hasSevere = hmsErrors.some(isSevereHMSError);
  3665. const hasWarning = hmsErrors.length > 0;
  3666. const pipColor = !status?.connected
  3667. ? 'bg-status-error'
  3668. : hasSevere
  3669. ? 'bg-status-error'
  3670. : hasWarning
  3671. ? 'bg-status-warning'
  3672. : 'bg-status-ok';
  3673. const pipTitle = !status?.connected
  3674. ? t('printers.connection.offline')
  3675. : hasWarning
  3676. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3677. : t('printers.connection.connected');
  3678. return (
  3679. <div
  3680. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3681. title={pipTitle}
  3682. />
  3683. );
  3684. })()}
  3685. </div>
  3686. {viewMode === 'compact' && showClearPlateButton && (
  3687. <button
  3688. type="button"
  3689. onClick={() => clearPlateMutation.mutate()}
  3690. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3691. aria-label={t('printers.plateStatus.markCleared')}
  3692. 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"
  3693. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3694. >
  3695. {clearPlateMutation.isPending ? (
  3696. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3697. ) : (
  3698. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3699. )}
  3700. </button>
  3701. )}
  3702. </div>
  3703. <p className="text-sm text-bambu-gray">
  3704. {printer.model || 'Unknown Model'}
  3705. {/* Nozzle Info - only in expanded. Every fitted size, not
  3706. just nozzles[0]: the array is indexed by extruder, so on a
  3707. dual-nozzle machine with two sizes fitted showing the
  3708. first entry alone named one hotend and implied it was the
  3709. whole printer. Deduplicated, so the usual matching pair
  3710. still reads as a single "0.4mm". */}
  3711. {viewMode === 'expanded' && installedNozzleDiameters(status).length > 0 && (
  3712. <span className="ml-1.5 text-bambu-gray" title={status?.nozzles?.[0]?.nozzle_type || 'Nozzle'}>
  3713. • {installedNozzleDiameters(status).join(' / ')}mm
  3714. </span>
  3715. )}
  3716. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3717. <span className="ml-2 text-bambu-gray">
  3718. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3719. {Math.round(maintenanceInfo.total_print_hours)}h
  3720. </span>
  3721. )}
  3722. </p>
  3723. </div>
  3724. </div>
  3725. </div>
  3726. {/* Badges row - only in expanded mode */}
  3727. {viewMode === 'expanded' && (
  3728. <div className="mt-2">
  3729. <div className="flex flex-wrap items-center gap-2">
  3730. {/* Connection status badge (or Maintenance pill when out of service).
  3731. Defensive: only swap when is_active is EXPLICITLY false. An
  3732. undefined / missing field defaults to "active" so the regular
  3733. pill renders — matches the backend default and prevents test
  3734. fixtures (or stale clients) from accidentally tripping the
  3735. maintenance UI. */}
  3736. {printer.is_active === false ? (
  3737. <span
  3738. 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"
  3739. title={t('printers.maintenance.subtitle')}
  3740. >
  3741. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3742. {t('printers.maintenance.pillLabel')}
  3743. </span>
  3744. ) : (
  3745. <span
  3746. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3747. status?.connected
  3748. ? 'bg-status-ok/20 text-status-ok'
  3749. : 'bg-status-error/20 text-status-error'
  3750. }`}
  3751. >
  3752. {status?.connected ? (
  3753. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3754. ) : (
  3755. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3756. )}
  3757. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3758. </span>
  3759. )}
  3760. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3761. {printer.is_active !== false && !status?.connected && (
  3762. <button
  3763. onClick={() => setShowDiagnostic(true)}
  3764. 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"
  3765. title={t('diagnostic.runButton')}
  3766. >
  3767. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3768. {t('diagnostic.runButton')}
  3769. </button>
  3770. )}
  3771. {/* Network connection indicator */}
  3772. {status?.connected && status?.wired_network && (
  3773. <span
  3774. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3775. title={t('printers.connection.ethernet', 'Ethernet')}
  3776. >
  3777. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3778. {t('printers.connection.ethernet', 'Ethernet')}
  3779. </span>
  3780. )}
  3781. {/* WiFi signal indicator */}
  3782. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3783. <span
  3784. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3785. wifiSignal >= -50
  3786. ? 'bg-status-ok/20 text-status-ok'
  3787. : wifiSignal >= -60
  3788. ? 'bg-status-ok/20 text-status-ok'
  3789. : wifiSignal >= -70
  3790. ? 'bg-status-warning/20 text-status-warning'
  3791. : wifiSignal >= -80
  3792. ? 'bg-orange-500/20 text-orange-600'
  3793. : 'bg-status-error/20 text-status-error'
  3794. }`}
  3795. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3796. >
  3797. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3798. {wifiSignal}dBm
  3799. </span>
  3800. )}
  3801. {/* HMS Status Indicator */}
  3802. {status?.connected && (() => {
  3803. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3804. return (
  3805. <button
  3806. onClick={() => setShowHMSModal(true)}
  3807. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3808. knownErrors.length > 0
  3809. ? knownErrors.some(isSevereHMSError)
  3810. ? 'bg-status-error/20 text-status-error'
  3811. : 'bg-status-warning/20 text-status-warning'
  3812. : 'bg-status-ok/20 text-status-ok'
  3813. }`}
  3814. title={t('printers.clickToViewHmsErrors')}
  3815. >
  3816. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3817. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3818. </button>
  3819. );
  3820. })()}
  3821. {/* AI failure detection badge (#1546) — always shown while detection
  3822. is enabled for this printer, like the other health badges. Gray
  3823. "Idle" outside a monitored print, class-colored during one. */}
  3824. {aiDetectionEnabled && (() => {
  3825. const cls = aiDetectionClass(aiDetection);
  3826. const colorClass =
  3827. cls === 'failure'
  3828. ? 'bg-status-error/20 text-status-error'
  3829. : cls === 'warning'
  3830. ? 'bg-status-warning/20 text-status-warning'
  3831. : cls === 'safe'
  3832. ? 'bg-status-ok/20 text-status-ok'
  3833. : cls === 'error'
  3834. ? 'bg-amber-500/20 text-amber-600 dark:text-amber-400'
  3835. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3836. // 'error' and 'unknown' have no score to quote — saying
  3837. // "Safe (0.000)" for a print nothing is looking at is the
  3838. // whole of #2952.
  3839. const title =
  3840. cls === 'error'
  3841. ? t('printers.aiDetection.tooltipError', {
  3842. reason: aiDetection?.error ?? t('printers.aiDetection.error'),
  3843. })
  3844. : cls === 'unknown'
  3845. ? t('printers.aiDetection.tooltipUnknown')
  3846. : aiDetection
  3847. ? t('printers.aiDetection.tooltip', {
  3848. status: t(`printers.aiDetection.${cls}`),
  3849. score: aiDetection.score.toFixed(3),
  3850. })
  3851. : t('printers.aiDetection.tooltipIdle');
  3852. const Icon = cls === 'error' ? EyeOff : ScanEye;
  3853. return (
  3854. <button
  3855. onClick={() => setShowAiModal(true)}
  3856. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3857. title={title}
  3858. >
  3859. <Icon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3860. {t(`printers.aiDetection.${cls}`)}
  3861. </button>
  3862. );
  3863. })()}
  3864. {/* Maintenance Status Indicator */}
  3865. {maintenanceInfo && (
  3866. <button
  3867. onClick={() => navigate('/maintenance')}
  3868. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3869. maintenanceInfo.due_count > 0
  3870. ? 'bg-status-error/20 text-status-error'
  3871. : maintenanceInfo.warning_count > 0
  3872. ? 'bg-status-warning/20 text-status-warning'
  3873. : 'bg-status-ok/20 text-status-ok'
  3874. }`}
  3875. title={
  3876. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3877. ? `${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`
  3878. : t('printers.maintenanceUpToDate')
  3879. }
  3880. >
  3881. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3882. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3883. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3884. : 'OK'}
  3885. </button>
  3886. )}
  3887. {/* Queue Count Badge */}
  3888. {queueCount > 0 && (
  3889. <button
  3890. onClick={() => navigate('/queue')}
  3891. 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"
  3892. title={t('printers.queue.inQueue', { count: queueCount })}
  3893. >
  3894. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3895. {queueCount}
  3896. </button>
  3897. )}
  3898. {/* Firmware Version Badge */}
  3899. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3900. <button
  3901. onClick={() => setShowFirmwareModal(true)}
  3902. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3903. firmwareInfo.update_available
  3904. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3905. : 'bg-status-ok/20 text-status-ok'
  3906. }`}
  3907. title={
  3908. firmwareInfo.update_available
  3909. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3910. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3911. }
  3912. >
  3913. {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)]" />}
  3914. {firmwareInfo.current_version}
  3915. </button>
  3916. ) : status?.firmware_version ? (
  3917. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3918. {status.firmware_version}
  3919. </span>
  3920. ) : null}
  3921. {/* Enclosure Door Badge — models with an actual door sensor.
  3922. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3923. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3924. <span
  3925. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3926. status.door_open
  3927. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3928. : 'bg-status-ok/20 text-status-ok'
  3929. }`}
  3930. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3931. >
  3932. {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)]" />}
  3933. </span>
  3934. )}
  3935. </div>
  3936. </div>
  3937. )}
  3938. </div>
  3939. {/* Delete Confirmation */}
  3940. {showDeleteConfirm && (
  3941. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3942. <Card className="w-full max-w-md mx-4">
  3943. <CardContent>
  3944. <div className="flex items-start gap-3 mb-4">
  3945. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3946. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3947. </div>
  3948. <div>
  3949. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3950. <p className="text-sm text-bambu-gray mt-1">
  3951. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3952. </p>
  3953. </div>
  3954. </div>
  3955. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3956. <label className="flex items-start gap-3 cursor-pointer">
  3957. <input
  3958. type="checkbox"
  3959. checked={deleteArchives}
  3960. onChange={(e) => setDeleteArchives(e.target.checked)}
  3961. 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"
  3962. />
  3963. <div>
  3964. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3965. <p className="text-xs text-bambu-gray mt-0.5">
  3966. {deleteArchives
  3967. ? t('printers.confirm.deleteArchivesNote')
  3968. : t('printers.confirm.keepArchivesNote')}
  3969. </p>
  3970. </div>
  3971. </label>
  3972. </div>
  3973. <div className="flex justify-end gap-2">
  3974. <Button
  3975. variant="secondary"
  3976. onClick={() => {
  3977. setShowDeleteConfirm(false);
  3978. setDeleteArchives(true);
  3979. }}
  3980. >
  3981. {t('common.cancel')}
  3982. </Button>
  3983. <Button
  3984. variant="danger"
  3985. onClick={() => {
  3986. deleteMutation.mutate({ deleteArchives });
  3987. setShowDeleteConfirm(false);
  3988. setDeleteArchives(true);
  3989. }}
  3990. >
  3991. Delete
  3992. </Button>
  3993. </div>
  3994. </CardContent>
  3995. </Card>
  3996. </div>
  3997. )}
  3998. {/* Status — see the equivalent defensive `=== false` check on the
  3999. header pill above for why this is not `!printer.is_active`. */}
  4000. {printer.is_active === false ? (
  4001. // Maintenance mode (#1476) — replaces the cover/progress container
  4002. // so the card keeps the same height. Renders for both compact and
  4003. // expanded view modes so the printer stays visible but plainly
  4004. // out-of-service.
  4005. <>
  4006. {viewMode === 'compact' ? (
  4007. <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">
  4008. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4009. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  4010. {t('printers.maintenance.pillLabel')}
  4011. </span>
  4012. </div>
  4013. ) : (
  4014. <>
  4015. <div className="flex items-center gap-2 mb-2">
  4016. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4017. {t('printers.status.title', 'Status')}
  4018. </span>
  4019. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4020. </div>
  4021. <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">
  4022. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  4023. <div className="flex-1 min-w-0">
  4024. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  4025. {t('printers.maintenance.title')}
  4026. </p>
  4027. <p className="text-xs text-bambu-gray mt-0.5">
  4028. {t('printers.maintenance.subtitle')}
  4029. </p>
  4030. </div>
  4031. <Button
  4032. variant="secondary"
  4033. size="sm"
  4034. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  4035. onClick={() => maintenanceMutation.mutate(true)}
  4036. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  4037. >
  4038. {t('printers.maintenance.exitButton')}
  4039. </Button>
  4040. </div>
  4041. </>
  4042. )}
  4043. </>
  4044. ) : status?.connected && (
  4045. <>
  4046. {/* Compact: Simple status bar */}
  4047. {viewMode === 'compact' ? (
  4048. (() => {
  4049. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  4050. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  4051. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  4052. ? Math.max(0, Math.min(100, status.progress || 0))
  4053. : showClearPlateButton
  4054. ? 100
  4055. : hasProblem
  4056. ? 100
  4057. : 0;
  4058. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  4059. const compactProgressClass = hasProblem
  4060. ? 'bg-status-error'
  4061. : status.state === 'PAUSE'
  4062. ? 'bg-status-warning'
  4063. : 'bg-bambu-green';
  4064. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  4065. const hasCompactLayers =
  4066. isActiveCompactPrint &&
  4067. status.layer_num != null &&
  4068. status.total_layers != null &&
  4069. status.total_layers > 0;
  4070. return (
  4071. <>
  4072. <div className="relative mt-2 flex items-center gap-2">
  4073. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  4074. <div
  4075. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  4076. style={{ width: `${compactProgress}%` }}
  4077. />
  4078. </div>
  4079. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  4080. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  4081. </span>
  4082. </div>
  4083. {/* #2674: size S showed only a name, a pip and a progress bar — not
  4084. enough to answer "which printer finishes first", which is what a
  4085. wall-mounted fleet view is for. One line of the metrics the
  4086. expanded card already renders, using the same formatters and the
  4087. same ETA styling so S and M read alike. The row keeps its height
  4088. when idle so cards don't shift as prints start and stop. */}
  4089. <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">
  4090. {hasCompactEta && (
  4091. <>
  4092. <span className="flex shrink-0 items-center gap-1">
  4093. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4094. {formatDuration(status.remaining_time! * 60)}
  4095. </span>
  4096. <span
  4097. className="shrink-0 font-medium text-bambu-green"
  4098. title={t('printers.estimatedCompletion')}
  4099. >
  4100. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4101. </span>
  4102. </>
  4103. )}
  4104. {hasCompactLayers && (
  4105. <span className="flex min-w-0 items-center gap-1 truncate">
  4106. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4107. {status.layer_num}/{status.total_layers}
  4108. </span>
  4109. )}
  4110. </div>
  4111. </>
  4112. );
  4113. })()
  4114. ) : (
  4115. /* Expanded: Full status section */
  4116. <>
  4117. <div className="flex items-center gap-2 mb-2">
  4118. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4119. {t('printers.status.title', 'Status')}
  4120. </span>
  4121. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4122. </div>
  4123. {/* Current Print or Idle Placeholder */}
  4124. {(() => {
  4125. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4126. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4127. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4128. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4129. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4130. // A running print always has at least one object, so a count of
  4131. // zero means "not loaded", not "nothing to skip" — after a
  4132. // restart mid-print the list is empty until something rebuilds
  4133. // it. Treating that as nothing-to-skip disabled the only
  4134. // control that opens the modal, and the modal's own fetch is
  4135. // what rebuilds the list, so the print could never get it back.
  4136. // Exactly one object is the real nothing-to-skip case.
  4137. const objectCount = status.printable_objects_count ?? 0;
  4138. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4139. return (
  4140. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4141. <button
  4142. onClick={() => setShowSkipObjectsModal(true)}
  4143. disabled={!canSkipObjects}
  4144. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4145. canSkipObjects
  4146. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4147. : 'text-bambu-gray/30 cursor-not-allowed'
  4148. }`}
  4149. title={
  4150. !hasPermission('printers:control')
  4151. ? t('printers.permission.noControl')
  4152. : !isActivePrint
  4153. ? t('printers.skipObjects.onlyWhilePrinting')
  4154. : objectCount === 1
  4155. ? t('printers.skipObjects.requiresMultiple')
  4156. : t('printers.skipObjects.tooltip')
  4157. }
  4158. >
  4159. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4160. {objectsData && objectsData.skipped_count > 0 && (
  4161. <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">
  4162. {objectsData.skipped_count}
  4163. </span>
  4164. )}
  4165. </button>
  4166. <div className="flex items-stretch gap-2">
  4167. <CoverImage
  4168. url={coverUrl}
  4169. printName={printName || undefined}
  4170. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4171. />
  4172. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4173. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4174. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4175. {plateStatusPill}
  4176. </div>
  4177. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4178. {printName || t('printers.noActiveJob', 'No active job')}
  4179. </p>
  4180. <div className="flex h-3 items-center gap-2 text-sm">
  4181. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4182. <div
  4183. 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`}
  4184. style={{ width: `${progress}%` }}
  4185. />
  4186. </div>
  4187. <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>
  4188. </div>
  4189. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4190. {isActivePrint ? (
  4191. <>
  4192. {status.remaining_time != null && status.remaining_time > 0 && (
  4193. <>
  4194. <span className="flex items-center gap-1">
  4195. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4196. {formatDuration(status.remaining_time * 60)}
  4197. </span>
  4198. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4199. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4200. </span>
  4201. </>
  4202. )}
  4203. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4204. <span className="flex items-center gap-1">
  4205. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4206. {status.layer_num}/{status.total_layers}
  4207. </span>
  4208. )}
  4209. {currentPrintUser && (
  4210. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4211. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4212. {currentPrintUser}
  4213. </span>
  4214. )}
  4215. </>
  4216. ) : lastPrint ? (
  4217. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4218. Last: {lastPrint.print_name || lastPrint.filename}
  4219. {lastPrint.completed_at && (
  4220. <span className="ml-1 text-bambu-gray/60">
  4221. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4222. </span>
  4223. )}
  4224. </p>
  4225. ) : (
  4226. <span>{t('printers.readyToPrint')}</span>
  4227. )}
  4228. </div>
  4229. </div>
  4230. </div>
  4231. <PrinterQueueWidget
  4232. printerId={printer.id}
  4233. printerModel={printer.model}
  4234. loadedFilamentTypes={loadedFilamentTypes}
  4235. loadedFilaments={loadedFilaments}
  4236. loadedVariants={loadedVariants}
  4237. variant="panelExtension"
  4238. />
  4239. </div>
  4240. );
  4241. })()}
  4242. </>
  4243. )}
  4244. {/* Temperatures */}
  4245. {status.temperatures && viewMode === 'expanded' && (() => {
  4246. // Use actual heater states from MQTT stream
  4247. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4248. const bedHeating = status.temperatures.bed_heating || false;
  4249. const chamberHeating = status.temperatures.chamber_heating || false;
  4250. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4251. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4252. const kinds: HeaterSensorKind[] = ['nozzle'];
  4253. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4254. kinds.push('bed');
  4255. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4256. return kinds;
  4257. })();
  4258. // active_extruder: 0=right, 1=left
  4259. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4260. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4261. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4262. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4263. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4264. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4265. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4266. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4267. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4268. 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 ${
  4269. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4270. }`;
  4271. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4272. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4273. // the widget there is at best dead UI and at worst suggests a
  4274. // control that does nothing. Mirrors the enclosure-door badge
  4275. // gate above.
  4276. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4277. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4278. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4279. // show it only when the printer actually reports it (airduct part id 3,
  4280. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4281. // have a built-in chamber fan that's always present, so they keep the
  4282. // existing model-list gate and the "Chamber Fan" label.
  4283. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4284. const chamberFanLabel = isExhaustModel
  4285. ? t('printers.fans.exhaust')
  4286. : t('printers.fans.chamber');
  4287. // Composed rather than either/or so both lists stay live for
  4288. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4289. // where that fan is an add-on kit — actually report it. Written
  4290. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4291. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4292. // which reads as if removing them were safe.
  4293. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4294. const fanItems: {
  4295. key: string;
  4296. label: string;
  4297. value: number;
  4298. Icon: typeof Fan;
  4299. activeClass: string;
  4300. }[] = [
  4301. {
  4302. key: 'part',
  4303. label: t('printers.fans.partCooling'),
  4304. value: status.cooling_fan_speed ?? 0,
  4305. Icon: Fan,
  4306. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4307. },
  4308. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4309. // Only reported (non-null) when the firmware lists airduct part
  4310. // id 10, i.e. when the fan is physically installed. Placed
  4311. // before the right-hand auxiliary fan so the two aux badges read
  4312. // left-to-right in the same order as the physical hardware.
  4313. ...(status.left_aux_fan_speed != null
  4314. ? [
  4315. {
  4316. key: 'aux2',
  4317. label: t('printers.fans.leftAuxiliary'),
  4318. value: status.left_aux_fan_speed,
  4319. Icon: Wind,
  4320. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4321. },
  4322. ]
  4323. : []),
  4324. {
  4325. key: 'aux',
  4326. label: t('printers.fans.auxiliary'),
  4327. value: status.big_fan1_speed ?? 0,
  4328. Icon: Wind,
  4329. activeClass: 'text-blue-600 dark:text-blue-400',
  4330. },
  4331. ...(showChamberFan
  4332. ? [
  4333. {
  4334. key: 'chamber',
  4335. label: chamberFanLabel,
  4336. value: status.big_fan2_speed ?? 0,
  4337. Icon: AirVent,
  4338. activeClass: 'text-green-600 dark:text-green-400',
  4339. },
  4340. ]
  4341. : []),
  4342. ];
  4343. return (
  4344. <>
  4345. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4346. {/* Nozzle temp - combined for dual nozzle */}
  4347. <div
  4348. className={statusControlClass}
  4349. title={statusControlTitle}
  4350. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4351. >
  4352. <button
  4353. type="button"
  4354. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4355. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4356. onClick={(e) => {
  4357. e.stopPropagation();
  4358. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4359. }}
  4360. >
  4361. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4362. </button>
  4363. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4364. {status.temperatures.nozzle_2 !== undefined ? (
  4365. <>
  4366. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4367. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4368. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4369. </p>
  4370. </>
  4371. ) : singleNozzleSlot ? (
  4372. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4373. <div className="cursor-default">
  4374. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4375. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4376. {Math.round(status.temperatures.nozzle || 0)}°C
  4377. </p>
  4378. </div>
  4379. </NozzleSlotHoverCard>
  4380. ) : (
  4381. <>
  4382. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4383. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4384. {Math.round(status.temperatures.nozzle || 0)}°C
  4385. </p>
  4386. </>
  4387. )}
  4388. {statusControlMenu === 'nozzle-temp' && (
  4389. isDualNozzle ? (
  4390. <IndicatorControlPopover
  4391. title="Set Nozzle Temperatures"
  4392. widthClass="w-[300px]"
  4393. popoverWidth={300}
  4394. popoverHeight={260}
  4395. isPending={nozzleTemperatureMutation.isPending}
  4396. onClose={() => setStatusControlMenu(null)}
  4397. >
  4398. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4399. <NozzleTemperatureControlBox
  4400. label="Left Temp"
  4401. current={status.temperatures.nozzle}
  4402. target={status.temperatures.nozzle_target}
  4403. isActive={activeNozzle === 'L'}
  4404. isPending={nozzleTemperatureMutation.isPending}
  4405. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4406. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4407. />
  4408. <NozzleTemperatureControlBox
  4409. label="Right Temp"
  4410. current={status.temperatures.nozzle_2}
  4411. target={status.temperatures.nozzle_2_target}
  4412. isActive={activeNozzle === 'R'}
  4413. isPending={nozzleTemperatureMutation.isPending}
  4414. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4415. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4416. />
  4417. </div>
  4418. </IndicatorControlPopover>
  4419. ) : (
  4420. <IndicatorControlPopover
  4421. title="Set Nozzle Temperature"
  4422. unit="°C"
  4423. customMin={0}
  4424. customMax={320}
  4425. isPending={nozzleTemperatureMutation.isPending}
  4426. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4427. onClose={() => setStatusControlMenu(null)}
  4428. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4429. />
  4430. )
  4431. )}
  4432. </div>
  4433. <div
  4434. className={statusControlClass}
  4435. title={statusControlTitle}
  4436. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4437. >
  4438. <button
  4439. type="button"
  4440. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4441. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4442. onClick={(e) => {
  4443. e.stopPropagation();
  4444. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4445. }}
  4446. >
  4447. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4448. </button>
  4449. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4450. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4451. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4452. {Math.round(status.temperatures.bed || 0)}°C
  4453. </p>
  4454. {statusControlMenu === 'bed-temp' && (
  4455. <IndicatorControlPopover
  4456. title="Set Bed Temperature"
  4457. unit="°C"
  4458. customMin={0}
  4459. customMax={140}
  4460. isPending={bedTemperatureMutation.isPending}
  4461. options={buildPresetOptions(bedTempPresets, 'C')}
  4462. onClose={() => setStatusControlMenu(null)}
  4463. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4464. />
  4465. )}
  4466. </div>
  4467. {status.temperatures.chamber !== undefined && (() => {
  4468. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4469. // but can't act on M141, so we keep the card read-only there.
  4470. const hasChamberHeater = status.supports_chamber_heater === true;
  4471. return (
  4472. <div
  4473. className={hasChamberHeater
  4474. ? statusControlClass
  4475. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4476. title={hasChamberHeater ? statusControlTitle : undefined}
  4477. onClick={hasChamberHeater
  4478. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4479. : undefined}
  4480. >
  4481. <button
  4482. type="button"
  4483. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4484. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4485. onClick={(e) => {
  4486. e.stopPropagation();
  4487. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4488. }}
  4489. >
  4490. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4491. </button>
  4492. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4493. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4494. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4495. {Math.round(status.temperatures.chamber || 0)}°C
  4496. </p>
  4497. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4498. <IndicatorControlPopover
  4499. title="Set Chamber Temperature"
  4500. unit="°C"
  4501. customMin={0}
  4502. customMax={MAX_CHAMBER_TEMP_C}
  4503. isPending={chamberTemperatureMutation.isPending}
  4504. options={buildPresetOptions(chamberTempPresets, 'C')}
  4505. onClose={() => setStatusControlMenu(null)}
  4506. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4507. />
  4508. )}
  4509. </div>
  4510. );
  4511. })()}
  4512. {/* Active nozzle indicator for dual-nozzle printers */}
  4513. {isDualNozzle && (
  4514. <DualNozzleHoverCard
  4515. leftSlot={leftNozzleSlot}
  4516. rightSlot={rightNozzleSlot}
  4517. activeNozzle={activeNozzle}
  4518. filamentInfo={filamentInfo}
  4519. >
  4520. <div
  4521. 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 ${
  4522. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4523. }`}
  4524. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4525. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4526. >
  4527. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4528. <div className="flex items-center gap-2">
  4529. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4530. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4531. </span>
  4532. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4533. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4534. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4535. </span>
  4536. </div>
  4537. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4538. {statusControlMenu === 'nozzle-select' && (
  4539. <IndicatorControlPopover
  4540. title="Set Nozzle Selection"
  4541. widthClass="w-[300px]"
  4542. popoverWidth={300}
  4543. popoverHeight={140}
  4544. isPending={selectExtruderMutation.isPending}
  4545. options={[
  4546. { label: 'Left', value: 1 },
  4547. { label: 'Right', value: 0 },
  4548. ]}
  4549. onClose={() => setStatusControlMenu(null)}
  4550. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4551. />
  4552. )}
  4553. </div>
  4554. </DualNozzleHoverCard>
  4555. )}
  4556. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4557. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4558. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4559. )}
  4560. </div>
  4561. <div className="mt-2 flex items-center gap-1.5">
  4562. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4563. const active = value > 0;
  4564. return (
  4565. <div
  4566. key={key}
  4567. 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 ${
  4568. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4569. }`}
  4570. title={canUseStatusControls ? label : statusControlTitle}
  4571. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4572. >
  4573. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4574. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4575. {value}%
  4576. </span>
  4577. {statusControlMenu === `fan-${key}` && (
  4578. <IndicatorControlPopover
  4579. title={`Set ${label} Speed`}
  4580. unit="%"
  4581. customMin={0}
  4582. customMax={100}
  4583. isPending={fanSpeedMutation.isPending}
  4584. options={buildPresetOptions(fanSpeedPresets, '%')}
  4585. onClose={() => setStatusControlMenu(null)}
  4586. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4587. />
  4588. )}
  4589. </div>
  4590. );
  4591. })}
  4592. </div>
  4593. </>
  4594. );
  4595. })()}
  4596. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4597. {/* Controls */}
  4598. {viewMode === 'expanded' && (() => {
  4599. // Determine print state for control buttons
  4600. const isRunning = status.state === 'RUNNING';
  4601. const isPaused = status.state === 'PAUSE';
  4602. const isPrinting = isRunning || isPaused;
  4603. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4604. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4605. 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';
  4606. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4607. return (
  4608. <div className="mt-3">
  4609. {/* Section Header */}
  4610. <div className="flex items-center gap-2 mb-2">
  4611. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4612. {t('printers.controls')}
  4613. </span>
  4614. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4615. </div>
  4616. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4617. {/* Left: Secondary controls */}
  4618. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4619. <button
  4620. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4621. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4622. className={`${iconControlClass} ${
  4623. status.chamber_light
  4624. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4625. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4626. }`}
  4627. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4628. >
  4629. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4630. </button>
  4631. {/* Airduct Mode (P2S / X2D / H2*) */}
  4632. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4633. const isHeating = status.airduct_mode === 1;
  4634. const Icon = isHeating ? Flame : Snowflake;
  4635. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4636. 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';
  4637. return (
  4638. <div className="relative">
  4639. <button
  4640. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4641. disabled={!hasPermission('printers:control')}
  4642. className={`${iconControlClass} ${bg}`}
  4643. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4644. >
  4645. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4646. </button>
  4647. {showAirductMenu === printer.id && (
  4648. <>
  4649. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4650. <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]">
  4651. {([
  4652. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4653. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4654. ] as const).map(({ mode, label, modeId }) => (
  4655. <button
  4656. key={mode}
  4657. onClick={() => {
  4658. airductMutation.mutate(mode);
  4659. setShowAirductMenu(null);
  4660. }}
  4661. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4662. status.airduct_mode === modeId
  4663. ? 'text-bambu-green bg-bambu-green/10'
  4664. : 'text-white hover:bg-bambu-dark-tertiary'
  4665. }`}
  4666. >
  4667. {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)]" />}
  4668. {label}
  4669. </button>
  4670. ))}
  4671. </div>
  4672. </>
  4673. )}
  4674. </div>
  4675. );
  4676. })()}
  4677. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4678. {(() => {
  4679. const canControl = hasPermission('printers:control');
  4680. const disabled = isPrinting || !canControl;
  4681. 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';
  4682. // Which part the Z axis moves (#1334). The endpoint takes a signed
  4683. // nozzle-bed gap that means the same thing on every printer, so the
  4684. // arrows are ours to interpret: on a bed-slinger "up" lifts the
  4685. // toolhead and opens the gap, on a bed-on-Z printer it raises the
  4686. // plate toward the nozzle and closes it.
  4687. const zMovesToolhead = isBedSlinger(printer.model);
  4688. const requestZJog = (arrow: 'up' | 'down') => {
  4689. const opensGap = zMovesToolhead ? arrow === 'up' : arrow === 'down';
  4690. // No not-homed gate here, and no endstop bypass to gate either:
  4691. // since #2579 the jog is a bare move that never touches M211. That
  4692. // does not make it clamped — the firmware ignores soft endstops on
  4693. // MQTT G-code entirely, which is what the banner above warns about.
  4694. bedJogMutation.mutate({ distance: opensGap ? bedJogStep : -bedJogStep });
  4695. };
  4696. const requestXyJog = (x: number, y: number) => {
  4697. xyJogMutation.mutate({ x, y });
  4698. };
  4699. const requestExtruderJog = (distance: number) => {
  4700. extruderJogMutation.mutate(distance);
  4701. };
  4702. return (
  4703. <div className="relative">
  4704. <button
  4705. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4706. disabled={disabled}
  4707. className={`${iconControlClass} ${
  4708. disabled
  4709. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4710. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4711. }`}
  4712. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4713. >
  4714. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4715. </button>
  4716. {showBedJogMenu === printer.id && (
  4717. <>
  4718. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4719. <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">
  4720. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4721. {t('printers.bedJog.title')}
  4722. </div>
  4723. <div className="h-px bg-bambu-dark-tertiary" />
  4724. {/* #2579: Bambu firmware does not enforce soft endstops on
  4725. G-code sent over MQTT, so manual moves can drive past the
  4726. travel limits and cause a collision. Not fixable from our
  4727. side — warn prominently. */}
  4728. <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">
  4729. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4730. <span>{t('printers.bedJog.limitWarning')}</span>
  4731. </div>
  4732. <div className="h-px bg-bambu-dark-tertiary" />
  4733. <div className="flex justify-center px-3 py-2.5">
  4734. <div className="flex items-center justify-center gap-3">
  4735. <div className="grid grid-cols-3 gap-1">
  4736. <div />
  4737. <button
  4738. onClick={() => requestXyJog(0, bedJogStep)}
  4739. disabled={xyJogMutation.isPending}
  4740. className={jogButtonClass}
  4741. aria-label="Move Y forward"
  4742. >
  4743. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4744. </button>
  4745. <div />
  4746. <button
  4747. onClick={() => requestXyJog(-bedJogStep, 0)}
  4748. disabled={xyJogMutation.isPending}
  4749. className={jogButtonClass}
  4750. aria-label="Move X left"
  4751. >
  4752. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4753. </button>
  4754. <button
  4755. onClick={() => {
  4756. setShowBedJogMenu(null);
  4757. homeAxesMutation.mutate('all');
  4758. }}
  4759. disabled={homeAxesMutation.isPending}
  4760. className={jogButtonClass}
  4761. aria-label={t('printers.bedJog.homeZ')}
  4762. >
  4763. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4764. </button>
  4765. <button
  4766. onClick={() => requestXyJog(bedJogStep, 0)}
  4767. disabled={xyJogMutation.isPending}
  4768. className={jogButtonClass}
  4769. aria-label="Move X right"
  4770. >
  4771. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4772. </button>
  4773. <div />
  4774. <button
  4775. onClick={() => requestXyJog(0, -bedJogStep)}
  4776. disabled={xyJogMutation.isPending}
  4777. className={jogButtonClass}
  4778. aria-label="Move Y back"
  4779. >
  4780. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4781. </button>
  4782. <div />
  4783. </div>
  4784. <div className="flex flex-col items-center gap-1">
  4785. <button
  4786. onClick={() => requestZJog('up')}
  4787. disabled={bedJogMutation.isPending}
  4788. className={jogButtonClass}
  4789. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadUp' : 'printers.bedJog.up')}
  4790. >
  4791. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4792. </button>
  4793. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4794. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4795. </div>
  4796. <button
  4797. onClick={() => requestZJog('down')}
  4798. disabled={bedJogMutation.isPending}
  4799. className={jogButtonClass}
  4800. aria-label={t(zMovesToolhead ? 'printers.bedJog.toolheadDown' : 'printers.bedJog.down')}
  4801. >
  4802. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4803. </button>
  4804. </div>
  4805. <div className="flex flex-col items-center gap-1">
  4806. <button
  4807. onClick={() => requestExtruderJog(-bedJogStep)}
  4808. disabled={extruderJogMutation.isPending}
  4809. className={jogButtonClass}
  4810. aria-label="Retract filament"
  4811. >
  4812. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4813. </button>
  4814. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4815. <span className="text-sm font-semibold leading-none">E</span>
  4816. </div>
  4817. <button
  4818. onClick={() => requestExtruderJog(bedJogStep)}
  4819. disabled={extruderJogMutation.isPending}
  4820. className={jogButtonClass}
  4821. aria-label="Extrude filament"
  4822. >
  4823. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4824. </button>
  4825. </div>
  4826. </div>
  4827. </div>
  4828. <div className="h-px bg-bambu-dark-tertiary" />
  4829. <div className="px-3 pt-2.5 pb-3">
  4830. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4831. {t('printers.bedJog.step')}
  4832. </div>
  4833. <div className="flex gap-1">
  4834. {[1, 10, 50].map((step) => (
  4835. <button
  4836. key={step}
  4837. onClick={() => setBedJogStep(step)}
  4838. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4839. bedJogStep === step
  4840. ? 'bg-bambu-green/20 text-bambu-green'
  4841. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4842. }`}
  4843. >
  4844. {step}
  4845. </button>
  4846. ))}
  4847. </div>
  4848. </div>
  4849. </div>
  4850. </>
  4851. )}
  4852. </div>
  4853. );
  4854. })()}
  4855. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4856. <button
  4857. onClick={handleTogglePlateDetection}
  4858. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4859. className={`${iconControlClass} rounded-r-none ${
  4860. printer.plate_detection_enabled
  4861. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4862. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4863. }`}
  4864. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4865. >
  4866. {plateDetectionMutation.isPending ? (
  4867. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4868. ) : (
  4869. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4870. )}
  4871. </button>
  4872. <button
  4873. onClick={handleOpenPlateManagement}
  4874. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4875. 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 ${
  4876. printer.plate_detection_enabled
  4877. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4878. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4879. }`}
  4880. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4881. >
  4882. {isCheckingPlate ? (
  4883. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4884. ) : (
  4885. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4886. )}
  4887. </button>
  4888. </div>
  4889. {/* Print Speed */}
  4890. {(() => (
  4891. <div className="relative">
  4892. <button
  4893. data-testid="speed-control"
  4894. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4895. disabled={!isPrinting || !hasPermission('printers:control')}
  4896. className={`${iconControlClass} ${
  4897. isPrinting
  4898. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4899. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4900. }`}
  4901. title={isPrinting ? t('printers.speed.title') : undefined}
  4902. >
  4903. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4904. </button>
  4905. {showSpeedMenu === printer.id && (
  4906. <>
  4907. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4908. <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]">
  4909. {([
  4910. { mode: 1, label: t('printers.speed.silent') },
  4911. { mode: 2, label: t('printers.speed.standard') },
  4912. { mode: 3, label: t('printers.speed.sport') },
  4913. { mode: 4, label: t('printers.speed.ludicrous') },
  4914. ] as const).map(({ mode, label }) => (
  4915. <button
  4916. key={mode}
  4917. onClick={() => {
  4918. printSpeedMutation.mutate(mode);
  4919. setShowSpeedMenu(null);
  4920. }}
  4921. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4922. status.speed_level === mode
  4923. ? 'text-bambu-green bg-bambu-green/10'
  4924. : 'text-white hover:bg-bambu-dark-tertiary'
  4925. }`}
  4926. >
  4927. {label}
  4928. </button>
  4929. ))}
  4930. </div>
  4931. </>
  4932. )}
  4933. </div>
  4934. ))()}
  4935. </div>
  4936. {/* Right: Print Control Buttons */}
  4937. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4938. {/* Pause/Resume button */}
  4939. {(() => {
  4940. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4941. return (
  4942. <button
  4943. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4944. disabled={pauseUnavailable}
  4945. className={`
  4946. ${printControlClass}
  4947. ${pauseUnavailable
  4948. ? unavailablePrintActionClass
  4949. : isPaused
  4950. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4951. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4952. }
  4953. `}
  4954. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4955. >
  4956. {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)]" />}
  4957. {isPaused ? t('printers.resume') : t('printers.pause')}
  4958. </button>
  4959. );
  4960. })()}
  4961. {/* Stop button */}
  4962. {(() => {
  4963. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4964. return (
  4965. <button
  4966. onClick={() => setShowStopConfirm(true)}
  4967. disabled={stopUnavailable}
  4968. className={`
  4969. ${printControlClass}
  4970. ${stopUnavailable
  4971. ? unavailablePrintActionClass
  4972. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4973. }
  4974. `}
  4975. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4976. >
  4977. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4978. {t('printers.stop')}
  4979. </button>
  4980. );
  4981. })()}
  4982. </div>
  4983. </div>
  4984. </div>
  4985. );
  4986. })()}
  4987. {/* AMS Units - 2-Column Grid Layout */}
  4988. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4989. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4990. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4991. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4992. // The external spool can only be hidden while some AMS remains to
  4993. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  4994. // filament section, so the toggle is not offered there and a stored
  4995. // preference from a printer that later lost its AMS cannot blank the
  4996. // row either — both read through canHideExternalSpool.
  4997. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  4998. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  4999. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  5000. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  5001. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  5002. // floating point, and that lands verbatim in the DOM.
  5003. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  5004. // Deliberately NOT scaled with the body (#1848). These AMS cards
  5005. // already grow to fill the row, so the 3.5rem is a floor they sit
  5006. // well above in practice -- raising it just costs a unit its place
  5007. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  5008. // its line, and flex-grow stretches its single slot across the whole
  5009. // card. The AMS-HT's own width does scale, below, because its
  5010. // readings sit beside the slot rather than under it.
  5011. const slotMinWidth = '3.5rem';
  5012. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  5013. // The AMS-HT holds a single spool, and its slot is the only thing
  5014. // on that row able to grow -- so it swallowed every spare pixel and
  5015. // shoved the temperature and humidity hard against the card's edge.
  5016. // Capping it at roughly two ordinary slots keeps the readings clear
  5017. // of the edge; the cap scales because the text inside the slot does.
  5018. const htSlotStyle: React.CSSProperties = {
  5019. minWidth: slotMinWidth,
  5020. maxWidth: scaledRem(7.25),
  5021. };
  5022. const slotGridStyle = (columns: number): React.CSSProperties => ({
  5023. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  5024. });
  5025. // #1762 (comment 2): while a print is running/paused, overlay a small
  5026. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  5027. // mapping. Catches the reporter's scenario — "any X1C" queue job
  5028. // staged to a printer with mismatched filament: the wrong-slot pill
  5029. // is visible the instant printing starts.
  5030. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  5031. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  5032. ? status.ams_mapping
  5033. : [];
  5034. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  5035. const boundedSlotCount = Math.max(1, slotCount);
  5036. const gapCount = Math.max(0, boundedSlotCount - 1);
  5037. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  5038. return {
  5039. flex: `1 1 ${minWidth}`,
  5040. minWidth,
  5041. };
  5042. };
  5043. return (
  5044. <div className="mt-3">
  5045. {/* Section Header */}
  5046. <div className="flex items-center gap-2 mb-2">
  5047. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5048. {t('printers.filaments')}
  5049. </span>
  5050. <AmsBackupBadge
  5051. state={status.ams_filament_backup}
  5052. onClick={() => setAmsBackupModalOpen(true)}
  5053. />
  5054. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5055. {/* Offered only when an AMS is present: on a printer that
  5056. feeds from the external spool alone, hiding it would
  5057. empty the row entirely (#1782). */}
  5058. {canHideExternalSpool && (
  5059. <>
  5060. <ExternalSpoolToggle
  5061. hidden={externalSpoolHidden}
  5062. onClick={toggleExternalSpool}
  5063. />
  5064. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  5065. </>
  5066. )}
  5067. </div>
  5068. {/* AMS Content */}
  5069. <div className="flex flex-wrap gap-2">
  5070. {/* Regular AMS units */}
  5071. {regularAms.map((ams) => {
  5072. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5073. return (
  5074. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5075. {/* Header: Label + Stats (no icon) */}
  5076. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5077. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5078. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5079. <AmsNameHoverCard
  5080. ams={ams}
  5081. printerId={printer.id}
  5082. label={getAmsLabel(ams.id, ams.tray.length)}
  5083. amsLabels={amsLabels}
  5084. canEdit={hasPermission('printers:update')}
  5085. onSaved={refetchAmsLabels}
  5086. >
  5087. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5088. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5089. </span>
  5090. </AmsNameHoverCard>
  5091. {sideBadge?.kind === 'inlet' ? (
  5092. <InletBadge
  5093. inlet={sideBadge.inlet}
  5094. title={t('printers.amsSwitchInletTooltip', {
  5095. inlet: sideBadge.inlet,
  5096. side: FTS_INLET_SIDE[sideBadge.inlet],
  5097. })}
  5098. />
  5099. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5100. <NozzleBadge side={sideBadge.side} />
  5101. ) : null}
  5102. </div>
  5103. {(ams.humidity != null || ams.temp != null) && (
  5104. <div className="flex shrink-0 items-center gap-1.5">
  5105. {ams.humidity != null && (
  5106. <HumidityIndicator
  5107. humidity={ams.humidity}
  5108. goodThreshold={amsThresholds?.humidityGood}
  5109. fairThreshold={amsThresholds?.humidityFair}
  5110. onClick={() => setAmsHistoryModal({
  5111. amsId: ams.id,
  5112. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5113. mode: 'humidity',
  5114. })}
  5115. compact
  5116. />
  5117. )}
  5118. {ams.temp != null && (
  5119. <div className="mr-1">
  5120. <TemperatureIndicator
  5121. temp={ams.temp}
  5122. goodThreshold={amsThresholds?.tempGood}
  5123. fairThreshold={amsThresholds?.tempFair}
  5124. onClick={() => setAmsHistoryModal({
  5125. amsId: ams.id,
  5126. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5127. mode: 'temperature',
  5128. })}
  5129. compact
  5130. />
  5131. </div>
  5132. )}
  5133. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5134. Screen-only models (P1 series) keep the control but can't
  5135. be commanded: it stays disabled and says why (#2533). */}
  5136. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5137. <button
  5138. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5139. onClick={(e) => {
  5140. if (ams.dry_time > 0) {
  5141. stopDryingMutation.mutate(ams.id);
  5142. } else if (dryingPopoverAmsId === ams.id) {
  5143. setDryingPopoverAmsId(null);
  5144. } else {
  5145. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5146. }
  5147. }}
  5148. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5149. ams.dry_time > 0
  5150. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5151. : status.drying_screen_only || ams.dry_sf_reason?.length
  5152. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5153. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5154. }`}
  5155. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t(dryingBlockedKey(ams.dry_sf_reason)) : t('printers.drying.start')}
  5156. >
  5157. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5158. </button>
  5159. )}
  5160. </div>
  5161. )}
  5162. </div>
  5163. {/* Drying status bar. A dry_time whose countdown is not
  5164. ticking, with no active drying phase (a parked command —
  5165. e.g. an H2D mid-print already powering other drying — or
  5166. a paused cycle), is shown as "not running", not as an
  5167. active cycle: the amber badge claiming a running dry
  5168. that the AMS never began is how this was found. */}
  5169. {ams.dry_time > 0 && ams.dry_countdown_stalled && (
  5170. <div className="flex items-center gap-2 rounded-lg bg-slate-100 dark:bg-slate-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]" title={t('printers.drying.notRunningHint')}>
  5171. <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5172. <span className="text-slate-600 dark:text-slate-300 font-medium">{t('printers.drying.notRunning')}</span>
  5173. {ams.dry_filament && (
  5174. <span className="text-slate-500/90 dark:text-slate-400/80">
  5175. {ams.dry_target_temp != null
  5176. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5177. : ams.dry_filament}
  5178. </span>
  5179. )}
  5180. {!status.drying_screen_only && (
  5181. <button
  5182. onClick={() => stopDryingMutation.mutate(ams.id)}
  5183. disabled={stopDryingMutation.isPending}
  5184. className="ml-auto text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 transition-colors disabled:opacity-50"
  5185. title={t('printers.drying.stop')}
  5186. >
  5187. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5188. </button>
  5189. )}
  5190. </div>
  5191. )}
  5192. {ams.dry_time > 0 && !ams.dry_countdown_stalled && (
  5193. <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)]">
  5194. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5195. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5196. {/* The temperature is only ever known from the target we
  5197. cached when sending the command — the filament can also
  5198. be read off a uniformly loaded unit, so it can outlive
  5199. the temperature (#2759). */}
  5200. {ams.dry_filament && (
  5201. <span className="text-amber-700/80 dark:text-amber-300/70">
  5202. {ams.dry_target_temp != null
  5203. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5204. : ams.dry_filament}
  5205. </span>
  5206. )}
  5207. <span className="text-amber-700/80 dark:text-amber-300/70">
  5208. {t('printers.drying.timeRemaining', {
  5209. time: ams.dry_time >= 60
  5210. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5211. : `${ams.dry_time}m`
  5212. })}
  5213. </span>
  5214. {/* A cycle on a screen-only model was started at the printer
  5215. and can only be stopped there (#2533). */}
  5216. {!status.drying_screen_only && (
  5217. <button
  5218. onClick={() => stopDryingMutation.mutate(ams.id)}
  5219. disabled={stopDryingMutation.isPending}
  5220. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5221. title={t('printers.drying.stop')}
  5222. >
  5223. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5224. </button>
  5225. )}
  5226. </div>
  5227. )}
  5228. {/* Slots grid: 4 columns - always render 4 slots */}
  5229. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5230. {[0, 1, 2, 3].map((slotIdx) => {
  5231. // Find tray data for this slot (may be undefined if data incomplete)
  5232. // Use array index if available, as tray.id may not always be set
  5233. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5234. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5235. const isEmpty = !tray?.tray_type;
  5236. const emptyKind = getEmptySlotKind(tray);
  5237. // Check if this is the currently loaded tray
  5238. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5239. const globalTrayId = ams.id * 4 + slotIdx;
  5240. const isActive = effectiveTrayNow === globalTrayId;
  5241. // Runout guidance (#2587): the slot the paused print now
  5242. // expects filament in, and the slot that ran out.
  5243. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5244. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5245. // Get cloud preset info if available
  5246. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5247. // Get saved slot preset mapping (for user-configured slots)
  5248. const slotPreset = slotPresets?.[globalTrayId];
  5249. // Only trusted while it still describes what the printer reports in the
  5250. // slot: the row survives a spool swap, and the display chain below puts
  5251. // it ahead of the live filament id (see slotPresetDescribesTray).
  5252. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5253. ? slotPreset?.preset_name
  5254. : undefined;
  5255. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5256. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5257. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5258. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5259. // Slot-assigned-only spool fill (no tag link required)
  5260. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5261. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5262. : undefined;
  5263. const slotSpoolForFill = slotAssignmentForFill
  5264. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5265. : undefined;
  5266. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5267. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5268. : null;
  5269. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5270. const inventoryFill = (() => {
  5271. const sp = inventoryAssignment?.spool;
  5272. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5273. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5274. }
  5275. return null;
  5276. })();
  5277. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5278. // (inventory weight_used may be stale or over-counted — #676)
  5279. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5280. ? null : inventoryFill;
  5281. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5282. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5283. : resolvedInventoryFill !== null ? 'inventory' as const
  5284. : hasFillLevel ? 'ams' as const
  5285. : undefined;
  5286. // Build filament data for hover card
  5287. const filamentData = tray?.tray_type ? {
  5288. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5289. // Spoolman spool name wins over cloud lookup so a slot bound to
  5290. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5291. // Design PLA") instead of whatever the printer's filament_id
  5292. // resolves to in the cloud catalog (often "Generic PLA" for
  5293. // P-prefix local presets). Spoolman's filament.name is just the
  5294. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5295. // the hover card shows "Devil Design PLA Basic" rather than the
  5296. // vendor-less form. Strip the "@<printer>..." suffix that
  5297. // BambuStudio appends to user-preset names.
  5298. profile: slotPresetName || (slotSpoolForFill ? [slotSpoolForFill.brand, slotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || slotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || inventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  5299. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5300. colorHex: tray.tray_color || null,
  5301. kFactor: formatKValue(tray.k),
  5302. fillLevel: effectiveFill,
  5303. trayUuid: tray.tray_uuid || null,
  5304. tagUid: tray.tag_uid || null,
  5305. fillSource,
  5306. } : null;
  5307. // Check if this specific slot is being refreshed
  5308. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5309. refreshingSlot?.slotId === slotIdx;
  5310. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5311. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5312. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5313. ? `P${activePrintSlotIdx + 1}`
  5314. : null;
  5315. // Slot visual content (goes inside hover card)
  5316. const slotVisual = (
  5317. <div
  5318. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5319. isExpectedSlot
  5320. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5321. : isRanOutSlot
  5322. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5323. : isActive
  5324. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5325. : ''
  5326. }`}
  5327. >
  5328. {isExpectedSlot && (
  5329. <span
  5330. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5331. title={t('printers.expectedSlot.title')}
  5332. 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"
  5333. >
  5334. ↓
  5335. </span>
  5336. )}
  5337. {activePrintSlotLabel && (
  5338. <span
  5339. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5340. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5341. 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"
  5342. >
  5343. {activePrintSlotLabel}
  5344. </span>
  5345. )}
  5346. {/* Filament color circle with 1-based slot number centered inside */}
  5347. <FilamentSlotCircle
  5348. trayColor={tray?.tray_color}
  5349. trayType={tray?.tray_type}
  5350. isEmpty={isEmpty}
  5351. emptyKind={emptyKind}
  5352. slotNumber={slotIdx + 1}
  5353. />
  5354. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5355. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5356. </div>
  5357. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5358. {/* Fill bar */}
  5359. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5360. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5361. <div
  5362. className="h-full rounded-full transition-all"
  5363. style={{
  5364. width: `${effectiveFill}%`,
  5365. backgroundColor: getFillBarColor(effectiveFill),
  5366. }}
  5367. />
  5368. )}
  5369. </div>
  5370. </div>
  5371. );
  5372. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5373. return (
  5374. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5375. {/* Loading overlay during RFID re-read */}
  5376. {isRefreshing && (
  5377. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5378. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5379. </div>
  5380. )}
  5381. {/* Hover card wraps only the visual content */}
  5382. {filamentData ? (
  5383. <FilamentHoverCard
  5384. data={filamentData}
  5385. actions={renderAmsSlotActions({
  5386. amsId: ams.id,
  5387. slotId: slotIdx,
  5388. loadTrayId: ams.id * 4 + slotIdx,
  5389. isRefreshing,
  5390. })}
  5391. spoolman={{
  5392. enabled: spoolmanEnabled,
  5393. // #1457: slot assignment is the user's most explicit action — it must
  5394. // outrank the tag-link, which can be stale when a non-RFID slot's
  5395. // fallback tag is still attached to a previous spool in Spoolman.
  5396. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5397. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5398. spoolmanUrl,
  5399. syncMode: spoolmanSyncMode,
  5400. // Suppress Link button when slot is already occupied by ANY assignment
  5401. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5402. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5403. // still appearing on slots with a local Devil Design PLA assigned.
  5404. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5405. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5406. setLinkSpoolModal({
  5407. tagUid: filamentData.tagUid || linkTag,
  5408. trayUuid: filamentData.trayUuid || '',
  5409. printerId: printer.id,
  5410. amsId: ams.id,
  5411. trayId: slotIdx,
  5412. });
  5413. } : undefined,
  5414. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5415. }}
  5416. inventory={(() => {
  5417. if (spoolmanEnabled) {
  5418. if (spoolmanLoading) return undefined;
  5419. const slotAssignment = slotAssignmentForFill;
  5420. const spoolmanSpool = slotSpoolForFill;
  5421. return {
  5422. assignedSpool: spoolmanSpool ? {
  5423. id: spoolmanSpool.id,
  5424. material: spoolmanSpool.material,
  5425. subtype: spoolmanSpool.subtype,
  5426. brand: spoolmanSpool.brand ?? null,
  5427. color_name: spoolmanSpool.color_name ?? null,
  5428. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5429. // The spool's own swatch (#2967). Spoolman carries the
  5430. // extra stops but has no effect field at all, so those
  5431. // rolls gradient and never shimmer.
  5432. rgba: spoolmanSpool.rgba ?? null,
  5433. extra_colors: spoolmanSpool.extra_colors ?? null,
  5434. effect_type: spoolmanSpool.effect_type ?? null,
  5435. remainingWeightGrams: spoolmanSpool.label_weight
  5436. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5437. : undefined,
  5438. } : null,
  5439. onAssignSpool: () => setAssignSpoolModal({
  5440. printerId: printer.id,
  5441. amsId: ams.id,
  5442. trayId: slotIdx,
  5443. trayInfo: {
  5444. type: tray?.tray_type || filamentData.profile,
  5445. material: tray?.tray_type ?? undefined,
  5446. profile: filamentData.profile,
  5447. color: filamentData.colorHex || '',
  5448. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5449. },
  5450. }),
  5451. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5452. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5453. };
  5454. }
  5455. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5456. return {
  5457. assignedSpool: assignment?.spool ? {
  5458. id: assignment.spool.id,
  5459. material: assignment.spool.material,
  5460. subtype: assignment.spool.subtype,
  5461. brand: assignment.spool.brand,
  5462. color_name: assignment.spool.color_name,
  5463. // The spool's own swatch (#2967).
  5464. rgba: assignment.spool.rgba ?? null,
  5465. extra_colors: assignment.spool.extra_colors ?? null,
  5466. effect_type: assignment.spool.effect_type ?? null,
  5467. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5468. } : null,
  5469. onAssignSpool: () => setAssignSpoolModal({
  5470. printerId: printer.id,
  5471. amsId: ams.id,
  5472. trayId: slotIdx,
  5473. trayInfo: {
  5474. type: tray?.tray_type || filamentData.profile,
  5475. material: tray?.tray_type ?? undefined,
  5476. profile: filamentData.profile,
  5477. color: filamentData.colorHex || '',
  5478. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5479. },
  5480. }),
  5481. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5482. isAssigned: !!assignment || isBambuLabSpool(tray),
  5483. };
  5484. })()}
  5485. configureSlot={{
  5486. enabled: hasPermission('printers:control'),
  5487. onConfigure: () => setConfigureSlotModal({
  5488. amsId: ams.id,
  5489. trayId: slotIdx,
  5490. trayCount: ams.tray.length,
  5491. trayType: tray?.tray_type || undefined,
  5492. trayColor: tray?.tray_color || undefined,
  5493. traySubBrands: tray?.tray_sub_brands || undefined,
  5494. trayInfoIdx: tray?.tray_info_idx || undefined,
  5495. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5496. caliIdx: tray?.cali_idx,
  5497. savedPresetId: slotPreset?.preset_id,
  5498. }),
  5499. }}
  5500. >
  5501. {slotVisual}
  5502. </FilamentHoverCard>
  5503. ) : (
  5504. <EmptySlotHoverCard
  5505. kind={emptyKind ?? undefined}
  5506. actions={renderAmsSlotActions({
  5507. amsId: ams.id,
  5508. slotId: slotIdx,
  5509. loadTrayId: ams.id * 4 + slotIdx,
  5510. isRefreshing,
  5511. })}
  5512. configureSlot={{
  5513. enabled: hasPermission('printers:control'),
  5514. onConfigure: () => setConfigureSlotModal({
  5515. amsId: ams.id,
  5516. trayId: slotIdx,
  5517. trayCount: ams.tray.length,
  5518. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5519. }),
  5520. }}
  5521. onAssignSpool={() => setAssignSpoolModal({
  5522. printerId: printer.id,
  5523. amsId: ams.id,
  5524. trayId: slotIdx,
  5525. trayInfo: {
  5526. type: '',
  5527. material: undefined,
  5528. profile: '',
  5529. color: '',
  5530. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5531. },
  5532. })}
  5533. >
  5534. {slotVisual}
  5535. </EmptySlotHoverCard>
  5536. )}
  5537. </div>
  5538. );
  5539. })}
  5540. </div>
  5541. </div>
  5542. );
  5543. })}
  5544. {/* HT AMS units */}
  5545. {htAms.map((ams) => {
  5546. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5547. const tray = ams.tray[0];
  5548. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5549. const isEmpty = !tray?.tray_type;
  5550. const emptyKind = getEmptySlotKind(tray);
  5551. // Check if this is the currently loaded tray
  5552. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5553. const isActive = effectiveTrayNow === globalTrayId;
  5554. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5555. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5556. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5557. // Get cloud preset info if available
  5558. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5559. // Get saved slot preset mapping (for user-configured slots)
  5560. const slotPreset = slotPresets?.[globalTrayId];
  5561. // Only trusted while it still describes what the printer reports in the
  5562. // slot: the row survives a spool swap, and the display chain below puts
  5563. // it ahead of the live filament id (see slotPresetDescribesTray).
  5564. const slotPresetName = slotPresetDescribesTray(slotPreset?.preset_id, tray?.tray_info_idx)
  5565. ? slotPreset?.preset_name
  5566. : undefined;
  5567. const htSlotId = tray?.id ?? 0;
  5568. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5569. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5570. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5571. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5572. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5573. const htInventoryFill = (() => {
  5574. const sp = htInventoryAssignment?.spool;
  5575. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5576. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5577. }
  5578. return null;
  5579. })();
  5580. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5581. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5582. ? null : htInventoryFill;
  5583. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5584. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5585. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5586. : undefined;
  5587. const htSlotSpoolForFill = htSlotAssignmentForFill
  5588. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5589. : undefined;
  5590. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5591. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5592. : null;
  5593. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5594. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5595. : htResolvedInventoryFill !== null ? 'inventory' as const
  5596. : hasFillLevel ? 'ams' as const
  5597. : undefined;
  5598. // Build filament data for hover card
  5599. const filamentData = tray?.tray_type ? {
  5600. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5601. profile: slotPresetName || (htSlotSpoolForFill ? [htSlotSpoolForFill.brand, htSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || htSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || htInventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  5602. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5603. colorHex: tray.tray_color || null,
  5604. kFactor: formatKValue(tray.k),
  5605. fillLevel: htEffectiveFill,
  5606. trayUuid: tray.tray_uuid || null,
  5607. tagUid: tray.tag_uid || null,
  5608. fillSource: htFillSource,
  5609. } : null;
  5610. // Check if this specific slot is being refreshed
  5611. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5612. refreshingSlot?.slotId === htSlotId;
  5613. // #1762 (comment 2): active print-slot index for this HT slot.
  5614. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5615. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5616. ? `P${htActivePrintSlotIdx + 1}`
  5617. : null;
  5618. // Slot visual content (goes inside hover card)
  5619. const slotVisual = (
  5620. <div
  5621. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5622. isExpectedSlot
  5623. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5624. : isRanOutSlot
  5625. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5626. : isActive
  5627. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5628. : ''
  5629. }`}
  5630. >
  5631. {isExpectedSlot && (
  5632. <span
  5633. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5634. title={t('printers.expectedSlot.title')}
  5635. 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"
  5636. >
  5637. ↓
  5638. </span>
  5639. )}
  5640. {htActivePrintSlotLabel && (
  5641. <span
  5642. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5643. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5644. 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"
  5645. >
  5646. {htActivePrintSlotLabel}
  5647. </span>
  5648. )}
  5649. {/* Filament color circle with 1-based slot number centered inside */}
  5650. <FilamentSlotCircle
  5651. trayColor={tray?.tray_color}
  5652. trayType={tray?.tray_type}
  5653. isEmpty={isEmpty}
  5654. emptyKind={emptyKind}
  5655. slotNumber={1}
  5656. />
  5657. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5658. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5659. </div>
  5660. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5661. {/* Fill bar */}
  5662. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5663. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5664. <div
  5665. className="h-full rounded-full transition-all"
  5666. style={{
  5667. width: `${htEffectiveFill}%`,
  5668. backgroundColor: getFillBarColor(htEffectiveFill),
  5669. }}
  5670. />
  5671. )}
  5672. </div>
  5673. </div>
  5674. );
  5675. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5676. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5677. // Without this override, the L view squishes HT into a sliver next to the
  5678. // 4-slot AMS neighbors.
  5679. // 11rem holds one slot plus the temperature/humidity
  5680. // column beside it; both grow with the body scale.
  5681. const htCardWidth = scaledRem(11);
  5682. const htCardStyle: React.CSSProperties = {
  5683. flex: `1 1 ${htCardWidth}`,
  5684. minWidth: htCardWidth,
  5685. // An AMS-HT is never wider than a full AMS. Without a
  5686. // ceiling, a unit that wraps onto a line of its own is
  5687. // the only flex item there and grow stretches its single
  5688. // slot across the entire card, leaving the readings
  5689. // stranded at the far edge.
  5690. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5691. };
  5692. return (
  5693. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5694. {/* Row 1: Label + Nozzle + Drying */}
  5695. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5696. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5697. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5698. <AmsNameHoverCard
  5699. ams={ams}
  5700. printerId={printer.id}
  5701. label={getAmsLabel(ams.id, ams.tray.length)}
  5702. amsLabels={amsLabels}
  5703. canEdit={hasPermission('printers:update')}
  5704. onSaved={refetchAmsLabels}
  5705. >
  5706. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5707. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5708. </span>
  5709. </AmsNameHoverCard>
  5710. {sideBadge?.kind === 'inlet' ? (
  5711. <InletBadge
  5712. inlet={sideBadge.inlet}
  5713. title={t('printers.amsSwitchInletTooltip', {
  5714. inlet: sideBadge.inlet,
  5715. side: FTS_INLET_SIDE[sideBadge.inlet],
  5716. })}
  5717. />
  5718. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5719. <NozzleBadge side={sideBadge.side} />
  5720. ) : null}
  5721. </div>
  5722. {/* Drying button for HT AMS */}
  5723. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5724. <div className="relative ml-auto">
  5725. <button
  5726. disabled={status.drying_screen_only}
  5727. onClick={(e) => {
  5728. if (ams.dry_time > 0) {
  5729. stopDryingMutation.mutate(ams.id);
  5730. } else if (dryingPopoverAmsId === ams.id) {
  5731. setDryingPopoverAmsId(null);
  5732. } else {
  5733. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5734. }
  5735. }}
  5736. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5737. ams.dry_time > 0
  5738. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5739. : status.drying_screen_only
  5740. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5741. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5742. }`}
  5743. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5744. >
  5745. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5746. </button>
  5747. </div>
  5748. )}
  5749. </div>
  5750. {/* HT AMS drying status bar. Same not-running split as the
  5751. standard-AMS bar above: a frozen countdown is not a
  5752. running cycle. */}
  5753. {ams.dry_time > 0 && (
  5754. <div className={`flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg px-2 py-1 text-[length:var(--pc-t9,9px)] ${ams.dry_countdown_stalled ? 'bg-slate-100 dark:bg-slate-500/10' : 'bg-amber-50 dark:bg-amber-500/10'}`} title={ams.dry_countdown_stalled ? t('printers.drying.notRunningHint') : undefined}>
  5755. {ams.dry_countdown_stalled
  5756. ? <Hourglass className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-slate-500 dark:text-slate-400 shrink-0" />
  5757. : <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />}
  5758. {ams.dry_countdown_stalled && (
  5759. <span className="text-slate-600 dark:text-slate-300 text-[length:var(--pc-t8,8px)] font-medium truncate">{t('printers.drying.notRunning')}</span>
  5760. )}
  5761. {ams.dry_filament && (
  5762. <span className={`${ams.dry_countdown_stalled ? 'text-slate-500/90 dark:text-slate-400/80' : 'text-amber-700/80 dark:text-amber-300/70'} text-[length:var(--pc-t8,8px)] truncate`}>
  5763. {ams.dry_target_temp != null
  5764. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5765. : ams.dry_filament}
  5766. </span>
  5767. )}
  5768. {!ams.dry_countdown_stalled && (
  5769. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5770. {ams.dry_time >= 60
  5771. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5772. : `${ams.dry_time}m`}
  5773. </span>
  5774. )}
  5775. {!status.drying_screen_only && (
  5776. <button
  5777. onClick={() => stopDryingMutation.mutate(ams.id)}
  5778. disabled={stopDryingMutation.isPending}
  5779. 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"
  5780. title={t('printers.drying.stop')}
  5781. >
  5782. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5783. </button>
  5784. )}
  5785. </div>
  5786. )}
  5787. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5788. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5789. {/* Slot wrapper with loading overlay */}
  5790. <div className="relative group flex-1" style={htSlotStyle}>
  5791. {/* Loading overlay during RFID re-read */}
  5792. {isHtRefreshing && (
  5793. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5794. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5795. </div>
  5796. )}
  5797. {/* Hover card wraps only the visual content */}
  5798. {filamentData ? (
  5799. <FilamentHoverCard
  5800. data={filamentData}
  5801. actions={renderAmsSlotActions({
  5802. amsId: ams.id,
  5803. slotId: htSlotId,
  5804. loadTrayId: ams.id * 4 + htSlotId,
  5805. isRefreshing: isHtRefreshing,
  5806. })}
  5807. spoolman={{
  5808. enabled: spoolmanEnabled,
  5809. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5810. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5811. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5812. spoolmanUrl,
  5813. syncMode: spoolmanSyncMode,
  5814. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5815. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5816. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5817. setLinkSpoolModal({
  5818. tagUid: filamentData.tagUid || linkTag,
  5819. trayUuid: filamentData.trayUuid || '',
  5820. printerId: printer.id,
  5821. amsId: ams.id,
  5822. trayId: htSlotId,
  5823. });
  5824. } : undefined,
  5825. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5826. }}
  5827. inventory={(() => {
  5828. if (spoolmanEnabled) {
  5829. if (spoolmanLoading) return undefined;
  5830. const slotAssignment = htSlotAssignmentForFill;
  5831. const spoolmanSpool = htSlotSpoolForFill;
  5832. return {
  5833. assignedSpool: spoolmanSpool ? {
  5834. id: spoolmanSpool.id,
  5835. material: spoolmanSpool.material,
  5836. subtype: spoolmanSpool.subtype,
  5837. brand: spoolmanSpool.brand ?? null,
  5838. color_name: spoolmanSpool.color_name ?? null,
  5839. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  5840. // The spool's own swatch (#2967). Spoolman carries the
  5841. // extra stops but has no effect field at all, so those
  5842. // rolls gradient and never shimmer.
  5843. rgba: spoolmanSpool.rgba ?? null,
  5844. extra_colors: spoolmanSpool.extra_colors ?? null,
  5845. effect_type: spoolmanSpool.effect_type ?? null,
  5846. remainingWeightGrams: spoolmanSpool.label_weight
  5847. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5848. : undefined,
  5849. } : null,
  5850. onAssignSpool: () => setAssignSpoolModal({
  5851. printerId: printer.id,
  5852. amsId: ams.id,
  5853. trayId: htSlotId,
  5854. trayInfo: {
  5855. type: tray?.tray_type || filamentData.profile,
  5856. material: tray?.tray_type ?? undefined,
  5857. profile: filamentData.profile,
  5858. color: filamentData.colorHex || '',
  5859. location: getAmsLabel(ams.id, ams.tray.length),
  5860. },
  5861. }),
  5862. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5863. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5864. };
  5865. }
  5866. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5867. return {
  5868. assignedSpool: assignment?.spool ? {
  5869. id: assignment.spool.id,
  5870. material: assignment.spool.material,
  5871. subtype: assignment.spool.subtype,
  5872. brand: assignment.spool.brand,
  5873. color_name: assignment.spool.color_name,
  5874. // The spool's own swatch (#2967).
  5875. rgba: assignment.spool.rgba ?? null,
  5876. extra_colors: assignment.spool.extra_colors ?? null,
  5877. effect_type: assignment.spool.effect_type ?? null,
  5878. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5879. } : null,
  5880. onAssignSpool: () => setAssignSpoolModal({
  5881. printerId: printer.id,
  5882. amsId: ams.id,
  5883. trayId: htSlotId,
  5884. trayInfo: {
  5885. type: tray?.tray_type || filamentData.profile,
  5886. material: tray?.tray_type ?? undefined,
  5887. profile: filamentData.profile,
  5888. color: filamentData.colorHex || '',
  5889. location: getAmsLabel(ams.id, ams.tray.length),
  5890. },
  5891. }),
  5892. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5893. isAssigned: !!assignment || isBambuLabSpool(tray),
  5894. };
  5895. })()}
  5896. configureSlot={{
  5897. enabled: hasPermission('printers:control'),
  5898. onConfigure: () => setConfigureSlotModal({
  5899. amsId: ams.id,
  5900. trayId: htSlotId,
  5901. trayCount: ams.tray.length,
  5902. trayType: tray?.tray_type || undefined,
  5903. trayColor: tray?.tray_color || undefined,
  5904. traySubBrands: tray?.tray_sub_brands || undefined,
  5905. trayInfoIdx: tray?.tray_info_idx || undefined,
  5906. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5907. caliIdx: tray?.cali_idx,
  5908. savedPresetId: slotPreset?.preset_id,
  5909. }),
  5910. }}
  5911. >
  5912. {slotVisual}
  5913. </FilamentHoverCard>
  5914. ) : (
  5915. <EmptySlotHoverCard
  5916. kind={emptyKind ?? undefined}
  5917. actions={renderAmsSlotActions({
  5918. amsId: ams.id,
  5919. slotId: htSlotId,
  5920. loadTrayId: ams.id * 4 + htSlotId,
  5921. isRefreshing: isHtRefreshing,
  5922. })}
  5923. configureSlot={{
  5924. enabled: hasPermission('printers:control'),
  5925. onConfigure: () => setConfigureSlotModal({
  5926. amsId: ams.id,
  5927. trayId: htSlotId,
  5928. trayCount: ams.tray.length,
  5929. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5930. }),
  5931. }}
  5932. onAssignSpool={() => setAssignSpoolModal({
  5933. printerId: printer.id,
  5934. amsId: ams.id,
  5935. trayId: htSlotId,
  5936. trayInfo: {
  5937. type: '',
  5938. material: undefined,
  5939. profile: '',
  5940. color: '',
  5941. location: getAmsLabel(ams.id, ams.tray.length),
  5942. },
  5943. })}
  5944. >
  5945. {slotVisual}
  5946. </EmptySlotHoverCard>
  5947. )}
  5948. </div>
  5949. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5950. {(ams.humidity != null || ams.temp != null) && (
  5951. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5952. {ams.temp != null && (
  5953. <TemperatureIndicator
  5954. temp={ams.temp}
  5955. goodThreshold={amsThresholds?.tempGood}
  5956. fairThreshold={amsThresholds?.tempFair}
  5957. onClick={() => setAmsHistoryModal({
  5958. amsId: ams.id,
  5959. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5960. mode: 'temperature',
  5961. })}
  5962. compact
  5963. />
  5964. )}
  5965. {ams.humidity != null && (
  5966. <HumidityIndicator
  5967. humidity={ams.humidity}
  5968. goodThreshold={amsThresholds?.humidityGood}
  5969. fairThreshold={amsThresholds?.humidityFair}
  5970. onClick={() => setAmsHistoryModal({
  5971. amsId: ams.id,
  5972. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5973. mode: 'humidity',
  5974. })}
  5975. compact
  5976. />
  5977. )}
  5978. </div>
  5979. )}
  5980. </div>
  5981. </div>
  5982. );
  5983. })}
  5984. {/* External spool(s) - grouped in one card like regular AMS */}
  5985. {status.vt_tray.length > 0 && showExternalSpool && (
  5986. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5987. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5988. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  5989. </div>
  5990. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  5991. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5992. const extTrayId = extTray.id ?? 254;
  5993. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5994. // generically — use active_extruder to determine L vs R:
  5995. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5996. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5997. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5998. (extTrayId === 255 && status.active_extruder === 0)
  5999. : effectiveTrayNow === extTrayId;
  6000. const slotTrayId = extTrayId - 254; // 0 or 1
  6001. const extLabel = isDualNozzle
  6002. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  6003. : '';
  6004. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  6005. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  6006. // Only trusted while it still describes what the printer reports in the
  6007. // slot: the row survives a spool swap, and the display chain below puts
  6008. // it ahead of the live filament id (see slotPresetDescribesTray).
  6009. const extSlotPresetName = slotPresetDescribesTray(extSlotPreset?.preset_id, extTray.tray_info_idx)
  6010. ? extSlotPreset?.preset_name
  6011. : undefined;
  6012. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  6013. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  6014. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  6015. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6016. const extInventoryFill = (() => {
  6017. const sp = extInventoryAssignment?.spool;
  6018. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  6019. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  6020. }
  6021. return null;
  6022. })();
  6023. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  6024. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  6025. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  6026. ? null : extInventoryFill;
  6027. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  6028. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  6029. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  6030. : undefined;
  6031. const extSlotSpoolForFill = extSlotAssignmentForFill
  6032. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  6033. : undefined;
  6034. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  6035. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  6036. : null;
  6037. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  6038. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  6039. : extResolvedInventoryFill !== null ? 'inventory' as const
  6040. : extHasFillLevel ? 'ams' as const
  6041. : undefined;
  6042. const extFilamentData = {
  6043. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  6044. profile: extSlotPresetName || (extSlotSpoolForFill ? [extSlotSpoolForFill.brand, extSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || extSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || extInventoryAssignment?.spool?.slicer_filament_name || extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
  6045. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  6046. colorHex: extTray.tray_color || null,
  6047. kFactor: formatKValue(extTray.k),
  6048. fillLevel: extEffectiveFill,
  6049. trayUuid: extTray.tray_uuid || null,
  6050. tagUid: extTray.tag_uid || null,
  6051. fillSource: extFillSource,
  6052. };
  6053. const isEmpty = !extTray.tray_type;
  6054. const emptyKind = getEmptySlotKind(extTray);
  6055. const extSlotContent = (
  6056. <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' : ''}`}>
  6057. {/* Color circle: L/R inside on dual-nozzle external (replaces
  6058. the separate Ext-L/Ext-R caption that made the row taller than
  6059. regular AMS slots), 1-based slot number on single-nozzle. */}
  6060. <FilamentSlotCircle
  6061. trayColor={extTray.tray_color}
  6062. trayType={extTray.tray_type}
  6063. isEmpty={isEmpty}
  6064. emptyKind={emptyKind}
  6065. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  6066. />
  6067. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  6068. {extTray.tray_type || t('ams.slotEmpty')}
  6069. </div>
  6070. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  6071. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  6072. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  6073. <div
  6074. className="h-full rounded-full transition-all"
  6075. style={{
  6076. width: `${extEffectiveFill}%`,
  6077. backgroundColor: getFillBarColor(extEffectiveFill),
  6078. }}
  6079. />
  6080. )}
  6081. </div>
  6082. </div>
  6083. );
  6084. return (
  6085. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  6086. {!isEmpty ? (
  6087. <FilamentHoverCard
  6088. data={extFilamentData}
  6089. actions={renderAmsSlotActions({
  6090. amsId: 255,
  6091. slotId: slotTrayId,
  6092. loadTrayId: extTrayId,
  6093. includeRfid: false,
  6094. })}
  6095. spoolman={{
  6096. enabled: spoolmanEnabled,
  6097. // #1457: slot assignment outranks tag-link (see top-level slot block).
  6098. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  6099. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  6100. spoolmanUrl,
  6101. syncMode: spoolmanSyncMode,
  6102. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  6103. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  6104. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  6105. setLinkSpoolModal({
  6106. tagUid: extFilamentData.tagUid || linkTag,
  6107. trayUuid: extFilamentData.trayUuid || '',
  6108. printerId: printer.id,
  6109. amsId: 255,
  6110. trayId: slotTrayId,
  6111. });
  6112. } : undefined,
  6113. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  6114. }}
  6115. inventory={(() => {
  6116. if (spoolmanEnabled) {
  6117. if (spoolmanLoading) return undefined;
  6118. const slotAssignment = extSlotAssignmentForFill;
  6119. const spoolmanSpool = extSlotSpoolForFill;
  6120. return {
  6121. assignedSpool: spoolmanSpool ? {
  6122. id: spoolmanSpool.id,
  6123. material: spoolmanSpool.material,
  6124. subtype: spoolmanSpool.subtype,
  6125. brand: spoolmanSpool.brand ?? null,
  6126. color_name: spoolmanSpool.color_name ?? null,
  6127. color_name_is_synthesized: spoolmanSpool.color_name_is_synthesized,
  6128. // The spool's own swatch (#2967). Spoolman carries the
  6129. // extra stops but has no effect field at all, so those
  6130. // rolls gradient and never shimmer.
  6131. rgba: spoolmanSpool.rgba ?? null,
  6132. extra_colors: spoolmanSpool.extra_colors ?? null,
  6133. effect_type: spoolmanSpool.effect_type ?? null,
  6134. remainingWeightGrams: spoolmanSpool.label_weight
  6135. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  6136. : undefined,
  6137. } : null,
  6138. onAssignSpool: () => setAssignSpoolModal({
  6139. printerId: printer.id,
  6140. amsId: 255,
  6141. trayId: slotTrayId,
  6142. trayInfo: {
  6143. type: extTray.tray_type || extFilamentData.profile,
  6144. material: extTray.tray_type ?? undefined,
  6145. profile: extFilamentData.profile,
  6146. color: extFilamentData.colorHex || '',
  6147. location: extLabel || t('printers.external'),
  6148. },
  6149. }),
  6150. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  6151. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  6152. };
  6153. }
  6154. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  6155. return {
  6156. assignedSpool: assignment?.spool ? {
  6157. id: assignment.spool.id,
  6158. material: assignment.spool.material,
  6159. subtype: assignment.spool.subtype,
  6160. brand: assignment.spool.brand,
  6161. color_name: assignment.spool.color_name,
  6162. // The spool's own swatch (#2967).
  6163. rgba: assignment.spool.rgba ?? null,
  6164. extra_colors: assignment.spool.extra_colors ?? null,
  6165. effect_type: assignment.spool.effect_type ?? null,
  6166. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  6167. } : null,
  6168. onAssignSpool: () => setAssignSpoolModal({
  6169. printerId: printer.id,
  6170. amsId: 255,
  6171. trayId: slotTrayId,
  6172. trayInfo: {
  6173. type: extTray.tray_type || extFilamentData.profile,
  6174. material: extTray.tray_type ?? undefined,
  6175. profile: extFilamentData.profile,
  6176. color: extFilamentData.colorHex || '',
  6177. location: extLabel || t('printers.external'),
  6178. },
  6179. }),
  6180. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  6181. isAssigned: !!assignment || isBambuLabSpool(extTray),
  6182. };
  6183. })()}
  6184. configureSlot={{
  6185. enabled: hasPermission('printers:control'),
  6186. onConfigure: () => setConfigureSlotModal({
  6187. amsId: 255,
  6188. trayId: slotTrayId,
  6189. trayCount: 1,
  6190. trayType: extTray.tray_type || undefined,
  6191. trayColor: extTray.tray_color || undefined,
  6192. traySubBrands: extTray.tray_sub_brands || undefined,
  6193. trayInfoIdx: extTray.tray_info_idx || undefined,
  6194. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6195. caliIdx: extTray.cali_idx,
  6196. savedPresetId: extSlotPreset?.preset_id,
  6197. }),
  6198. }}
  6199. >
  6200. {extSlotContent}
  6201. </FilamentHoverCard>
  6202. ) : (
  6203. <EmptySlotHoverCard
  6204. kind={emptyKind ?? undefined}
  6205. actions={renderAmsSlotActions({
  6206. amsId: 255,
  6207. slotId: slotTrayId,
  6208. loadTrayId: extTrayId,
  6209. includeRfid: false,
  6210. })}
  6211. configureSlot={{
  6212. enabled: hasPermission('printers:control'),
  6213. onConfigure: () => setConfigureSlotModal({
  6214. amsId: 255,
  6215. trayId: slotTrayId,
  6216. trayCount: 1,
  6217. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6218. }),
  6219. }}
  6220. onAssignSpool={() => setAssignSpoolModal({
  6221. printerId: printer.id,
  6222. amsId: 255,
  6223. trayId: slotTrayId,
  6224. trayInfo: {
  6225. type: '',
  6226. material: undefined,
  6227. profile: '',
  6228. color: '',
  6229. location: `External Slot ${slotTrayId + 1}`,
  6230. },
  6231. })}
  6232. >
  6233. {extSlotContent}
  6234. </EmptySlotHoverCard>
  6235. )}
  6236. </div>
  6237. );
  6238. })}
  6239. </div>
  6240. </div>
  6241. )}
  6242. </div>
  6243. </div>
  6244. );
  6245. })()}
  6246. </>
  6247. )}
  6248. {/* Powered-down printer with a dirty plate: the status block above renders
  6249. nothing without a live connection, so the plate-clear control gets its own
  6250. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6251. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6252. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6253. expandedClearPlateButton
  6254. )}
  6255. {/* Bottom block (power row + action bar). Wrapped together so the
  6256. power row hugs the action bar at the card bottom instead of
  6257. floating up when there's less filament content above. */}
  6258. {viewMode === 'expanded' && (
  6259. <div className="mt-auto">
  6260. {smartPlug && (
  6261. <div className="pt-3">
  6262. <div className="flex items-center gap-2 mb-2">
  6263. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6264. {t('printers.power', 'Power')}
  6265. </span>
  6266. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6267. </div>
  6268. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6269. {/* Plug name + current power */}
  6270. <div className="flex items-center gap-2 min-w-0 pl-1">
  6271. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6272. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6273. <span
  6274. 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"
  6275. title={t('smartPlugs.power')}
  6276. >
  6277. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6278. </span>
  6279. </div>
  6280. {/* Spacer */}
  6281. <div className="flex-1" />
  6282. <div className="flex items-center gap-2">
  6283. {/* Auto-off */}
  6284. <button
  6285. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6286. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6287. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6288. 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 ${
  6289. !hasPermission('smart_plugs:control')
  6290. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6291. : smartPlug.auto_off || smartPlug.auto_off_executed
  6292. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6293. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6294. }`}
  6295. >
  6296. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6297. </button>
  6298. <button
  6299. onClick={() => {
  6300. if (plugStatus?.state === 'ON') {
  6301. setShowPowerOffConfirm(true);
  6302. } else {
  6303. setShowPowerOnConfirm(true);
  6304. }
  6305. }}
  6306. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6307. 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 ${
  6308. !hasPermission('smart_plugs:control')
  6309. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6310. : plugStatus?.state === 'ON'
  6311. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6312. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6313. }`}
  6314. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6315. >
  6316. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6317. </button>
  6318. </div>
  6319. </div>
  6320. {/* HA entity buttons row */}
  6321. {scriptPlugs && scriptPlugs.length > 0 && (
  6322. <div className="flex items-center gap-2 mt-2">
  6323. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6324. <span className="text-xs text-bambu-gray">HA:</span>
  6325. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6326. <div className="flex flex-wrap gap-1">
  6327. {scriptPlugs.map(script => {
  6328. const isScript = script.ha_entity_id?.startsWith('script.');
  6329. return (
  6330. <button
  6331. key={script.id}
  6332. onClick={() => {
  6333. if (isScript) {
  6334. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6335. } else {
  6336. setHaToggleConfirm(script);
  6337. }
  6338. }}
  6339. disabled={runScriptMutation.isPending}
  6340. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6341. 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"
  6342. >
  6343. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6344. {script.name}
  6345. </button>
  6346. );
  6347. })}
  6348. </div>
  6349. </div>
  6350. )}
  6351. </div>
  6352. )}
  6353. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6354. a printer can have an enclosure door contact without having a plug,
  6355. and nesting it there would hide the row on exactly those setups. */}
  6356. <PrinterHASensorRow printerId={printer.id} />
  6357. {/* Connection Info & Actions */}
  6358. <div className="pt-4">
  6359. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6360. <div className="flex items-center justify-between gap-2">
  6361. {printerActionsMenu}
  6362. <div className="flex items-center justify-end gap-2 flex-wrap">
  6363. {/* Camera split button: the icon opens whichever view was used
  6364. last, the caret picks between the two and remembers it.
  6365. Replaces the old Settings > General > Camera switch, which
  6366. made choosing between an overlay and a window a trip to
  6367. another page for something you decide per camera. */}
  6368. <div className="flex items-center flex-shrink-0">
  6369. <Button
  6370. variant="secondary"
  6371. size="sm"
  6372. onClick={() => openCameraIn(cameraViewMode)}
  6373. disabled={!status?.connected || !hasPermission('camera:view')}
  6374. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6375. className={`${footerIconButtonClass} !rounded-r-none`}
  6376. >
  6377. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6378. </Button>
  6379. <Button
  6380. variant="secondary"
  6381. size="sm"
  6382. onClick={(e) => {
  6383. // No open/close toggle: the menu's own outside-mousedown
  6384. // handler has already dismissed it by the time this lands.
  6385. const rect = e.currentTarget.getBoundingClientRect();
  6386. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6387. }}
  6388. disabled={!status?.connected || !hasPermission('camera:view')}
  6389. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6390. aria-label={t('settings.cameraViewMode')}
  6391. // Not footerIconButtonClass plus an override: both widths
  6392. // would carry !important and the stylesheet's own order,
  6393. // not this one, would decide which won.
  6394. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6395. >
  6396. <ChevronDown className="w-3 h-3" />
  6397. </Button>
  6398. </div>
  6399. {cameraMenuAnchor && (
  6400. <ContextMenu
  6401. x={cameraMenuAnchor.x}
  6402. y={cameraMenuAnchor.y}
  6403. items={cameraViewModeMenuItems}
  6404. onClose={() => setCameraMenuAnchor(null)}
  6405. />
  6406. )}
  6407. <Button
  6408. variant="secondary"
  6409. size="sm"
  6410. onClick={() => setShowFileManager(true)}
  6411. disabled={!hasPermission('printers:files')}
  6412. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6413. className={footerIconButtonClass}
  6414. >
  6415. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6416. </Button>
  6417. {/* Shown whatever the printer is doing (#2849): this uploads a
  6418. file and queues it, which a busy or offline printer is no
  6419. reason to refuse -- it only means the item waits. Hiding it
  6420. while the drop zone accepted the same file would have left
  6421. the two routes into this flow disagreeing. */}
  6422. <Button
  6423. size="sm"
  6424. onClick={() => setShowUploadForPrint(true)}
  6425. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6426. title={
  6427. !hasPermission('library:upload')
  6428. ? t('fileManager.noPermissionUpload')
  6429. : !hasPermission('queue:create')
  6430. ? t('fileManager.noPermissionAddToQueue')
  6431. : t('common.print')
  6432. }
  6433. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6434. >
  6435. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6436. {t('common.print')}
  6437. </Button>
  6438. </div>
  6439. </div>
  6440. </div>
  6441. </div>
  6442. )}
  6443. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6444. card's horizontal padding instead of running full-bleed into the
  6445. rounded bottom edge. */}
  6446. <ScheduledDryingBanner
  6447. printerId={printer.id}
  6448. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6449. timeFormat={timeFormat}
  6450. />
  6451. </CardContent>
  6452. {/* File Manager Modal */}
  6453. {showFileManager && (
  6454. <FileManagerModal
  6455. printerId={printer.id}
  6456. printerName={printer.name}
  6457. onClose={() => setShowFileManager(false)}
  6458. />
  6459. )}
  6460. {/* Upload for Print Modal */}
  6461. {showUploadForPrint && (
  6462. <FileUploadModal
  6463. folderId={null}
  6464. onClose={() => setShowUploadForPrint(false)}
  6465. onUploadComplete={() => {}}
  6466. autoUpload
  6467. accept=".gcode,.3mf"
  6468. validateFile={(file) => {
  6469. const lower = file.name.toLowerCase();
  6470. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6471. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6472. }
  6473. }}
  6474. onFileUploaded={(uploadedFile) => {
  6475. // Check printer compatibility if sliced_for_model is available in metadata
  6476. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6477. const printerModel = mapModelCode(printer.model);
  6478. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6479. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6480. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6481. }
  6482. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6483. }}
  6484. />
  6485. )}
  6486. {/* Print Modal (after upload) */}
  6487. {printAfterUpload && (
  6488. <PrintModal
  6489. mode="create"
  6490. libraryFileId={printAfterUpload.id}
  6491. archiveName={printAfterUpload.filename}
  6492. initialSelectedPrinterIds={[printer.id]}
  6493. onClose={() => setPrintAfterUpload(null)}
  6494. onSuccess={() => setPrintAfterUpload(null)}
  6495. cleanupLibraryAfterDispatch
  6496. />
  6497. )}
  6498. {/* MQTT Debug Modal */}
  6499. {showMQTTDebug && (
  6500. <MQTTDebugModal
  6501. printerId={printer.id}
  6502. printerName={printer.name}
  6503. onClose={() => setShowMQTTDebug(false)}
  6504. />
  6505. )}
  6506. {showDiagnostic && (
  6507. <ConnectionDiagnosticModal
  6508. printerId={printer.id}
  6509. printerName={printer.name}
  6510. onClose={() => setShowDiagnostic(false)}
  6511. />
  6512. )}
  6513. {showPrinterInfo && (
  6514. <PrinterInfoModal
  6515. printer={printer}
  6516. status={status}
  6517. totalPrintHours={maintenanceInfo?.total_print_hours}
  6518. onClose={closePrinterInfo}
  6519. />
  6520. )}
  6521. {/* Plate Check Result Modal */}
  6522. {plateCheckResult && (
  6523. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6524. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6525. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6526. <div className="flex items-center gap-2">
  6527. {plateCheckResult.needs_calibration ? (
  6528. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6529. ) : plateCheckResult.is_empty ? (
  6530. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6531. ) : (
  6532. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6533. )}
  6534. <h2 className="text-lg font-semibold text-white">
  6535. Build Plate Check
  6536. </h2>
  6537. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6538. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6539. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6540. </span>
  6541. )}
  6542. </div>
  6543. <button
  6544. onClick={() => closePlateCheckModal()}
  6545. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6546. >
  6547. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6548. </button>
  6549. </div>
  6550. <div className="p-4 space-y-4">
  6551. {plateCheckResult.needs_calibration ? (
  6552. <>
  6553. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6554. <p className="font-medium text-blue-700 dark:text-blue-400">
  6555. {t('printers.plateDetection.calibrationRequired')}
  6556. </p>
  6557. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6558. </div>
  6559. <div className="text-sm text-bambu-gray space-y-2">
  6560. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6561. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6562. </div>
  6563. </>
  6564. ) : (
  6565. <>
  6566. <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'}`}>
  6567. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6568. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6569. </p>
  6570. <p className="text-sm text-bambu-gray mt-1">
  6571. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6572. </p>
  6573. </div>
  6574. {plateCheckResult.debug_image_url && (
  6575. <div>
  6576. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6577. <img
  6578. src={plateCheckResult.debug_image_url}
  6579. alt={t('printers.plateDetection.analysisPreview')}
  6580. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6581. />
  6582. <p className="text-xs text-bambu-gray mt-2">
  6583. {t('printers.plateDetection.analysisLegend')}
  6584. </p>
  6585. </div>
  6586. )}
  6587. <p className="text-xs text-bambu-gray">
  6588. {plateCheckResult.message}
  6589. </p>
  6590. </>
  6591. )}
  6592. {/* Saved References Grid */}
  6593. {plateReferences && plateReferences.references.length > 0 && (
  6594. <div className="mt-4">
  6595. <div className="flex items-center gap-2 mb-2">
  6596. <p className="text-sm font-medium text-white shrink-0">
  6597. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6598. </p>
  6599. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6600. </div>
  6601. <div className="grid grid-cols-5 gap-2">
  6602. {plateReferences.references.map((ref) => (
  6603. <div key={ref.index} className="relative group">
  6604. <img
  6605. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6606. alt={ref.label || `Reference ${ref.index + 1}`}
  6607. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6608. />
  6609. {/* Delete button */}
  6610. <button
  6611. onClick={() => handleDeleteRef(ref.index)}
  6612. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  6613. title={t('printers.plateDetection.deleteReference')}
  6614. >
  6615. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6616. </button>
  6617. {/* Label */}
  6618. {editingRefLabel?.index === ref.index ? (
  6619. <input
  6620. type="text"
  6621. value={editingRefLabel.label}
  6622. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6623. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6624. onKeyDown={(e) => {
  6625. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6626. if (e.key === 'Escape') setEditingRefLabel(null);
  6627. }}
  6628. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6629. autoFocus
  6630. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6631. />
  6632. ) : (
  6633. <p
  6634. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6635. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6636. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6637. >
  6638. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6639. </p>
  6640. )}
  6641. {/* Timestamp */}
  6642. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6643. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6644. </p>
  6645. </div>
  6646. ))}
  6647. </div>
  6648. </div>
  6649. )}
  6650. {/* ROI Editor */}
  6651. {!plateCheckResult.needs_calibration && (
  6652. <div className="mt-4">
  6653. <div className="flex items-center justify-between mb-2">
  6654. <div className="flex min-w-0 flex-1 items-center gap-2">
  6655. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6656. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6657. </div>
  6658. {!editingRoi ? (
  6659. <Button
  6660. variant="ghost"
  6661. size="sm"
  6662. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6663. >
  6664. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6665. {t('common.edit')}
  6666. </Button>
  6667. ) : (
  6668. <div className="flex gap-1">
  6669. <Button
  6670. variant="ghost"
  6671. size="sm"
  6672. onClick={() => setEditingRoi(null)}
  6673. disabled={isSavingRoi}
  6674. >
  6675. {t('common.cancel')}
  6676. </Button>
  6677. <Button
  6678. size="sm"
  6679. onClick={handleSaveRoi}
  6680. disabled={isSavingRoi}
  6681. >
  6682. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6683. </Button>
  6684. </div>
  6685. )}
  6686. </div>
  6687. {editingRoi ? (
  6688. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6689. <div className="grid grid-cols-2 gap-3">
  6690. <div>
  6691. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6692. <input
  6693. type="range"
  6694. min="0"
  6695. max="0.9"
  6696. step="0.01"
  6697. value={editingRoi.x}
  6698. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6699. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6700. />
  6701. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6702. </div>
  6703. <div>
  6704. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6705. <input
  6706. type="range"
  6707. min="0"
  6708. max="0.9"
  6709. step="0.01"
  6710. value={editingRoi.y}
  6711. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6712. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6713. />
  6714. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6715. </div>
  6716. <div>
  6717. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6718. <input
  6719. type="range"
  6720. min="0.1"
  6721. max="1"
  6722. step="0.01"
  6723. value={editingRoi.w}
  6724. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6725. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6726. />
  6727. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6728. </div>
  6729. <div>
  6730. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6731. <input
  6732. type="range"
  6733. min="0.1"
  6734. max="1"
  6735. step="0.01"
  6736. value={editingRoi.h}
  6737. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6738. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6739. />
  6740. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6741. </div>
  6742. </div>
  6743. <p className="text-xs text-bambu-gray">
  6744. {t('printers.roi.instruction')}
  6745. </p>
  6746. </div>
  6747. ) : (
  6748. <p className="text-xs text-bambu-gray">
  6749. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6750. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6751. </p>
  6752. )}
  6753. </div>
  6754. )}
  6755. </div>
  6756. <div className="flex justify-end gap-2 p-4">
  6757. {plateCheckResult.needs_calibration ? (
  6758. <>
  6759. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6760. {t('common.cancel')}
  6761. </Button>
  6762. <Button
  6763. onClick={() => handleCalibratePlate()}
  6764. disabled={isCalibrating}
  6765. >
  6766. {isCalibrating ? (
  6767. <>
  6768. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6769. Calibrating...
  6770. </>
  6771. ) : (
  6772. 'Calibrate Empty Plate'
  6773. )}
  6774. </Button>
  6775. </>
  6776. ) : (
  6777. <>
  6778. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6779. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6780. </Button>
  6781. <Button onClick={() => closePlateCheckModal()}>
  6782. Close
  6783. </Button>
  6784. </>
  6785. )}
  6786. </div>
  6787. </div>
  6788. </div>
  6789. )}
  6790. {/* Power On Confirmation */}
  6791. {showPowerOnConfirm && smartPlug && (
  6792. <ConfirmModal
  6793. title={t('printers.confirm.powerOnTitle')}
  6794. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6795. confirmText={t('printers.confirm.powerOnButton')}
  6796. variant="default"
  6797. onConfirm={() => {
  6798. powerControlMutation.mutate('on');
  6799. setShowPowerOnConfirm(false);
  6800. }}
  6801. onCancel={() => setShowPowerOnConfirm(false)}
  6802. />
  6803. )}
  6804. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6805. disconnects MQTT, which stops progress tracking + completion
  6806. notifications for the in-flight job. Idle / FINISH / FAILED states
  6807. skip this dialog and toggle directly. */}
  6808. {confirmMaintenanceEnter && (
  6809. <ConfirmModal
  6810. title={t('printers.maintenance.confirmMidPrintTitle')}
  6811. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6812. confirmText={t('printers.maintenance.menuEnter')}
  6813. variant="danger"
  6814. onConfirm={() => {
  6815. maintenanceMutation.mutate(false);
  6816. setConfirmMaintenanceEnter(false);
  6817. }}
  6818. onCancel={() => setConfirmMaintenanceEnter(false)}
  6819. />
  6820. )}
  6821. {/* Power Off Confirmation */}
  6822. {showPowerOffConfirm && smartPlug && (
  6823. <ConfirmModal
  6824. title={t('printers.confirm.powerOffTitle')}
  6825. message={
  6826. status?.state === 'RUNNING'
  6827. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6828. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6829. }
  6830. confirmText={t('printers.confirm.powerOffButton')}
  6831. variant="danger"
  6832. onConfirm={() => {
  6833. powerControlMutation.mutate('off');
  6834. setShowPowerOffConfirm(false);
  6835. }}
  6836. onCancel={() => setShowPowerOffConfirm(false)}
  6837. />
  6838. )}
  6839. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6840. {haToggleConfirm && (
  6841. <ConfirmModal
  6842. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6843. message={
  6844. status?.state === 'RUNNING'
  6845. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6846. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6847. }
  6848. confirmText={t('printers.confirm.haToggleButton')}
  6849. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6850. onConfirm={() => {
  6851. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6852. setHaToggleConfirm(null);
  6853. }}
  6854. onCancel={() => setHaToggleConfirm(null)}
  6855. />
  6856. )}
  6857. {/* Stop Print Confirmation */}
  6858. {showStopConfirm && (
  6859. <ConfirmModal
  6860. title={t('printers.confirm.stopTitle')}
  6861. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6862. confirmText={t('printers.confirm.stopButton')}
  6863. variant="danger"
  6864. onConfirm={() => {
  6865. stopPrintMutation.mutate();
  6866. setShowStopConfirm(false);
  6867. }}
  6868. onCancel={() => setShowStopConfirm(false)}
  6869. />
  6870. )}
  6871. {/* Pause Print Confirmation */}
  6872. {showPauseConfirm && (
  6873. <ConfirmModal
  6874. title={t('printers.confirm.pauseTitle')}
  6875. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6876. confirmText={t('printers.confirm.pauseButton')}
  6877. variant="default"
  6878. onConfirm={() => {
  6879. pausePrintMutation.mutate();
  6880. setShowPauseConfirm(false);
  6881. }}
  6882. onCancel={() => setShowPauseConfirm(false)}
  6883. />
  6884. )}
  6885. {/* Resume Print Confirmation */}
  6886. {showResumeConfirm && (
  6887. <ConfirmModal
  6888. title={t('printers.confirm.resumeTitle')}
  6889. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6890. confirmText={t('printers.confirm.resumeButton')}
  6891. variant="default"
  6892. onConfirm={() => {
  6893. resumePrintMutation.mutate();
  6894. setShowResumeConfirm(false);
  6895. }}
  6896. onCancel={() => setShowResumeConfirm(false)}
  6897. />
  6898. )}
  6899. {/* Skip Objects Modal */}
  6900. <SkipObjectsModal
  6901. printerId={printer.id}
  6902. isOpen={showSkipObjectsModal}
  6903. onClose={() => setShowSkipObjectsModal(false)}
  6904. />
  6905. {/* HMS Error Modal */}
  6906. {showHMSModal && (
  6907. <HMSErrorModal
  6908. printerName={printer.name}
  6909. errors={status?.hms_errors || []}
  6910. onClose={() => setShowHMSModal(false)}
  6911. printerId={printer.id}
  6912. hasPermission={hasPermission}
  6913. runoutGuidance={runoutGuidance}
  6914. />
  6915. )}
  6916. {/* AI failure detection modal (#1546) */}
  6917. {showAiModal && (
  6918. <AiDetectionModal
  6919. printerName={printer.name}
  6920. detection={aiDetection}
  6921. lastError={aiLastError}
  6922. onClose={() => setShowAiModal(false)}
  6923. />
  6924. )}
  6925. {/* AMS Filament Backup status / control modal (#1762) */}
  6926. {amsBackupModalOpen && status && (
  6927. <AmsBackupModal
  6928. isOpen={amsBackupModalOpen}
  6929. state={status.ams_filament_backup}
  6930. amsUnits={status.ams}
  6931. amsExtruderMap={status.ams_extruder_map}
  6932. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6933. canToggle={hasPermission('printers:control')}
  6934. pending={setAmsBackupMutation.isPending}
  6935. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6936. onClose={() => setAmsBackupModalOpen(false)}
  6937. />
  6938. )}
  6939. {/* AMS History Modal */}
  6940. {amsHistoryModal && (
  6941. <AMSHistoryModal
  6942. isOpen={!!amsHistoryModal}
  6943. onClose={() => setAmsHistoryModal(null)}
  6944. printerId={printer.id}
  6945. printerName={printer.name}
  6946. amsId={amsHistoryModal.amsId}
  6947. amsLabel={amsHistoryModal.amsLabel}
  6948. initialMode={amsHistoryModal.mode}
  6949. thresholds={amsThresholds}
  6950. />
  6951. )}
  6952. {/* Heater History Modal (nozzle / bed / chamber) */}
  6953. {heaterHistoryModal && (
  6954. <HeaterHistoryModal
  6955. isOpen={!!heaterHistoryModal}
  6956. onClose={() => setHeaterHistoryModal(null)}
  6957. printerId={printer.id}
  6958. printerName={printer.name}
  6959. initialKind={heaterHistoryModal.initialKind}
  6960. availableKinds={heaterHistoryModal.availableKinds}
  6961. />
  6962. )}
  6963. {/* Link Spool Modal */}
  6964. {linkSpoolModal && (
  6965. <LinkSpoolModal
  6966. isOpen={!!linkSpoolModal}
  6967. onClose={() => setLinkSpoolModal(null)}
  6968. tagUid={linkSpoolModal.tagUid}
  6969. trayUuid={linkSpoolModal.trayUuid}
  6970. printerId={linkSpoolModal.printerId}
  6971. amsId={linkSpoolModal.amsId}
  6972. trayId={linkSpoolModal.trayId}
  6973. />
  6974. )}
  6975. {/* Assign Spool Modal */}
  6976. {assignSpoolModal && (
  6977. <AssignSpoolModal
  6978. isOpen={!!assignSpoolModal}
  6979. onClose={() => setAssignSpoolModal(null)}
  6980. printerId={assignSpoolModal.printerId}
  6981. amsId={assignSpoolModal.amsId}
  6982. trayId={assignSpoolModal.trayId}
  6983. trayInfo={assignSpoolModal.trayInfo}
  6984. spoolmanEnabled={!!spoolmanEnabled}
  6985. />
  6986. )}
  6987. {/* Configure AMS Slot Modal */}
  6988. {configureSlotModal && (
  6989. <ConfigureAmsSlotModal
  6990. isOpen={!!configureSlotModal}
  6991. onClose={() => setConfigureSlotModal(null)}
  6992. printerId={printer.id}
  6993. slotInfo={configureSlotModal}
  6994. printerModel={mapModelCode(printer.model) || undefined}
  6995. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6996. onSuccess={() => {
  6997. // Refresh slot presets to show updated profile name
  6998. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6999. // Printer status will update automatically via WebSocket when AMS data changes
  7000. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7001. }}
  7002. />
  7003. )}
  7004. {/* Which hotend to feed — only asked on a printer with a Filament Track Switch */}
  7005. {feedDirectionRequest && (
  7006. <FeedDirectionModal
  7007. slotLabel={feedDirectionRequest.slotLabel}
  7008. amsId={feedDirectionRequest.amsId}
  7009. slotId={feedDirectionRequest.slotId}
  7010. extruderSlots={status?.extruder_slots ?? {}}
  7011. isLoading={loadAmsTrayMutation.isPending}
  7012. onConfirm={(extruderId) =>
  7013. loadAmsTrayMutation.mutate({ trayId: feedDirectionRequest.trayId, extruderId })
  7014. }
  7015. onCancel={() => setFeedDirectionRequest(null)}
  7016. />
  7017. )}
  7018. {/* Edit Printer Modal */}
  7019. {showEditModal && (
  7020. <EditPrinterModal
  7021. printer={printer}
  7022. onClose={() => setShowEditModal(false)}
  7023. />
  7024. )}
  7025. {/* Firmware Update Modal */}
  7026. {showFirmwareModal && firmwareInfo && (
  7027. <FirmwareUpdateModal
  7028. printer={printer}
  7029. firmwareInfo={firmwareInfo}
  7030. onClose={() => setShowFirmwareModal(false)}
  7031. />
  7032. )}
  7033. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  7034. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  7035. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  7036. const sliderMin = 35;
  7037. const sliderMax = maxTemp + 10;
  7038. return (
  7039. <>
  7040. {/* Backdrop */}
  7041. <div
  7042. className="fixed inset-0 z-[100]"
  7043. data-testid="drying-popover-backdrop"
  7044. onMouseDown={() => {
  7045. // The click that dismisses the native datetime picker lands
  7046. // here; it must not close the popover. The input is still
  7047. // focused at mousedown, so remember that and swallow the
  7048. // matching click.
  7049. dryingBackdropSkipCloseRef.current =
  7050. dryingAtTimeInputRef.current !== null &&
  7051. document.activeElement === dryingAtTimeInputRef.current;
  7052. }}
  7053. onClick={() => {
  7054. if (dryingBackdropSkipCloseRef.current) {
  7055. dryingBackdropSkipCloseRef.current = false;
  7056. return;
  7057. }
  7058. setDryingPopoverAmsId(null);
  7059. }}
  7060. />
  7061. {/* An 'above' popover is anchored by its bottom edge (CSS
  7062. bottom) so late-appearing content grows it upward, staying on
  7063. screen and glued to the trigger. maxHeight caps to the space
  7064. on the anchored side; when the viewport is too short the body
  7065. scrolls and the footer stays pinned. dvh so iOS Safari's
  7066. bottom toolbar doesn't clip the footer. */}
  7067. <div
  7068. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  7069. style={{
  7070. left: dryingPopoverPos.left,
  7071. ...(dryingPopoverPos.placement === 'above'
  7072. ? {
  7073. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  7074. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  7075. }
  7076. : {
  7077. top: dryingPopoverPos.top,
  7078. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  7079. }),
  7080. }}
  7081. onClick={e => e.stopPropagation()}
  7082. >
  7083. {/* Header */}
  7084. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  7085. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  7086. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  7087. </div>
  7088. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7089. {/* Body */}
  7090. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  7091. {/* Filament type select */}
  7092. <div>
  7093. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  7094. <ToolbarDropdown
  7095. value={dryingFilament}
  7096. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  7097. onChange={fil => {
  7098. setDryingFilament(fil);
  7099. const preset = dryingPresets[fil];
  7100. if (preset) {
  7101. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  7102. setDryingTemp(preset[key]);
  7103. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  7104. }
  7105. }}
  7106. fullWidth
  7107. />
  7108. </div>
  7109. {/* Temperature */}
  7110. <div>
  7111. <div className="flex items-center justify-between mb-1">
  7112. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  7113. <div className="flex items-center gap-1">
  7114. <NumberInput
  7115. min={45}
  7116. max={maxTemp}
  7117. value={dryingTemp}
  7118. onChange={setDryingTemp}
  7119. fallback={45}
  7120. 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"
  7121. />
  7122. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  7123. </div>
  7124. </div>
  7125. <input
  7126. type="range"
  7127. min={sliderMin}
  7128. max={sliderMax}
  7129. value={dryingTemp}
  7130. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  7131. className="w-full h-1 accent-bambu-green cursor-pointer"
  7132. />
  7133. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7134. <span>45°C</span>
  7135. <span>{maxTemp}°C</span>
  7136. </div>
  7137. </div>
  7138. {/* Duration */}
  7139. <div>
  7140. <div className="flex items-center justify-between mb-1">
  7141. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  7142. <div className="flex items-center gap-1">
  7143. <NumberInput
  7144. min={1}
  7145. max={24}
  7146. value={dryingDuration}
  7147. onChange={setDryingDuration}
  7148. fallback={1}
  7149. 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"
  7150. />
  7151. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  7152. </div>
  7153. </div>
  7154. <input
  7155. type="range"
  7156. min={1}
  7157. max={24}
  7158. value={dryingDuration}
  7159. onChange={e => setDryingDuration(Number(e.target.value))}
  7160. className="w-full h-1 accent-bambu-green cursor-pointer"
  7161. />
  7162. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  7163. <span>1h</span>
  7164. <span>24h</span>
  7165. </div>
  7166. </div>
  7167. {/* Rotate tray — disabled when any tray in THIS AMS has its
  7168. filament threaded out into the feed tube. The whole AMS
  7169. rotates as one mechanism (all 4 spools turn together), so a
  7170. single loaded slot locks the entire unit. Bambu per-tray
  7171. `state`: 9 = empty, 10 = spool present but not loaded
  7172. (rotation possible), 11 = loaded into tube (rotation impossible).
  7173. Catches both mid-print (active feed) AND idle-with-threaded-
  7174. filament — the H2D's post-print state leaves filament in the
  7175. tube but tray_now resets to 255, which a tray_now-only check
  7176. would silently miss. */}
  7177. {(() => {
  7178. const targetAms = dryingPopoverAmsId !== null
  7179. ? amsData.find(a => a.id === dryingPopoverAmsId)
  7180. : undefined;
  7181. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7182. tray => tray.state === 11,
  7183. );
  7184. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  7185. return (
  7186. <button
  7187. type="button"
  7188. onClick={() => setDryingRotateTray(enabled => !enabled)}
  7189. aria-pressed={rotateChecked}
  7190. disabled={trayLoadedInThisAms}
  7191. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  7192. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  7193. rotateChecked
  7194. ? 'bg-bambu-green border-bambu-green text-white'
  7195. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  7196. }`}
  7197. >
  7198. {t('printers.drying.rotateTray')}
  7199. </button>
  7200. );
  7201. })()}
  7202. {/* Start mode: now / after delay / at time (#2638) */}
  7203. <div>
  7204. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7205. <div className="grid grid-cols-3 gap-1">
  7206. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7207. <button
  7208. key={mode}
  7209. type="button"
  7210. onClick={() => setDryingStartMode(mode)}
  7211. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7212. dryingStartMode === mode
  7213. ? 'bg-bambu-green border-bambu-green text-white'
  7214. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7215. }`}
  7216. >
  7217. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7218. </button>
  7219. ))}
  7220. </div>
  7221. {dryingStartMode === 'delay' && (
  7222. // Inline chips: a dropdown menu would be clipped by
  7223. // the popover's scrollable body.
  7224. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7225. {DRYING_DELAY_OPTIONS.map(min => (
  7226. <button
  7227. key={min}
  7228. type="button"
  7229. aria-pressed={dryingDelayMinutes === min}
  7230. onClick={() => setDryingDelayMinutes(min)}
  7231. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7232. dryingDelayMinutes === min
  7233. ? 'bg-bambu-green border-bambu-green text-white'
  7234. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7235. }`}
  7236. >
  7237. {formatDurationFromHours(min / 60)}
  7238. </button>
  7239. ))}
  7240. </div>
  7241. )}
  7242. {dryingStartMode === 'at_time' && (
  7243. <input
  7244. ref={dryingAtTimeInputRef}
  7245. type="datetime-local"
  7246. data-testid="drying-start-at"
  7247. value={dryingStartAt}
  7248. onChange={e => setDryingStartAt(e.target.value)}
  7249. className="mt-1.5 w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] focus:outline-none focus:border-bambu-green [color-scheme:dark]"
  7250. />
  7251. )}
  7252. </div>
  7253. </div>
  7254. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7255. {/* Footer */}
  7256. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7257. <button
  7258. onClick={() => {
  7259. if (dryingPopoverAmsId !== null) {
  7260. // Clamp rotateTray off when any tray in this AMS is loaded into
  7261. // the tube — the rotate UI is disabled there, but the state may
  7262. // linger as `true` from a previous AMS, or a print may have
  7263. // started while the popover was open. Without this clamp the
  7264. // Start payload would carry rotate_tray=true and firmware would
  7265. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7266. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7267. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7268. tray => tray.state === 11,
  7269. );
  7270. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7271. if (dryingStartMode === 'now') {
  7272. startDryingMutation.mutate({
  7273. amsId: dryingPopoverAmsId,
  7274. temp: dryingTemp,
  7275. duration: dryingDuration,
  7276. filament: dryingFilament,
  7277. rotateTray: rotate,
  7278. });
  7279. } else {
  7280. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7281. if (startAfter) {
  7282. scheduleDryingMutation.mutate({
  7283. amsId: dryingPopoverAmsId,
  7284. temp: dryingTemp,
  7285. duration: dryingDuration,
  7286. filament: dryingFilament,
  7287. rotateTray: rotate,
  7288. startAfter,
  7289. });
  7290. }
  7291. }
  7292. }
  7293. }}
  7294. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7295. data-testid="drying-start-confirm"
  7296. 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"
  7297. >
  7298. {dryingStartMode === 'now'
  7299. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7300. : t('printers.drying.schedule')}
  7301. </button>
  7302. </div>
  7303. </div>
  7304. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7305. since the popover clips its own overflow. */}
  7306. <div
  7307. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7308. style={{
  7309. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7310. top: dryingPopoverPos.anchorY - 5,
  7311. ...(dryingPopoverPos.placement === 'above'
  7312. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7313. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7314. }}
  7315. />
  7316. </>
  7317. );
  7318. })()}
  7319. </Card>
  7320. );
  7321. }
  7322. export function AddPrinterModal({
  7323. onClose,
  7324. onAdd,
  7325. existingSerials,
  7326. }: {
  7327. onClose: () => void;
  7328. onAdd: (data: PrinterCreate) => void;
  7329. existingSerials: string[];
  7330. }) {
  7331. const { t } = useTranslation();
  7332. const [form, setForm] = useState<PrinterCreate>({
  7333. name: '',
  7334. serial_number: '',
  7335. ip_address: '',
  7336. access_code: '',
  7337. model: '',
  7338. location: '',
  7339. auto_archive: true,
  7340. });
  7341. // Discovery state
  7342. const [discovering, setDiscovering] = useState(false);
  7343. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7344. const [discoveryError, setDiscoveryError] = useState('');
  7345. const [hasScanned, setHasScanned] = useState(false);
  7346. const [isDocker, setIsDocker] = useState(false);
  7347. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7348. const [subnet, setSubnet] = useState('');
  7349. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7350. // text input so users can scan a subnet Bambuddy isn't directly on
  7351. // (printer behind a router on a different L3 segment — SSDP multicast
  7352. // won't cross that boundary, only an active unicast scan will). #1564
  7353. const [customSubnet, setCustomSubnet] = useState('');
  7354. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7355. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7356. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7357. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7358. // (not block) when checks fail, so the user doesn't add a printer that
  7359. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7360. // failed result awaiting an explicit "save anyway".
  7361. const [checkingSave, setCheckingSave] = useState(false);
  7362. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7363. // Fetch discovery info on mount + restore the last custom CIDR the user
  7364. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7365. // time they open this modal).
  7366. useEffect(() => {
  7367. discoveryApi.getInfo().then(info => {
  7368. setIsDocker(info.is_docker);
  7369. if (info.subnets.length > 0) {
  7370. setDetectedSubnets(info.subnets);
  7371. setSubnet(info.subnets[0]);
  7372. }
  7373. }).catch(() => {
  7374. // Ignore errors, assume not Docker
  7375. });
  7376. try {
  7377. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7378. if (saved) setCustomSubnet(saved);
  7379. } catch {
  7380. // localStorage unavailable (private mode, quota); recall is opportunistic
  7381. }
  7382. }, []);
  7383. // Filter out already-added printers
  7384. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7385. const handleAddSubmit = async (e: React.FormEvent) => {
  7386. e.preventDefault();
  7387. setCheckingSave(true);
  7388. try {
  7389. const result = await api.diagnoseConnection({
  7390. ip_address: form.ip_address.trim(),
  7391. serial_number: form.serial_number.trim() || undefined,
  7392. access_code: form.access_code || undefined,
  7393. });
  7394. if (result.checks.some((c) => c.status === 'fail')) {
  7395. setSaveWarning(result);
  7396. return;
  7397. }
  7398. } catch {
  7399. // Diagnostic infrastructure failed — never block the save on it.
  7400. } finally {
  7401. setCheckingSave(false);
  7402. }
  7403. onAdd(form);
  7404. };
  7405. const startDiscovery = async () => {
  7406. setDiscoveryError('');
  7407. setDiscovered([]);
  7408. setDiscovering(true);
  7409. setHasScanned(false);
  7410. setScanProgress({ scanned: 0, total: 0 });
  7411. // Native installs fall back to subnet scanning when the user picks
  7412. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7413. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7414. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7415. const wantsSubnetScan = isDocker || useCustomSubnet;
  7416. if (wantsSubnetScan && useCustomSubnet) {
  7417. try {
  7418. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7419. } catch {
  7420. // localStorage write best-effort; user just retypes next time
  7421. }
  7422. }
  7423. try {
  7424. if (wantsSubnetScan) {
  7425. await discoveryApi.startSubnetScan(scanCidr);
  7426. // Poll for scan status and results
  7427. const pollInterval = setInterval(async () => {
  7428. try {
  7429. const status = await discoveryApi.getScanStatus();
  7430. setScanProgress({ scanned: status.scanned, total: status.total });
  7431. const printers = await discoveryApi.getDiscoveredPrinters();
  7432. setDiscovered(printers);
  7433. if (!status.running) {
  7434. clearInterval(pollInterval);
  7435. setDiscovering(false);
  7436. setHasScanned(true);
  7437. }
  7438. } catch (e) {
  7439. console.error('Failed to get scan status:', e);
  7440. }
  7441. }, 500);
  7442. } else {
  7443. // Use SSDP discovery for native installs
  7444. await discoveryApi.startDiscovery(10);
  7445. // Poll for discovered printers every second
  7446. const pollInterval = setInterval(async () => {
  7447. try {
  7448. const printers = await discoveryApi.getDiscoveredPrinters();
  7449. setDiscovered(printers);
  7450. } catch (e) {
  7451. console.error('Failed to get discovered printers:', e);
  7452. }
  7453. }, 1000);
  7454. // Stop after 10 seconds
  7455. setTimeout(async () => {
  7456. clearInterval(pollInterval);
  7457. try {
  7458. await discoveryApi.stopDiscovery();
  7459. } catch {
  7460. // Ignore stop errors
  7461. }
  7462. setDiscovering(false);
  7463. setHasScanned(true);
  7464. // Final fetch
  7465. try {
  7466. const printers = await discoveryApi.getDiscoveredPrinters();
  7467. setDiscovered(printers);
  7468. } catch (e) {
  7469. console.error('Failed to get final discovered printers:', e);
  7470. }
  7471. }, 10000);
  7472. }
  7473. } catch (e) {
  7474. console.error('Failed to start discovery:', e);
  7475. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7476. setDiscovering(false);
  7477. setHasScanned(true);
  7478. }
  7479. };
  7480. // Reuse module-level mapModelCode
  7481. const selectPrinter = (printer: DiscoveredPrinter) => {
  7482. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7483. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7484. setForm({
  7485. ...form,
  7486. name: printer.name || '',
  7487. serial_number: serialNumber,
  7488. ip_address: printer.ip_address,
  7489. model: mapModelCode(printer.model),
  7490. });
  7491. // Clear discovery results after selection
  7492. setDiscovered([]);
  7493. };
  7494. // Cleanup discovery on unmount
  7495. useEffect(() => {
  7496. return () => {
  7497. discoveryApi.stopDiscovery().catch(() => {});
  7498. discoveryApi.stopSubnetScan().catch(() => {});
  7499. };
  7500. }, []);
  7501. // Close on Escape key
  7502. useEffect(() => {
  7503. const handleKeyDown = (e: KeyboardEvent) => {
  7504. if (e.key === 'Escape') onClose();
  7505. };
  7506. window.addEventListener('keydown', handleKeyDown);
  7507. return () => window.removeEventListener('keydown', handleKeyDown);
  7508. }, [onClose]);
  7509. return (
  7510. <>
  7511. <div
  7512. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7513. onClick={onClose}
  7514. >
  7515. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7516. <CardContent>
  7517. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7518. {/* Discovery Section */}
  7519. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7520. {/* Subnet picker — always visible. The dropdown lists detected
  7521. interface subnets and a "Custom..." sentinel that reveals
  7522. a CIDR text input for printers on a different L3 segment
  7523. (router, VLAN, etc.). #1564 */}
  7524. <div className="mb-3">
  7525. <label className="block text-sm text-bambu-gray mb-1">
  7526. {t('printers.discovery.subnetToScan')}
  7527. </label>
  7528. {detectedSubnets.length > 0 ? (
  7529. <select
  7530. 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"
  7531. value={useCustomSubnet ? '__custom__' : subnet}
  7532. onChange={(e) => {
  7533. if (e.target.value === '__custom__') {
  7534. setUseCustomSubnet(true);
  7535. } else {
  7536. setUseCustomSubnet(false);
  7537. setSubnet(e.target.value);
  7538. }
  7539. }}
  7540. disabled={discovering}
  7541. >
  7542. {detectedSubnets.map(s => (
  7543. <option key={s} value={s}>{s}</option>
  7544. ))}
  7545. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7546. </select>
  7547. ) : (
  7548. <input
  7549. type="text"
  7550. 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"
  7551. value={subnet}
  7552. onChange={(e) => setSubnet(e.target.value)}
  7553. placeholder="192.168.1.0/24"
  7554. disabled={discovering}
  7555. />
  7556. )}
  7557. {useCustomSubnet && (
  7558. <input
  7559. type="text"
  7560. aria-label={t('printers.discovery.customSubnetLabel')}
  7561. 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"
  7562. value={customSubnet}
  7563. onChange={(e) => setCustomSubnet(e.target.value)}
  7564. placeholder="10.1.1.0/24"
  7565. disabled={discovering}
  7566. />
  7567. )}
  7568. <p className="mt-1 text-xs text-bambu-gray">
  7569. {isDocker
  7570. ? t('printers.discovery.dockerNote')
  7571. : t('printers.discovery.customSubnetNote')}
  7572. </p>
  7573. </div>
  7574. <Button
  7575. type="button"
  7576. variant="secondary"
  7577. onClick={startDiscovery}
  7578. disabled={discovering}
  7579. className="w-full"
  7580. >
  7581. {discovering ? (
  7582. <>
  7583. <Loader2 className="w-4 h-4 animate-spin" />
  7584. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7585. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7586. : t('printers.discovery.scanning')}
  7587. </>
  7588. ) : (
  7589. <>
  7590. <Search className="w-4 h-4" />
  7591. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7592. </>
  7593. )}
  7594. </Button>
  7595. {discoveryError && (
  7596. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7597. )}
  7598. {newPrinters.length > 0 && (
  7599. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7600. {newPrinters.map((printer) => (
  7601. <div
  7602. key={printer.serial}
  7603. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7604. onClick={() => selectPrinter(printer)}
  7605. >
  7606. <div className="min-w-0 flex-1">
  7607. <p className="font-medium text-white text-sm truncate">
  7608. {printer.name || printer.serial}
  7609. </p>
  7610. <p className="text-xs text-bambu-gray truncate">
  7611. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7612. {printer.serial.startsWith('unknown-') && (
  7613. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7614. )}
  7615. </p>
  7616. </div>
  7617. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7618. </div>
  7619. ))}
  7620. </div>
  7621. )}
  7622. {discovering && (
  7623. <p className="mt-2 text-sm text-bambu-gray text-center">
  7624. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7625. </p>
  7626. )}
  7627. {hasScanned && !discovering && discovered.length === 0 && (
  7628. <p className="mt-2 text-sm text-bambu-gray text-center">
  7629. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7630. </p>
  7631. )}
  7632. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7633. <p className="mt-2 text-sm text-bambu-gray text-center">
  7634. {t('printers.discovery.allConfigured')}
  7635. </p>
  7636. )}
  7637. </div>
  7638. <form onSubmit={handleAddSubmit} className="space-y-4">
  7639. <div>
  7640. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7641. <input
  7642. type="text"
  7643. required
  7644. 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"
  7645. value={form.name}
  7646. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7647. placeholder={t('printers.modal.myPrinter')}
  7648. />
  7649. </div>
  7650. <div>
  7651. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7652. <input
  7653. type="text"
  7654. required
  7655. 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])?)*)"
  7656. 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"
  7657. value={form.ip_address}
  7658. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7659. placeholder="192.168.1.100 or printer.local"
  7660. />
  7661. </div>
  7662. <div>
  7663. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7664. <input
  7665. type="text"
  7666. required
  7667. 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"
  7668. value={form.serial_number}
  7669. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7670. placeholder="01P00A000000000"
  7671. />
  7672. </div>
  7673. <div>
  7674. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7675. <input
  7676. type="password"
  7677. required
  7678. 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"
  7679. value={form.access_code}
  7680. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7681. placeholder={t('printers.modal.fromPrinterSettings')}
  7682. />
  7683. </div>
  7684. <div>
  7685. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7686. <select
  7687. 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"
  7688. value={form.model || ''}
  7689. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7690. >
  7691. <option value="">{t('printers.modal.selectModel')}</option>
  7692. <optgroup label="A1 Series">
  7693. <option value="A1">A1</option>
  7694. <option value="A1 Mini">A1 Mini</option>
  7695. </optgroup>
  7696. <optgroup label="A2 Series">
  7697. <option value="A2L">A2L</option>
  7698. </optgroup>
  7699. <optgroup label="H2 Series">
  7700. <option value="H2C">H2C</option>
  7701. <option value="H2D">H2D</option>
  7702. <option value="H2D Pro">H2D Pro</option>
  7703. <option value="H2S">H2S</option>
  7704. </optgroup>
  7705. <optgroup label="P Series">
  7706. <option value="P1P">P1P</option>
  7707. <option value="P1S">P1S</option>
  7708. <option value="P2S">P2S</option>
  7709. </optgroup>
  7710. <optgroup label="X1 Series">
  7711. <option value="X1">X1</option>
  7712. <option value="X1C">X1 Carbon</option>
  7713. <option value="X1E">X1E</option>
  7714. </optgroup>
  7715. <optgroup label="X2 Series">
  7716. <option value="X2D">X2D</option>
  7717. </optgroup>
  7718. </select>
  7719. </div>
  7720. <div>
  7721. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7722. <input
  7723. type="text"
  7724. 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"
  7725. value={form.location || ''}
  7726. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7727. placeholder={t('printers.modal.locationPlaceholder')}
  7728. />
  7729. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7730. </div>
  7731. <div className="flex items-center gap-2">
  7732. <input
  7733. type="checkbox"
  7734. id="auto_archive"
  7735. checked={form.auto_archive}
  7736. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7737. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7738. />
  7739. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7740. {t('printers.modal.autoArchiveLabel')}
  7741. </label>
  7742. </div>
  7743. <button
  7744. type="button"
  7745. onClick={() => setShowDiagnostic(true)}
  7746. disabled={!form.ip_address.trim()}
  7747. 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"
  7748. >
  7749. <Stethoscope className="w-4 h-4" />
  7750. {t('diagnostic.runButton')}
  7751. </button>
  7752. {saveWarning ? (
  7753. <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">
  7754. <div className="flex items-start gap-2">
  7755. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7756. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7757. </div>
  7758. <DiagnosticChecklist result={saveWarning} />
  7759. <div className="flex gap-3">
  7760. <Button
  7761. type="button"
  7762. variant="secondary"
  7763. onClick={() => setSaveWarning(null)}
  7764. className="flex-1"
  7765. >
  7766. {t('printers.addPreflight.back')}
  7767. </Button>
  7768. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7769. {t('printers.addPreflight.saveAnyway')}
  7770. </Button>
  7771. </div>
  7772. </div>
  7773. ) : (
  7774. <div className="flex gap-3 pt-2">
  7775. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7776. {t('common.cancel')}
  7777. </Button>
  7778. <Button type="submit" disabled={checkingSave} className="flex-1">
  7779. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7780. </Button>
  7781. </div>
  7782. )}
  7783. </form>
  7784. </CardContent>
  7785. </Card>
  7786. </div>
  7787. {showDiagnostic && (
  7788. <ConnectionDiagnosticModal
  7789. connection={{
  7790. ip_address: form.ip_address.trim(),
  7791. serial_number: form.serial_number.trim() || undefined,
  7792. access_code: form.access_code || undefined,
  7793. }}
  7794. printerName={form.name || null}
  7795. onClose={() => setShowDiagnostic(false)}
  7796. />
  7797. )}
  7798. </>
  7799. );
  7800. }
  7801. function FirmwareUpdateModal({
  7802. printer,
  7803. firmwareInfo,
  7804. onClose,
  7805. }: {
  7806. printer: Printer;
  7807. firmwareInfo: FirmwareUpdateInfo;
  7808. onClose: () => void;
  7809. }) {
  7810. const { t } = useTranslation();
  7811. const queryClient = useQueryClient();
  7812. const { showToast } = useToast();
  7813. const { hasPermission } = useAuth();
  7814. const canUpdate = hasPermission('firmware:update');
  7815. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7816. const [isUploading, setIsUploading] = useState(false);
  7817. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7818. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7819. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7820. );
  7821. // Prepare check query — runs when a version is selected and user can update
  7822. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7823. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7824. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7825. staleTime: 30000,
  7826. enabled: !!selectedVersion && canUpdate && !isUploading,
  7827. });
  7828. // Start upload mutation
  7829. const uploadMutation = useMutation({
  7830. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7831. onSuccess: () => {
  7832. setIsUploading(true);
  7833. // Start polling for status
  7834. const interval = setInterval(async () => {
  7835. try {
  7836. const status = await firmwareApi.getUploadStatus(printer.id);
  7837. setUploadStatus(status);
  7838. if (status.status === 'complete' || status.status === 'error') {
  7839. clearInterval(interval);
  7840. setPollInterval(null);
  7841. setIsUploading(false);
  7842. if (status.status === 'complete') {
  7843. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7844. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7845. }
  7846. }
  7847. } catch {
  7848. // Ignore errors during polling
  7849. }
  7850. }, 2000);
  7851. setPollInterval(interval);
  7852. },
  7853. onError: (error: Error) => {
  7854. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7855. setIsUploading(false);
  7856. },
  7857. });
  7858. // Cleanup on unmount
  7859. useEffect(() => {
  7860. return () => {
  7861. if (pollInterval) clearInterval(pollInterval);
  7862. };
  7863. }, [pollInterval]);
  7864. const handleStartUpload = () => {
  7865. setUploadStatus(null);
  7866. uploadMutation.mutate();
  7867. };
  7868. return (
  7869. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7870. <Card className="w-full max-w-md mx-4">
  7871. <CardContent>
  7872. <div className="flex items-start gap-3 mb-4">
  7873. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7874. {firmwareInfo.update_available
  7875. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7876. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7877. </div>
  7878. <div className="flex-1">
  7879. <h3 className="text-lg font-semibold text-white">
  7880. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7881. </h3>
  7882. <p className="text-sm text-bambu-gray mt-1">
  7883. {printer.name}
  7884. </p>
  7885. </div>
  7886. </div>
  7887. {/* Version Info */}
  7888. {(() => {
  7889. const selectedEntry = selectedVersion
  7890. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7891. : null;
  7892. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7893. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7894. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7895. return (
  7896. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7897. <div className="flex justify-between items-center text-sm">
  7898. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7899. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7900. {firmwareInfo.current_version || t('common.unknown')}
  7901. </span>
  7902. </div>
  7903. {showSecondLine && (
  7904. <div className="flex justify-between items-center text-sm mt-1">
  7905. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7906. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7907. </div>
  7908. )}
  7909. {displayNotes && (
  7910. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7911. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7912. {t('printers.firmwareModal.releaseNotes')}
  7913. </summary>
  7914. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7915. {displayNotes}
  7916. </div>
  7917. </details>
  7918. )}
  7919. </div>
  7920. );
  7921. })()}
  7922. {/* Available versions list */}
  7923. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7924. <div className="mb-4">
  7925. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7926. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7927. {firmwareInfo.available_versions.map((v) => {
  7928. const isCurrent = firmwareInfo.current_version === v.version;
  7929. const isSelected = selectedVersion === v.version;
  7930. const cmp = firmwareInfo.current_version
  7931. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7932. : 0;
  7933. const relLabel = isCurrent
  7934. ? t('printers.firmwareModal.currentBadge')
  7935. : cmp > 0
  7936. ? t('printers.firmwareModal.newerBadge')
  7937. : t('printers.firmwareModal.olderBadge');
  7938. const relClass = isCurrent
  7939. ? 'text-bambu-gray'
  7940. : cmp > 0
  7941. ? 'text-orange-700 dark:text-orange-400'
  7942. : 'text-blue-700 dark:text-blue-400';
  7943. return (
  7944. <button
  7945. key={v.version}
  7946. type="button"
  7947. disabled={!v.file_available || !canUpdate || isCurrent}
  7948. onClick={() => setSelectedVersion(v.version)}
  7949. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7950. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7951. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7952. >
  7953. <div className="flex items-center gap-2 min-w-0">
  7954. <span className="font-mono text-white">{v.version}</span>
  7955. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7956. </div>
  7957. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7958. isCurrent
  7959. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7960. : v.file_available
  7961. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7962. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7963. }`}>
  7964. {isCurrent
  7965. ? t('printers.firmwareModal.installed')
  7966. : v.file_available
  7967. ? t('printers.firmwareModal.usable')
  7968. : t('printers.firmwareModal.unavailable')}
  7969. </span>
  7970. </button>
  7971. );
  7972. })}
  7973. </div>
  7974. </div>
  7975. )}
  7976. {/* Status / Progress (only when a version is selected) */}
  7977. {!selectedVersion ? null : isPreparing ? (
  7978. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7979. <Loader2 className="w-4 h-4 animate-spin" />
  7980. {t('printers.firmwareModal.checkingPrereqs')}
  7981. </div>
  7982. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7983. <div className="mb-4">
  7984. {prepareInfo.can_proceed ? (
  7985. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7986. <Box className="w-4 h-4" />
  7987. {t('printers.firmwareModal.sdCardReady')}
  7988. </div>
  7989. ) : (
  7990. <div className="space-y-1">
  7991. {prepareInfo.errors.map((error, i) => (
  7992. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7993. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7994. {error}
  7995. </div>
  7996. ))}
  7997. </div>
  7998. )}
  7999. </div>
  8000. ) : null}
  8001. {/* Upload Progress */}
  8002. {(isUploading || uploadStatus) && uploadStatus && (
  8003. <div className="mb-4">
  8004. <div className="flex items-center justify-between text-sm mb-1">
  8005. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  8006. <span className="text-white">{uploadStatus.progress}%</span>
  8007. </div>
  8008. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  8009. <div
  8010. className={`h-2 rounded-full transition-all ${
  8011. uploadStatus.status === 'error' ? 'bg-status-error' :
  8012. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  8013. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  8014. style={{ width: `${uploadStatus.progress}%` }}
  8015. />
  8016. </div>
  8017. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  8018. {uploadStatus.error && (
  8019. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  8020. )}
  8021. </div>
  8022. )}
  8023. {/* Success Message */}
  8024. {uploadStatus?.status === 'complete' && (
  8025. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  8026. <p className="text-sm text-bambu-green font-medium mb-2">
  8027. {t('printers.firmwareModal.uploadedSuccess')}
  8028. </p>
  8029. <p className="text-xs text-bambu-gray">
  8030. {t('printers.firmwareModal.applyInstructions')}
  8031. </p>
  8032. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  8033. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  8034. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  8035. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  8036. <li>{t('printers.firmwareModal.step4')}</li>
  8037. </ol>
  8038. </div>
  8039. )}
  8040. {/* Buttons */}
  8041. <div className="flex gap-2 justify-end">
  8042. <Button variant="secondary" onClick={onClose}>
  8043. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  8044. </Button>
  8045. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  8046. <Button
  8047. onClick={handleStartUpload}
  8048. disabled={uploadMutation.isPending}
  8049. >
  8050. {uploadMutation.isPending ? (
  8051. <>
  8052. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  8053. {t('printers.firmwareModal.starting')}
  8054. </>
  8055. ) : (
  8056. <>
  8057. <Download className="w-4 h-4 mr-2" />
  8058. {t('printers.firmwareModal.uploadFirmware')}
  8059. </>
  8060. )}
  8061. </Button>
  8062. )}
  8063. </div>
  8064. </CardContent>
  8065. </Card>
  8066. </div>
  8067. );
  8068. }
  8069. function EditPrinterModal({
  8070. printer,
  8071. onClose,
  8072. }: {
  8073. printer: Printer;
  8074. onClose: () => void;
  8075. }) {
  8076. const { t } = useTranslation();
  8077. const queryClient = useQueryClient();
  8078. const { showToast } = useToast();
  8079. const [form, setForm] = useState({
  8080. name: printer.name,
  8081. ip_address: printer.ip_address,
  8082. access_code: '',
  8083. model: printer.model || '',
  8084. location: printer.location || '',
  8085. auto_archive: printer.auto_archive,
  8086. is_active: printer.is_active,
  8087. });
  8088. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  8089. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  8090. const [checkingSave, setCheckingSave] = useState(false);
  8091. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  8092. const updateMutation = useMutation({
  8093. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  8094. onSuccess: () => {
  8095. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8096. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  8097. onClose();
  8098. },
  8099. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  8100. });
  8101. // Close on Escape key
  8102. useEffect(() => {
  8103. const handleKeyDown = (e: KeyboardEvent) => {
  8104. if (e.key === 'Escape') onClose();
  8105. };
  8106. window.addEventListener('keydown', handleKeyDown);
  8107. return () => window.removeEventListener('keydown', handleKeyDown);
  8108. }, [onClose]);
  8109. const doSave = () => {
  8110. const data: Partial<PrinterCreate> = {
  8111. name: form.name,
  8112. ip_address: form.ip_address,
  8113. model: form.model || undefined,
  8114. location: form.location || undefined,
  8115. auto_archive: form.auto_archive,
  8116. is_active: form.is_active,
  8117. };
  8118. // Only include access_code if it was changed
  8119. if (form.access_code) {
  8120. data.access_code = form.access_code;
  8121. }
  8122. updateMutation.mutate(data);
  8123. };
  8124. const handleSubmit = async (e: React.FormEvent) => {
  8125. e.preventDefault();
  8126. setCheckingSave(true);
  8127. try {
  8128. const result = await api.diagnoseConnection({
  8129. ip_address: form.ip_address.trim(),
  8130. serial_number: printer.serial_number,
  8131. access_code: form.access_code || undefined,
  8132. });
  8133. if (result.checks.some((c) => c.status === 'fail')) {
  8134. setSaveWarning(result);
  8135. return;
  8136. }
  8137. } catch {
  8138. // Diagnostic infrastructure failed — never block the save on it.
  8139. } finally {
  8140. setCheckingSave(false);
  8141. }
  8142. doSave();
  8143. };
  8144. return (
  8145. <div
  8146. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  8147. onClick={onClose}
  8148. >
  8149. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  8150. <CardContent>
  8151. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  8152. <form onSubmit={handleSubmit} className="space-y-4">
  8153. <div>
  8154. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  8155. <input
  8156. type="text"
  8157. required
  8158. 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"
  8159. value={form.name}
  8160. onChange={(e) => setForm({ ...form, name: e.target.value })}
  8161. placeholder={t('printers.modal.myPrinter')}
  8162. />
  8163. </div>
  8164. <div>
  8165. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  8166. <input
  8167. type="text"
  8168. required
  8169. 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])?)*)"
  8170. 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"
  8171. value={form.ip_address}
  8172. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  8173. placeholder="192.168.1.100 or printer.local"
  8174. />
  8175. </div>
  8176. <div>
  8177. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  8178. <input
  8179. type="text"
  8180. disabled
  8181. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  8182. value={printer.serial_number}
  8183. />
  8184. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  8185. </div>
  8186. <div>
  8187. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  8188. <input
  8189. type="password"
  8190. 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"
  8191. value={form.access_code}
  8192. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  8193. placeholder={t('printers.accessCodePlaceholder')}
  8194. />
  8195. </div>
  8196. <div>
  8197. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  8198. <select
  8199. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  8200. value={form.model}
  8201. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8202. >
  8203. <option value="">{t('printers.modal.selectModel')}</option>
  8204. <optgroup label="A1 Series">
  8205. <option value="A1">A1</option>
  8206. <option value="A1 Mini">A1 Mini</option>
  8207. </optgroup>
  8208. <optgroup label="A2 Series">
  8209. <option value="A2L">A2L</option>
  8210. </optgroup>
  8211. <optgroup label="H2 Series">
  8212. <option value="H2C">H2C</option>
  8213. <option value="H2D">H2D</option>
  8214. <option value="H2D Pro">H2D Pro</option>
  8215. <option value="H2S">H2S</option>
  8216. </optgroup>
  8217. <optgroup label="P Series">
  8218. <option value="P1P">P1P</option>
  8219. <option value="P1S">P1S</option>
  8220. <option value="P2S">P2S</option>
  8221. </optgroup>
  8222. <optgroup label="X1 Series">
  8223. <option value="X1">X1</option>
  8224. <option value="X1C">X1 Carbon</option>
  8225. <option value="X1E">X1E</option>
  8226. </optgroup>
  8227. <optgroup label="X2 Series">
  8228. <option value="X2D">X2D</option>
  8229. </optgroup>
  8230. </select>
  8231. </div>
  8232. <div>
  8233. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8234. <input
  8235. type="text"
  8236. 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"
  8237. value={form.location}
  8238. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8239. placeholder={t('printers.modal.locationPlaceholder')}
  8240. />
  8241. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8242. </div>
  8243. <div className="flex items-center gap-2">
  8244. <input
  8245. type="checkbox"
  8246. id="edit_auto_archive"
  8247. checked={form.auto_archive}
  8248. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8249. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8250. />
  8251. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8252. {t('printers.modal.autoArchiveLabel')}
  8253. </label>
  8254. </div>
  8255. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8256. is_active because the user-facing concept is "is this printer
  8257. in maintenance" not "is it active". */}
  8258. <div>
  8259. <div className="flex items-center gap-2">
  8260. <input
  8261. type="checkbox"
  8262. id="edit_maintenance_mode"
  8263. checked={!form.is_active}
  8264. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8265. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8266. />
  8267. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8268. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8269. {t('printers.maintenance.editFieldLabel')}
  8270. </label>
  8271. </div>
  8272. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8273. {t('printers.maintenance.editFieldHelp')}
  8274. </p>
  8275. </div>
  8276. {saveWarning ? (
  8277. <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">
  8278. <div className="flex items-start gap-2">
  8279. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8280. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8281. </div>
  8282. <DiagnosticChecklist result={saveWarning} />
  8283. <div className="flex gap-3">
  8284. <Button
  8285. type="button"
  8286. variant="secondary"
  8287. onClick={() => setSaveWarning(null)}
  8288. className="flex-1"
  8289. >
  8290. {t('printers.addPreflight.back')}
  8291. </Button>
  8292. <Button
  8293. type="button"
  8294. onClick={doSave}
  8295. className="flex-1"
  8296. disabled={updateMutation.isPending}
  8297. >
  8298. {t('printers.addPreflight.saveAnyway')}
  8299. </Button>
  8300. </div>
  8301. </div>
  8302. ) : (
  8303. <div className="flex gap-3 pt-4">
  8304. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8305. {t('common.cancel')}
  8306. </Button>
  8307. <Button
  8308. type="submit"
  8309. className="flex-1"
  8310. disabled={updateMutation.isPending || checkingSave}
  8311. >
  8312. {checkingSave
  8313. ? t('printers.addPreflight.checking')
  8314. : updateMutation.isPending
  8315. ? t('common.saving')
  8316. : t('printers.modal.saveChanges')}
  8317. </Button>
  8318. </div>
  8319. )}
  8320. </form>
  8321. </CardContent>
  8322. </Card>
  8323. </div>
  8324. );
  8325. }
  8326. // Component to check if a printer is offline (for power dropdown)
  8327. function usePrinterOfflineStatus(printerId: number) {
  8328. const { data: status } = useQuery({
  8329. queryKey: ['printerStatus', printerId],
  8330. queryFn: () => api.getPrinterStatus(printerId),
  8331. refetchInterval: 30000,
  8332. });
  8333. return !status?.connected;
  8334. }
  8335. // Power dropdown item for an offline printer
  8336. function PowerDropdownItem({
  8337. printer,
  8338. plug,
  8339. onPowerOn,
  8340. isPowering,
  8341. }: {
  8342. printer: Printer;
  8343. plug: { id: number; name: string };
  8344. onPowerOn: (plugId: number) => void;
  8345. isPowering: boolean;
  8346. }) {
  8347. const isOffline = usePrinterOfflineStatus(printer.id);
  8348. // Fetch plug status
  8349. const { data: plugStatus } = useQuery({
  8350. queryKey: ['smartPlugStatus', plug.id],
  8351. queryFn: () => api.getSmartPlugStatus(plug.id),
  8352. refetchInterval: 10000,
  8353. });
  8354. // Only show if printer is offline
  8355. if (!isOffline) {
  8356. return null;
  8357. }
  8358. return (
  8359. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8360. <div className="flex items-center gap-2 min-w-0">
  8361. <span className="text-sm text-white truncate">{printer.name}</span>
  8362. {plugStatus && (
  8363. <span
  8364. className={`text-xs px-1.5 py-0.5 rounded ${
  8365. plugStatus.state === 'ON'
  8366. ? 'bg-bambu-green/20 text-bambu-green'
  8367. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8368. }`}
  8369. >
  8370. {plugStatus.state || '?'}
  8371. </span>
  8372. )}
  8373. </div>
  8374. <button
  8375. onClick={() => onPowerOn(plug.id)}
  8376. disabled={isPowering || plugStatus?.state === 'ON'}
  8377. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8378. plugStatus?.state === 'ON'
  8379. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8380. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8381. }`}
  8382. >
  8383. <Power className="w-3 h-3" />
  8384. {isPowering ? '...' : 'On'}
  8385. </button>
  8386. </div>
  8387. );
  8388. }
  8389. export function PrintersPage() {
  8390. const { t } = useTranslation();
  8391. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8392. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8393. const accentButtonClass = {
  8394. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8395. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8396. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8397. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8398. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8399. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8400. }[activeAccent];
  8401. const [showAddModal, setShowAddModal] = useState(false);
  8402. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8403. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8404. });
  8405. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8406. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8407. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8408. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8409. });
  8410. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8411. return localStorage.getItem('printerSortAsc') !== 'false';
  8412. });
  8413. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8414. const [cardSize, setCardSize] = useState<number>(() => {
  8415. const saved = localStorage.getItem('printerCardSize');
  8416. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8417. });
  8418. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8419. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8420. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8421. });
  8422. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8423. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8424. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8425. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8426. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8427. });
  8428. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8429. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8430. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8431. });
  8432. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8433. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8434. // Defaulting to 'full' because the cards already show this info — users who
  8435. // pick cam-wall view still want to glance the same details without flipping.
  8436. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8437. const saved = localStorage.getItem('camWallStatusMode');
  8438. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8439. });
  8440. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8441. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8442. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8443. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8444. requestAnimationFrame(() => {
  8445. requestAnimationFrame(() => {
  8446. const card = document.getElementById(`printer-card-${printerId}`);
  8447. if (!card) return;
  8448. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8449. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8450. window.scrollTo({
  8451. top: Math.max(0, top),
  8452. behavior: 'smooth',
  8453. });
  8454. });
  8455. });
  8456. }, []);
  8457. const openCompactCard = useCallback((printerId: number) => {
  8458. setCompactDrilldownPrinterId(printerId);
  8459. setCardSize(2);
  8460. localStorage.setItem('printerCardSize', '2');
  8461. scrollPrinterIntoView(printerId);
  8462. }, [scrollPrinterIntoView]);
  8463. const returnToCompactCards = useCallback(() => {
  8464. const printerId = compactDrilldownPrinterId;
  8465. setCompactDrilldownPrinterId(null);
  8466. setCardSize(1);
  8467. localStorage.setItem('printerCardSize', '1');
  8468. if (printerId != null) {
  8469. scrollPrinterIntoView(printerId);
  8470. }
  8471. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8472. const [search, setSearch] = useState('');
  8473. // Both filters persist like every other preference on this page (#2833).
  8474. // `search` deliberately does not: a box that silently refills itself on
  8475. // return is more surprising than a dropdown that remembers.
  8476. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8477. // Validated on read: a value the dropdown no longer offers would filter
  8478. // every printer out, and nothing would explain why.
  8479. const saved = localStorage.getItem('printerStatusFilter');
  8480. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8481. });
  8482. const [locationFilter, setLocationFilter] = useState<string>(
  8483. () => localStorage.getItem('printerLocationFilter') || 'all'
  8484. );
  8485. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8486. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8487. try {
  8488. const saved = localStorage.getItem('printerCollapsedSections');
  8489. return saved ? JSON.parse(saved) : {};
  8490. } catch { return {}; }
  8491. });
  8492. const queryClient = useQueryClient();
  8493. const { showToast } = useToast();
  8494. const { hasPermission } = useAuth();
  8495. // Which way the camera buttons open a stream. Chosen per click from the
  8496. // button's own menu; null until this browser has made a choice, so the
  8497. // stored setting below can act as the default a fresh browser starts from.
  8498. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8499. () => readStoredCameraViewMode()
  8500. );
  8501. // Embedded camera viewer state - supports multiple simultaneous viewers
  8502. // Persisted to localStorage so cameras reopen after navigation
  8503. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8504. const saved = localStorage.getItem('openEmbeddedCameras');
  8505. if (saved) {
  8506. try {
  8507. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8508. return new Map(cameras.map(c => [c.id, c]));
  8509. } catch {
  8510. return new Map();
  8511. }
  8512. }
  8513. return new Map();
  8514. });
  8515. // Persist open cameras to localStorage when they change
  8516. useEffect(() => {
  8517. const cameras = Array.from(embeddedCameraPrinters.values());
  8518. if (cameras.length > 0) {
  8519. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8520. } else {
  8521. localStorage.removeItem('openEmbeddedCameras');
  8522. }
  8523. }, [embeddedCameraPrinters]);
  8524. const { data: printers, isLoading } = useQuery({
  8525. queryKey: ['printers'],
  8526. queryFn: api.getPrinters,
  8527. });
  8528. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8529. // so users with printers:read but no settings:read still get the values needed
  8530. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8531. const { data: settings } = useQuery({
  8532. queryKey: ['ui-preferences'],
  8533. queryFn: api.getUiPreferences,
  8534. });
  8535. // Parse user-configured temperature/fan presets once, with defensive fallback
  8536. // to built-in defaults on parse failure (validators on the backend already
  8537. // reject malformed writes, so this is just forward-compat).
  8538. const effectiveNozzleTempPresets = useMemo(
  8539. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8540. [settings?.nozzle_temp_presets],
  8541. );
  8542. const effectiveBedTempPresets = useMemo(
  8543. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8544. [settings?.bed_temp_presets],
  8545. );
  8546. const effectiveChamberTempPresets = useMemo(
  8547. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8548. [settings?.chamber_temp_presets],
  8549. );
  8550. const effectiveFanSpeedPresets = useMemo(
  8551. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8552. [settings?.fan_speed_presets],
  8553. );
  8554. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8555. const effectiveDryingPresets = useMemo(() => {
  8556. if (settings?.drying_presets) {
  8557. try {
  8558. const userPresets = JSON.parse(settings.drying_presets);
  8559. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8560. return { ...DRYING_PRESETS, ...userPresets };
  8561. }
  8562. } catch { /* ignore parse errors, use defaults */ }
  8563. }
  8564. return DRYING_PRESETS;
  8565. }, [settings?.drying_presets]);
  8566. // The local choice wins over the stored one: someone without settings:update
  8567. // cannot write their pick back, and a preference that silently reverted on
  8568. // the next render would be worse than none at all.
  8569. const cameraViewMode: CameraViewMode =
  8570. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8571. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8572. storeCameraViewMode(mode);
  8573. setChosenCameraViewMode(mode);
  8574. // Best effort, and only a default for other browsers -- the choice is
  8575. // already in effect here. Users below settings:update simply keep theirs
  8576. // locally, which is why the failure is logged rather than surfaced.
  8577. if (hasPermission('settings:update')) {
  8578. api.updateSettings({ camera_view_mode: mode })
  8579. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8580. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8581. }
  8582. }, [hasPermission, queryClient]);
  8583. // Fetch all smart plugs to know which printers have them
  8584. const { data: smartPlugs } = useQuery({
  8585. queryKey: ['smart-plugs'],
  8586. queryFn: api.getSmartPlugs,
  8587. });
  8588. // Fetch maintenance overview for all printers to show badges
  8589. const { data: maintenanceOverview } = useQuery({
  8590. queryKey: ['maintenanceOverview'],
  8591. queryFn: api.getMaintenanceOverview,
  8592. staleTime: 60 * 1000, // 1 minute
  8593. });
  8594. // Live AI failure detection state for the card badges (#1546). Matches the
  8595. // 10s refetch of the Failure Detection settings panel.
  8596. const { data: obicoPrinterStatus } = useQuery({
  8597. queryKey: ['obico-printer-status'],
  8598. queryFn: api.getObicoPrinterStatus,
  8599. refetchInterval: 10000,
  8600. });
  8601. // Badge visibility: detection enabled AND this printer in the monitored set
  8602. // (monitored_printers null = all). Live per-print state is passed separately.
  8603. const isAiMonitored = useCallback(
  8604. (printerId: number) =>
  8605. obicoPrinterStatus?.enabled === true &&
  8606. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8607. [obicoPrinterStatus],
  8608. );
  8609. // Fetch Spoolman status to enable link spool feature
  8610. const { data: spoolmanStatus } = useQuery({
  8611. queryKey: ['spoolman-status'],
  8612. queryFn: api.getSpoolmanStatus,
  8613. staleTime: 60 * 1000, // 1 minute
  8614. });
  8615. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8616. // Fetch Spoolman settings to get sync mode
  8617. const { data: spoolmanSettings } = useQuery({
  8618. queryKey: ['spoolman-settings'],
  8619. queryFn: api.getSpoolmanSettings,
  8620. enabled: !!spoolmanEnabled,
  8621. staleTime: 60 * 1000, // 1 minute
  8622. });
  8623. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8624. // Fetch unlinked spools to know if link button should be enabled
  8625. const { data: unlinkedSpools } = useQuery({
  8626. queryKey: ['unlinked-spools'],
  8627. queryFn: api.getUnlinkedSpools,
  8628. enabled: !!spoolmanEnabled,
  8629. staleTime: 30 * 1000, // 30 seconds
  8630. });
  8631. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8632. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8633. const { data: linkedSpoolsData } = useQuery({
  8634. queryKey: ['linked-spools'],
  8635. queryFn: api.getLinkedSpools,
  8636. enabled: !!spoolmanEnabled,
  8637. staleTime: 30 * 1000, // 30 seconds
  8638. });
  8639. const linkedSpools = linkedSpoolsData?.linked;
  8640. // Fetch spool assignments for inventory feature
  8641. const { data: spoolAssignments } = useQuery({
  8642. queryKey: ['spool-assignments'],
  8643. queryFn: () => api.getAssignments(),
  8644. enabled: hasPermission('inventory:view_assignments'),
  8645. staleTime: 30 * 1000,
  8646. });
  8647. const unassignMutation = useMutation({
  8648. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8649. api.unassignSpool(printerId, amsId, trayId),
  8650. onSuccess: () => {
  8651. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8652. },
  8653. });
  8654. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8655. queryKey: ['spoolman-inventory-spools'],
  8656. queryFn: () => api.getSpoolmanInventorySpools(false),
  8657. enabled: !!spoolmanEnabled,
  8658. staleTime: 30 * 1000,
  8659. });
  8660. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8661. queryKey: ['spoolman-slot-assignments'],
  8662. queryFn: () => api.getSpoolmanSlotAssignments(),
  8663. enabled: !!spoolmanEnabled,
  8664. staleTime: 30 * 1000,
  8665. });
  8666. const unassignSpoolmanMutation = useMutation({
  8667. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8668. onSuccess: () => {
  8669. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8670. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8671. },
  8672. });
  8673. // Helper to find assignment for a specific slot
  8674. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8675. return spoolAssignments?.find(
  8676. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8677. );
  8678. };
  8679. // Create a map of printer_id -> maintenance info for quick lookup
  8680. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8681. (acc, overview) => {
  8682. acc[overview.printer_id] = {
  8683. due_count: overview.due_count,
  8684. warning_count: overview.warning_count,
  8685. total_print_hours: overview.total_print_hours,
  8686. };
  8687. return acc;
  8688. },
  8689. {} as Record<number, PrinterMaintenanceInfo>
  8690. ) || {};
  8691. // Create a map of printer_id -> smart plug
  8692. const smartPlugByPrinter = smartPlugs?.reduce(
  8693. (acc, plug) => {
  8694. if (plug.printer_id) {
  8695. acc[plug.printer_id] = plug;
  8696. }
  8697. return acc;
  8698. },
  8699. {} as Record<number, typeof smartPlugs[0]>
  8700. ) || {};
  8701. const addMutation = useMutation({
  8702. mutationFn: api.createPrinter,
  8703. onSuccess: () => {
  8704. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8705. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8706. setShowAddModal(false);
  8707. },
  8708. onError: (error: Error) => {
  8709. // Localized message when the backend returns a stable error code;
  8710. // the raw message is an English fallback for non-UI clients.
  8711. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8712. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8713. return;
  8714. }
  8715. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8716. },
  8717. });
  8718. const powerOnMutation = useMutation({
  8719. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8720. onSuccess: () => {
  8721. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8722. setPoweringOn(null);
  8723. },
  8724. onError: () => {
  8725. setPoweringOn(null);
  8726. },
  8727. });
  8728. // Bulk selection state
  8729. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8730. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8731. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8732. const [bulkActionPending, setBulkActionPending] = useState(false);
  8733. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8734. const toggleSelect = useCallback((id: number) => {
  8735. setSelectedPrinterIds(prev => {
  8736. const next = new Set(prev);
  8737. if (next.has(id)) next.delete(id);
  8738. else next.add(id);
  8739. return next;
  8740. });
  8741. }, []);
  8742. const clearSelection = useCallback(() => {
  8743. setSelectedPrinterIds(new Set());
  8744. setIsSelectionMode(false);
  8745. }, []);
  8746. // Escape key exits selection mode
  8747. useEffect(() => {
  8748. const handleKeyDown = (e: KeyboardEvent) => {
  8749. if (e.key === 'Escape' && selectionMode) {
  8750. clearSelection();
  8751. }
  8752. };
  8753. window.addEventListener('keydown', handleKeyDown);
  8754. return () => window.removeEventListener('keydown', handleKeyDown);
  8755. }, [selectionMode, clearSelection]);
  8756. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8757. setBulkActionPending(true);
  8758. const ids = Array.from(selectedPrinterIds);
  8759. // Filter to only applicable printers based on cached state
  8760. const applicableIds = ids.filter(id => {
  8761. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8762. // clearPlate is checked before the connection filter: it only releases a
  8763. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8764. // down — every other action here needs to reach the machine (#2864).
  8765. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8766. if (!status?.connected) return false;
  8767. switch (action) {
  8768. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8769. case 'pause': return status.state === 'RUNNING';
  8770. case 'resume': return status.state === 'PAUSE';
  8771. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8772. default: return false;
  8773. }
  8774. });
  8775. if (applicableIds.length === 0) {
  8776. showToast(t('printers.bulk.noneApplicable'), 'error');
  8777. setBulkActionPending(false);
  8778. setBulkConfirmAction(null);
  8779. return;
  8780. }
  8781. const apiCall = {
  8782. stop: api.stopPrint,
  8783. pause: api.pausePrint,
  8784. resume: api.resumePrint,
  8785. clearPlate: api.clearPlate,
  8786. clearHMS: api.clearHMSErrors,
  8787. }[action];
  8788. const results = await Promise.allSettled(
  8789. applicableIds.map(id => apiCall(id))
  8790. );
  8791. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8792. const failed = results.filter(r => r.status === 'rejected').length;
  8793. if (failed === 0) {
  8794. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8795. } else {
  8796. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8797. }
  8798. // Invalidate status queries for affected printers
  8799. applicableIds.forEach(id => {
  8800. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8801. });
  8802. setBulkActionPending(false);
  8803. setBulkConfirmAction(null);
  8804. }, [selectedPrinterIds, queryClient, showToast, t]);
  8805. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8806. // Actions that need confirmation
  8807. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8808. setBulkConfirmAction(action);
  8809. } else {
  8810. executeBulkAction(action);
  8811. }
  8812. }, [executeBulkAction]);
  8813. const toggleHideDisconnected = () => {
  8814. const newValue = !hideDisconnected;
  8815. setHideDisconnected(newValue);
  8816. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8817. };
  8818. const handleSortChange = (newSort: SortOption) => {
  8819. setSortBy(newSort);
  8820. localStorage.setItem('printerSortBy', newSort);
  8821. };
  8822. const handleStatusFilterChange = (value: string) => {
  8823. setStatusFilter(value);
  8824. localStorage.setItem('printerStatusFilter', value);
  8825. };
  8826. const handleLocationFilterChange = (value: string) => {
  8827. setLocationFilter(value);
  8828. localStorage.setItem('printerLocationFilter', value);
  8829. };
  8830. const toggleSortDirection = () => {
  8831. const newAsc = !sortAsc;
  8832. setSortAsc(newAsc);
  8833. localStorage.setItem('printerSortAsc', String(newAsc));
  8834. };
  8835. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8836. const getGridClasses = () => {
  8837. switch (cardSize) {
  8838. 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
  8839. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8840. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8841. case 4: return 'grid-cols-1'; // XL: single column, full width
  8842. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8843. }
  8844. };
  8845. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8846. // Increment version counter whenever a printer status cache entry is updated so
  8847. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8848. useEffect(() => {
  8849. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8850. if (
  8851. event.type === 'updated' &&
  8852. Array.isArray(event.query.queryKey) &&
  8853. event.query.queryKey[0] === 'printerStatus'
  8854. ) {
  8855. setStatusCacheVersion(v => v + 1);
  8856. }
  8857. });
  8858. return unsubscribe;
  8859. }, [queryClient]);
  8860. // Filter printers by search term, status, and location
  8861. const filteredPrinters = useMemo(() => {
  8862. if (!printers) return [];
  8863. let result = printers;
  8864. // Text search
  8865. if (search.trim()) {
  8866. const q = search.trim().toLowerCase();
  8867. result = result.filter(p =>
  8868. p.name.toLowerCase().includes(q) ||
  8869. (p.model || '').toLowerCase().includes(q) ||
  8870. (p.location || '').toLowerCase().includes(q) ||
  8871. (p.serial_number || '').toLowerCase().includes(q)
  8872. );
  8873. }
  8874. // Location filter
  8875. if (locationFilter !== 'all') {
  8876. result = result.filter(p => (p.location || '') === locationFilter);
  8877. }
  8878. // Status filter
  8879. if (statusFilter !== 'all') {
  8880. result = result.filter(p => {
  8881. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8882. if (!status?.connected) return statusFilter === 'offline';
  8883. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8884. switch (statusFilter) {
  8885. case 'printing': return status.state === 'RUNNING';
  8886. case 'paused': return status.state === 'PAUSE';
  8887. case 'finished': return status.state === 'FINISH';
  8888. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8889. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8890. case 'offline': return false; // Connected printers are never offline
  8891. default: return true;
  8892. }
  8893. });
  8894. }
  8895. return result;
  8896. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8897. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8898. // Derive unique locations for the location filter dropdown
  8899. const availableLocations = useMemo(() => {
  8900. if (!printers) return [];
  8901. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8902. }, [printers]);
  8903. // A saved location can outlive what it matched -- renamed, cleared, or the
  8904. // only printer that had it deleted. The dropdown is rendered only while some
  8905. // printer has a location, so a stale one would hide every printer *and* the
  8906. // control to undo it, leaving an empty page and no way back (#2833).
  8907. // Deliberately waits for `printers`: it is undefined while the query is in
  8908. // flight, and acting on the empty list that produces would throw the saved
  8909. // filter away every time the page loads.
  8910. useEffect(() => {
  8911. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8912. setLocationFilter('all');
  8913. localStorage.setItem('printerLocationFilter', 'all');
  8914. }, [printers, availableLocations, locationFilter]);
  8915. // Sort printers based on selected option
  8916. const sortedPrinters = useMemo(() => {
  8917. const sorted = [...filteredPrinters];
  8918. switch (sortBy) {
  8919. case 'name':
  8920. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8921. break;
  8922. case 'model':
  8923. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8924. break;
  8925. case 'location':
  8926. // Sort by location, with ungrouped printers last
  8927. sorted.sort((a, b) => {
  8928. const locA = a.location || '';
  8929. const locB = b.location || '';
  8930. if (!locA && locB) return 1;
  8931. if (locA && !locB) return -1;
  8932. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8933. });
  8934. break;
  8935. case 'status':
  8936. // Sort by status: HMS errors > printing > idle > offline
  8937. sorted.sort((a, b) => {
  8938. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8939. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8940. const getPriority = (s: typeof statusA) => {
  8941. if (!s?.connected) return 3; // offline
  8942. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8943. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8944. if (s.state === 'RUNNING') return 1; // printing
  8945. return 2; // idle
  8946. };
  8947. return getPriority(statusA) - getPriority(statusB);
  8948. });
  8949. break;
  8950. case 'eta':
  8951. sorted.sort((a, b) => {
  8952. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8953. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8954. const tier = (s: typeof statusA) => {
  8955. if (!s?.connected) return 3; // offline last
  8956. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8957. if (s.state === 'RUNNING') return 1; // printing without ETA
  8958. return 2; // idle
  8959. };
  8960. const ta = tier(statusA);
  8961. const tb = tier(statusB);
  8962. if (ta !== tb) return ta - tb;
  8963. if (ta === 0) {
  8964. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8965. if (diff !== 0) return diff;
  8966. }
  8967. return a.name.localeCompare(b.name);
  8968. });
  8969. break;
  8970. }
  8971. // Apply ascending/descending
  8972. if (!sortAsc) {
  8973. sorted.reverse();
  8974. }
  8975. return sorted;
  8976. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8977. const selectAll = useCallback(() => {
  8978. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8979. setIsSelectionMode(true);
  8980. }, [sortedPrinters]);
  8981. const selectByState = useCallback((state: PrinterState) => {
  8982. setSelectedPrinterIds(prev => {
  8983. const next = new Set(prev);
  8984. sortedPrinters.forEach(p => {
  8985. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8986. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8987. });
  8988. return next;
  8989. });
  8990. setIsSelectionMode(true);
  8991. }, [sortedPrinters, queryClient]);
  8992. const selectByLocation = useCallback((location: string) => {
  8993. setSelectedPrinterIds(prev => {
  8994. const next = new Set(prev);
  8995. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  8996. return next;
  8997. });
  8998. setIsSelectionMode(true);
  8999. }, [sortedPrinters]);
  9000. const selectByModel = useCallback((model: string) => {
  9001. setSelectedPrinterIds(prev => {
  9002. const next = new Set(prev);
  9003. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  9004. return next;
  9005. });
  9006. setIsSelectionMode(true);
  9007. }, [sortedPrinters]);
  9008. const toggleSectionCollapse = useCallback((key: string) => {
  9009. setCollapsedSections(prev => {
  9010. const next = { ...prev, [key]: !prev[key] };
  9011. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  9012. return next;
  9013. });
  9014. }, []);
  9015. // Group printers when sorted by location, status, or model
  9016. const groupedPrinters = useMemo(() => {
  9017. if (sortBy === 'name' || sortBy === 'eta') return null;
  9018. const groups: Record<string, typeof sortedPrinters> = {};
  9019. if (sortBy === 'location') {
  9020. sortedPrinters.forEach(printer => {
  9021. const location = printer.location || 'Ungrouped';
  9022. if (!groups[location]) groups[location] = [];
  9023. groups[location].push(printer);
  9024. });
  9025. } else if (sortBy === 'model') {
  9026. sortedPrinters.forEach(printer => {
  9027. const model = printer.model || 'Unknown';
  9028. if (!groups[model]) groups[model] = [];
  9029. groups[model].push(printer);
  9030. });
  9031. } else if (sortBy === 'status') {
  9032. sortedPrinters.forEach(printer => {
  9033. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  9034. const group = classifyPrinterStatus(status);
  9035. if (!groups[group]) groups[group] = [];
  9036. groups[group].push(printer);
  9037. });
  9038. }
  9039. return groups;
  9040. // 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
  9041. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  9042. const toolbarRef = useRef<HTMLDivElement>(null);
  9043. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  9044. const expandedToolbarWidthRef = useRef(0);
  9045. const [compactToolbar, setCompactToolbar] = useState(false);
  9046. const measureToolbar = useCallback(() => {
  9047. const toolbar = toolbarRef.current;
  9048. if (!toolbar) return;
  9049. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  9050. if (measuredControlsWidth) {
  9051. expandedToolbarWidthRef.current = measuredControlsWidth;
  9052. }
  9053. const searchMinimumWidth = 220;
  9054. const gapWidth = 8;
  9055. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  9056. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  9057. }, []);
  9058. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  9059. useLayoutEffect(() => {
  9060. measureToolbar();
  9061. const toolbar = toolbarRef.current;
  9062. if (!toolbar) return;
  9063. if (typeof ResizeObserver === 'undefined') {
  9064. window.addEventListener('resize', measureToolbar);
  9065. return () => window.removeEventListener('resize', measureToolbar);
  9066. }
  9067. const resizeObserver = new ResizeObserver(() => measureToolbar());
  9068. resizeObserver.observe(toolbar);
  9069. window.addEventListener('resize', measureToolbar);
  9070. return () => {
  9071. resizeObserver.disconnect();
  9072. window.removeEventListener('resize', measureToolbar);
  9073. };
  9074. }, [
  9075. measureToolbar,
  9076. printers?.length,
  9077. availableLocations.length,
  9078. hideDisconnected,
  9079. smartPlugCount,
  9080. ]);
  9081. const renderFilterControls = (inMenu = false) => (
  9082. <>
  9083. {/* Status filter */}
  9084. {printers && printers.length > 0 && (
  9085. <ToolbarDropdown
  9086. value={statusFilter}
  9087. onChange={handleStatusFilterChange}
  9088. fullWidth={inMenu}
  9089. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  9090. />
  9091. )}
  9092. {/* Location filter — only shown when at least one printer has a location */}
  9093. {printers && printers.length > 0 && availableLocations.length > 0 && (
  9094. <ToolbarDropdown
  9095. value={locationFilter}
  9096. onChange={handleLocationFilterChange}
  9097. fullWidth={inMenu}
  9098. options={[
  9099. { value: 'all', label: t('printers.filter.allLocations') },
  9100. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  9101. ]}
  9102. />
  9103. )}
  9104. <button
  9105. type="button"
  9106. onClick={toggleHideDisconnected}
  9107. aria-pressed={hideDisconnected}
  9108. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  9109. hideDisconnected
  9110. ? 'bg-bambu-green border-bambu-green text-white'
  9111. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9112. }`}
  9113. >
  9114. {t('printers.hideOffline')}
  9115. </button>
  9116. </>
  9117. );
  9118. const renderViewControls = (inMenu = false) => (
  9119. <>
  9120. {/* Sort dropdown */}
  9121. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  9122. <ToolbarDropdown<SortOption>
  9123. value={sortBy}
  9124. onChange={handleSortChange}
  9125. fullWidth={inMenu}
  9126. options={[
  9127. { value: 'name', label: t('printers.sort.name') },
  9128. { value: 'status', label: t('printers.sort.status') },
  9129. { value: 'model', label: t('printers.sort.model') },
  9130. { value: 'location', label: t('printers.sort.location') },
  9131. { value: 'eta', label: t('printers.sort.eta') },
  9132. ]}
  9133. />
  9134. <button
  9135. onClick={toggleSortDirection}
  9136. 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"
  9137. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  9138. >
  9139. {sortAsc ? (
  9140. <ArrowUp className="w-4 h-4 text-white" />
  9141. ) : (
  9142. <ArrowDown className="w-4 h-4 text-white" />
  9143. )}
  9144. </button>
  9145. </div>
  9146. {/* Page view toggle: Cards / Cam Wall */}
  9147. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  9148. <button
  9149. type="button"
  9150. onClick={() => {
  9151. setPageView('cards');
  9152. localStorage.setItem('printerPageView', 'cards');
  9153. }}
  9154. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9155. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9156. }`}
  9157. title={t('printers.pageView.cards')}
  9158. aria-pressed={pageView === 'cards'}
  9159. >
  9160. <LayoutGrid className="w-3.5 h-3.5" />
  9161. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  9162. </button>
  9163. <button
  9164. type="button"
  9165. onClick={() => {
  9166. setPageView('camwall');
  9167. localStorage.setItem('printerPageView', 'camwall');
  9168. }}
  9169. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  9170. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  9171. }`}
  9172. title={t('printers.pageView.camWall')}
  9173. aria-pressed={pageView === 'camwall'}
  9174. disabled={!hasPermission('camera:view')}
  9175. >
  9176. <MonitorPlay className="w-3.5 h-3.5" />
  9177. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  9178. </button>
  9179. </div>
  9180. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  9181. view, and the page a kiosk token points at. Only offered once the wall
  9182. is the active view, so it doesn't compete with the toggle above. */}
  9183. {pageView === 'camwall' && hasPermission('camera:view') && (
  9184. <RouterLink
  9185. to="/camwall"
  9186. 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' : ''}`}
  9187. title={t('printers.pageView.openCamWallPage')}
  9188. >
  9189. <ExternalLink className="w-3.5 h-3.5" />
  9190. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  9191. </RouterLink>
  9192. )}
  9193. {/* Card size selector */}
  9194. <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' : ''}`}>
  9195. {cardSizeLabels.map((label, index) => {
  9196. const size = index + 1;
  9197. const isSelected = cardSize === size;
  9198. return (
  9199. <button
  9200. key={label}
  9201. onClick={() => {
  9202. setCompactDrilldownPrinterId(null);
  9203. setCardSize(size);
  9204. localStorage.setItem('printerCardSize', String(size));
  9205. }}
  9206. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9207. index === 0 ? 'rounded-l-lg' : ''
  9208. } ${
  9209. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9210. } ${
  9211. isSelected
  9212. ? 'bg-bambu-green text-white'
  9213. : 'text-white hover:bg-bambu-dark-tertiary'
  9214. }`}
  9215. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9216. >
  9217. {label}
  9218. </button>
  9219. );
  9220. })}
  9221. </div>
  9222. </>
  9223. );
  9224. const renderActionControls = (inMenu = false) => (
  9225. <>
  9226. {/* Bulk select toggle */}
  9227. <button
  9228. onClick={() => {
  9229. if (selectionMode) clearSelection();
  9230. else setIsSelectionMode(true);
  9231. }}
  9232. 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' : ''} ${
  9233. selectionMode
  9234. ? 'bg-bambu-green border-bambu-green text-white'
  9235. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9236. }`}
  9237. title={t('printers.bulk.select')}
  9238. disabled={!hasPermission('printers:control')}
  9239. >
  9240. <CheckSquare className="w-4 h-4" />
  9241. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9242. </button>
  9243. {/* Power dropdown for offline printers with smart plugs */}
  9244. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9245. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9246. <button
  9247. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9248. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9249. inMenu
  9250. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9251. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9252. }`}
  9253. >
  9254. <span className="flex items-center gap-1.5">
  9255. <Power className="w-4 h-4" />
  9256. {t('printers.powerOn')}
  9257. </span>
  9258. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9259. </button>
  9260. {showPowerDropdown && (
  9261. <>
  9262. {/* Backdrop to close dropdown */}
  9263. <div
  9264. className="fixed inset-0 z-10"
  9265. onClick={() => setShowPowerDropdown(false)}
  9266. />
  9267. <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">
  9268. <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">
  9269. {t('printers.offlinePrintersWithPlugs')}
  9270. </div>
  9271. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9272. <PowerDropdownItem
  9273. key={printer.id}
  9274. printer={printer}
  9275. plug={smartPlugByPrinter[printer.id]}
  9276. onPowerOn={(plugId) => {
  9277. setPoweringOn(plugId);
  9278. powerOnMutation.mutate(plugId);
  9279. }}
  9280. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9281. />
  9282. ))}
  9283. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9284. <div className="px-3 py-2 text-sm text-bambu-gray">
  9285. No printers with smart plugs
  9286. </div>
  9287. )}
  9288. </div>
  9289. </>
  9290. )}
  9291. </div>
  9292. )}
  9293. <Button
  9294. onClick={() => setShowAddModal(true)}
  9295. disabled={!hasPermission('printers:create')}
  9296. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9297. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9298. >
  9299. <Plus className="w-4 h-4" />
  9300. {t('printers.addPrinter')}
  9301. </Button>
  9302. </>
  9303. );
  9304. return (
  9305. <div className="p-4 md:p-8">
  9306. <div className="space-y-3 mb-6">
  9307. <div>
  9308. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9309. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9310. {t('printers.title')}
  9311. </h1>
  9312. <StatusSummaryBar printers={printers} />
  9313. </div>
  9314. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9315. {/* Only show search bar when printers exist */}
  9316. {printers && printers.length > 0 && (
  9317. <div className="relative min-w-0 flex-1">
  9318. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9319. <input
  9320. type="search"
  9321. name="printer-search"
  9322. autoComplete="off"
  9323. data-1p-ignore
  9324. data-lpignore="true"
  9325. value={search}
  9326. onChange={(e) => setSearch(e.target.value)}
  9327. placeholder={t('printers.search')}
  9328. aria-label={t('printers.search')}
  9329. 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"
  9330. />
  9331. {search && (
  9332. <button
  9333. type="button"
  9334. aria-label={t('common.clear')}
  9335. onClick={() => setSearch('')}
  9336. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9337. >
  9338. <X className="w-4 h-4" />
  9339. </button>
  9340. )}
  9341. </div>
  9342. )}
  9343. <div
  9344. ref={expandedToolbarControlsRef}
  9345. aria-hidden={compactToolbar}
  9346. inert={compactToolbar}
  9347. 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`}
  9348. >
  9349. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9350. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9351. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9352. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9353. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9354. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9355. </div>
  9356. {compactToolbar && (
  9357. <div className="ml-auto flex items-center justify-end gap-1">
  9358. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9359. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9360. </ToolbarMenu>
  9361. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9362. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9363. </ToolbarMenu>
  9364. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9365. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9366. </ToolbarMenu>
  9367. </div>
  9368. )}
  9369. </div>
  9370. </div>
  9371. {isLoading ? (
  9372. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9373. ) : printers?.length === 0 ? (
  9374. <Card>
  9375. <CardContent className="text-center py-12">
  9376. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9377. <Button
  9378. onClick={() => setShowAddModal(true)}
  9379. disabled={!hasPermission('printers:create')}
  9380. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9381. >
  9382. <Plus className="w-4 h-4" />
  9383. {t('printers.addPrinter')}
  9384. </Button>
  9385. </CardContent>
  9386. </Card>
  9387. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9388. <Card>
  9389. <CardContent className="text-center py-12">
  9390. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9391. </CardContent>
  9392. </Card>
  9393. ) : pageView === 'camwall' ? (
  9394. <CameraWall
  9395. printers={sortedPrinters}
  9396. maxLive={camWallMaxLive}
  9397. snapshotIntervalSec={camWallSnapshotSec}
  9398. onTileClick={(id, name) => {
  9399. // A wall tile has no room for a split button, so it follows the
  9400. // mode the card buttons last chose.
  9401. if (cameraViewMode === 'embedded') {
  9402. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9403. } else {
  9404. openCameraWindow(id);
  9405. }
  9406. }}
  9407. statusMode={camWallStatusMode}
  9408. onChangeMaxLive={(next) => {
  9409. setCamWallMaxLive(next);
  9410. localStorage.setItem('camWallMaxLive', String(next));
  9411. }}
  9412. onChangeSnapshotIntervalSec={(next) => {
  9413. setCamWallSnapshotSec(next);
  9414. localStorage.setItem('camWallSnapshotSec', String(next));
  9415. }}
  9416. onChangeStatusMode={(next) => {
  9417. setCamWallStatusMode(next);
  9418. localStorage.setItem('camWallStatusMode', next);
  9419. }}
  9420. />
  9421. ) : groupedPrinters ? (
  9422. /* Grouped view (location, status, or model) */
  9423. <div className="space-y-6">
  9424. {(() => {
  9425. const keys = sortBy === 'status'
  9426. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9427. : Object.keys(groupedPrinters);
  9428. // For status grouping, asc/desc flips the fixed priority order
  9429. // (asc = error→offline, desc = offline→error). This matches the
  9430. // sort-toggle behaviour for other groupings.
  9431. return (sortAsc ? keys : [...keys].reverse());
  9432. })().map((groupKey) => {
  9433. const groupPrinters = groupedPrinters[groupKey];
  9434. const collapseKey = `${sortBy}:${groupKey}`;
  9435. const isOpen = !collapsedSections[collapseKey];
  9436. const dot = sortBy === 'status'
  9437. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9438. : 'bg-bambu-green';
  9439. const label = sortBy === 'status'
  9440. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9441. : groupKey;
  9442. return (
  9443. <Collapsible
  9444. key={groupKey}
  9445. open={isOpen}
  9446. onToggle={() => toggleSectionCollapse(collapseKey)}
  9447. summaryClassName="py-1"
  9448. summary={
  9449. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9450. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9451. {label}
  9452. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9453. {selectionMode && (
  9454. <button
  9455. onClick={(e) => {
  9456. e.stopPropagation();
  9457. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9458. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9459. else if (sortBy === 'model') selectByModel(groupKey);
  9460. }}
  9461. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9462. >
  9463. {t('printers.bulk.selectAll')}
  9464. </button>
  9465. )}
  9466. </h2>
  9467. }
  9468. >
  9469. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9470. {groupPrinters.map((printer) => (
  9471. <PrinterCard
  9472. key={printer.id}
  9473. printer={printer}
  9474. hideIfDisconnected={hideDisconnected}
  9475. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9476. viewMode={viewMode}
  9477. cardSize={cardSize}
  9478. amsThresholds={settings ? {
  9479. humidityGood: Number(settings.ams_humidity_good) || 40,
  9480. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9481. tempGood: Number(settings.ams_temp_good) || 28,
  9482. tempFair: Number(settings.ams_temp_fair) || 35,
  9483. } : undefined}
  9484. spoolmanEnabled={spoolmanEnabled}
  9485. hasUnlinkedSpools={hasUnlinkedSpools}
  9486. linkedSpools={linkedSpools}
  9487. spoolmanUrl={spoolmanStatus?.url}
  9488. spoolmanSyncMode={spoolmanSyncMode}
  9489. onGetAssignment={getAssignment}
  9490. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9491. spoolmanSpools={spoolmanSpools}
  9492. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9493. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9494. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9495. timeFormat={settings?.time_format || 'system'}
  9496. cameraViewMode={cameraViewMode}
  9497. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9498. onSelectCameraViewMode={selectCameraViewMode}
  9499. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9500. dryingPresets={effectiveDryingPresets}
  9501. nozzleTempPresets={effectiveNozzleTempPresets}
  9502. bedTempPresets={effectiveBedTempPresets}
  9503. chamberTempPresets={effectiveChamberTempPresets}
  9504. fanSpeedPresets={effectiveFanSpeedPresets}
  9505. requirePlateClear={settings?.require_plate_clear === true}
  9506. selectionMode={selectionMode}
  9507. isSelected={selectedPrinterIds.has(printer.id)}
  9508. onToggleSelect={toggleSelect}
  9509. onOpenCompactCard={openCompactCard}
  9510. aiDetectionEnabled={isAiMonitored(printer.id)}
  9511. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9512. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9513. />
  9514. ))}
  9515. </div>
  9516. </Collapsible>
  9517. );
  9518. })}
  9519. </div>
  9520. ) : (
  9521. /* Regular grid view */
  9522. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9523. {sortedPrinters.map((printer) => (
  9524. <PrinterCard
  9525. key={printer.id}
  9526. printer={printer}
  9527. hideIfDisconnected={hideDisconnected}
  9528. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9529. viewMode={viewMode}
  9530. cardSize={cardSize}
  9531. spoolmanEnabled={spoolmanEnabled}
  9532. hasUnlinkedSpools={hasUnlinkedSpools}
  9533. linkedSpools={linkedSpools}
  9534. spoolmanUrl={spoolmanStatus?.url}
  9535. spoolmanSyncMode={spoolmanSyncMode}
  9536. onGetAssignment={getAssignment}
  9537. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9538. spoolmanSpools={spoolmanSpools}
  9539. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9540. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9541. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9542. amsThresholds={settings ? {
  9543. humidityGood: Number(settings.ams_humidity_good) || 40,
  9544. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9545. tempGood: Number(settings.ams_temp_good) || 28,
  9546. tempFair: Number(settings.ams_temp_fair) || 35,
  9547. } : undefined}
  9548. timeFormat={settings?.time_format || 'system'}
  9549. cameraViewMode={cameraViewMode}
  9550. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9551. onSelectCameraViewMode={selectCameraViewMode}
  9552. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9553. dryingPresets={effectiveDryingPresets}
  9554. nozzleTempPresets={effectiveNozzleTempPresets}
  9555. bedTempPresets={effectiveBedTempPresets}
  9556. chamberTempPresets={effectiveChamberTempPresets}
  9557. fanSpeedPresets={effectiveFanSpeedPresets}
  9558. requirePlateClear={settings?.require_plate_clear === true}
  9559. selectionMode={selectionMode}
  9560. isSelected={selectedPrinterIds.has(printer.id)}
  9561. onToggleSelect={toggleSelect}
  9562. onOpenCompactCard={openCompactCard}
  9563. aiDetectionEnabled={isAiMonitored(printer.id)}
  9564. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9565. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9566. />
  9567. ))}
  9568. </div>
  9569. )}
  9570. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9571. <button
  9572. type="button"
  9573. onClick={returnToCompactCards}
  9574. 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}`}
  9575. title={t('common.back', 'Back')}
  9576. >
  9577. <ArrowLeft className="w-4 h-4" />
  9578. {t('common.back', 'Back')}
  9579. </button>
  9580. )}
  9581. {showAddModal && (
  9582. <AddPrinterModal
  9583. onClose={() => setShowAddModal(false)}
  9584. onAdd={(data) => addMutation.mutate(data)}
  9585. existingSerials={printers?.map(p => p.serial_number) || []}
  9586. />
  9587. )}
  9588. {/* Bulk selection toolbar */}
  9589. {selectionMode && printers && (
  9590. <BulkPrinterToolbar
  9591. selectedIds={selectedPrinterIds}
  9592. printers={printers}
  9593. onClose={clearSelection}
  9594. onSelectAll={selectAll}
  9595. onSelectByLocation={selectByLocation}
  9596. onSelectByState={selectByState}
  9597. onAction={handleBulkAction}
  9598. actionPending={bulkActionPending}
  9599. />
  9600. )}
  9601. {/* Bulk action confirmation modals */}
  9602. {bulkConfirmAction === 'stop' && (
  9603. <ConfirmModal
  9604. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9605. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9606. confirmText={t('printers.bulk.confirm.stopButton')}
  9607. variant="danger"
  9608. isLoading={bulkActionPending}
  9609. onConfirm={() => executeBulkAction('stop')}
  9610. onCancel={() => setBulkConfirmAction(null)}
  9611. />
  9612. )}
  9613. {bulkConfirmAction === 'pause' && (
  9614. <ConfirmModal
  9615. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9616. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9617. confirmText={t('printers.bulk.confirm.pauseButton')}
  9618. isLoading={bulkActionPending}
  9619. onConfirm={() => executeBulkAction('pause')}
  9620. onCancel={() => setBulkConfirmAction(null)}
  9621. />
  9622. )}
  9623. {bulkConfirmAction === 'clearPlate' && (
  9624. <ConfirmModal
  9625. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9626. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9627. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9628. isLoading={bulkActionPending}
  9629. onConfirm={() => executeBulkAction('clearPlate')}
  9630. onCancel={() => setBulkConfirmAction(null)}
  9631. />
  9632. )}
  9633. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9634. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9635. <EmbeddedCameraViewer
  9636. key={camera.id}
  9637. printerId={camera.id}
  9638. printerName={camera.name}
  9639. viewerIndex={index}
  9640. onClose={() => setEmbeddedCameraPrinters(prev => {
  9641. const next = new Map(prev);
  9642. next.delete(camera.id);
  9643. return next;
  9644. })}
  9645. />
  9646. ))}
  9647. </div>
  9648. );
  9649. }