PrintersPage.tsx 436 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { computePopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. BED_TEMP_DEFAULTS,
  8. CHAMBER_TEMP_DEFAULTS,
  9. FAN_SPEED_DEFAULTS,
  10. NOZZLE_TEMP_DEFAULTS,
  11. buildPresetOptions,
  12. parsePresetTriple,
  13. } from '../utils/temperatureFanPresets';
  14. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  15. // covers header + filament select + temp slider + duration + rotate-tray
  16. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  17. // earlier); under-estimating leaves the popover clipped off the bottom (the
  18. // original bug at #1447).
  19. const DRYING_POPOVER_WIDTH = 240;
  20. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  21. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  22. import { useTranslation } from 'react-i18next';
  23. import { useTheme } from '../contexts/ThemeContext';
  24. import { useAuth } from '../contexts/AuthContext';
  25. import {
  26. Plus,
  27. Link,
  28. Unlink,
  29. Signal,
  30. Clock,
  31. MoreVertical,
  32. Trash2,
  33. RefreshCw,
  34. RotateCw,
  35. Box,
  36. HardDrive,
  37. AlertTriangle,
  38. AlertCircle,
  39. Terminal,
  40. Power,
  41. Zap,
  42. Wrench,
  43. ChevronDown,
  44. Filter,
  45. Pencil,
  46. ArrowLeft,
  47. ArrowRight,
  48. ArrowUp,
  49. ArrowDown,
  50. Layers,
  51. Video,
  52. Search,
  53. Loader2,
  54. Square,
  55. Pause,
  56. Play,
  57. X,
  58. Fan,
  59. Wind,
  60. AirVent,
  61. Download,
  62. ScanSearch,
  63. CheckCircle,
  64. CheckSquare,
  65. XCircle,
  66. User,
  67. Home,
  68. Printer as PrinterIcon,
  69. Info,
  70. Cable,
  71. Flame,
  72. Repeat,
  73. Snowflake,
  74. Gauge,
  75. DoorOpen,
  76. DoorClosed,
  77. Move,
  78. LogIn,
  79. LogOut,
  80. MoreHorizontal,
  81. SlidersHorizontal,
  82. Stethoscope,
  83. ScanEye,
  84. LineChart as LineChartIcon,
  85. LayoutGrid,
  86. MonitorPlay,
  87. ExternalLink,
  88. } from 'lucide-react';
  89. // Aliased: lucide-react already exports a `Link` icon into this module.
  90. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  91. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  92. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  93. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  94. import { Card, CardContent } from '../components/Card';
  95. import { Button } from '../components/Button';
  96. import { ConfirmModal } from '../components/ConfirmModal';
  97. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  98. import { FileManagerModal } from '../components/FileManagerModal';
  99. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  100. import { CameraWall } from '../components/CameraWall';
  101. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  102. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  103. import { AiDetectionModal } from '../components/AiDetectionModal';
  104. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  105. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  106. import { AmsBackupModal } from '../components/AmsBackupModal';
  107. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  108. import type { HeaterSensorKind } from '../api/client';
  109. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  110. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  111. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  112. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  113. import { useToast } from '../contexts/ToastContext';
  114. import { ChamberLight } from '../components/icons/ChamberLight';
  115. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  116. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  117. import { FileUploadModal } from '../components/FileUploadModal';
  118. import { PrintModal } from '../components/PrintModal';
  119. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  120. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
  121. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  122. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  123. import { Collapsible } from '../components/Collapsible';
  124. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  125. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  126. export interface SpoolmanSlotAssignmentRow {
  127. printer_id: number;
  128. ams_id: number;
  129. tray_id: number;
  130. spoolman_spool_id: number;
  131. }
  132. // Color names resolve via getColorName() which reads the backend color_catalog
  133. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  134. // Format K value with 3 decimal places, default to 0.020 if null
  135. function formatKValue(k: number | null | undefined): string {
  136. const value = k ?? 0.020;
  137. return value.toFixed(3);
  138. }
  139. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  140. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  141. const { mode } = useTheme();
  142. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  143. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  144. return (
  145. <span
  146. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  147. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  148. >
  149. {side}
  150. </span>
  151. );
  152. }
  153. // Expand nozzle type codes to material names
  154. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  155. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  156. function nozzleTypeName(type: string, t: (key: string) => string): string {
  157. if (!type) return '';
  158. // Full text names (from main nozzle info)
  159. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  160. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  161. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  162. // 4-char codes (e.g. "HS01"): last 2 digits = material
  163. if (type.length >= 4) {
  164. const material = type.slice(2, 4);
  165. if (material === '00') return t('printers.nozzleStainlessSteel');
  166. if (material === '01') return t('printers.nozzleHardenedSteel');
  167. if (material === '05') return t('printers.nozzleTungstenCarbide');
  168. }
  169. // 2-digit numeric codes
  170. if (type === '00') return t('printers.nozzleStainlessSteel');
  171. if (type === '01') return t('printers.nozzleHardenedSteel');
  172. if (type === '05') return t('printers.nozzleTungstenCarbide');
  173. // 2-char alpha codes: H prefix = hardened steel
  174. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  175. return type;
  176. }
  177. // Parse flow type from nozzle type code
  178. // HH = high flow, HS = standard/normal
  179. function nozzleFlowName(type: string, t: (key: string) => string): string {
  180. if (!type) return '';
  181. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  182. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  183. return '';
  184. }
  185. // Per-slot hover card for nozzle rack
  186. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  187. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  188. slot: import('../api/client').NozzleRackSlot;
  189. index: number;
  190. activeStatus?: boolean;
  191. filamentName?: string;
  192. children: React.ReactNode;
  193. }) {
  194. const { t } = useTranslation();
  195. const [isVisible, setIsVisible] = useState(false);
  196. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  197. const triggerRef = useRef<HTMLDivElement>(null);
  198. const cardRef = useRef<HTMLDivElement>(null);
  199. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  200. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  201. const isMounted = slot.stat === 1;
  202. useEffect(() => {
  203. if (isVisible && triggerRef.current && cardRef.current) {
  204. const triggerRect = triggerRef.current.getBoundingClientRect();
  205. const cardHeight = cardRef.current.offsetHeight;
  206. const headerHeight = 56;
  207. const spaceAbove = triggerRect.top - headerHeight;
  208. const spaceBelow = window.innerHeight - triggerRect.bottom;
  209. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  210. setPosition('bottom');
  211. } else {
  212. setPosition('top');
  213. }
  214. }
  215. }, [isVisible]);
  216. const handleMouseEnter = () => {
  217. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  218. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  219. };
  220. const handleMouseLeave = () => {
  221. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  222. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  223. };
  224. useEffect(() => {
  225. return () => {
  226. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  227. };
  228. }, []);
  229. const filamentCss = parseFilamentColor(slot.filament_color);
  230. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  231. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  232. return (
  233. <div
  234. ref={triggerRef}
  235. className="relative"
  236. onMouseEnter={handleMouseEnter}
  237. onMouseLeave={handleMouseLeave}
  238. >
  239. {children}
  240. {isVisible && (
  241. <div
  242. ref={cardRef}
  243. className={`
  244. absolute left-1/2 -translate-x-1/2 z-50
  245. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  246. animate-in fade-in-0 zoom-in-95 duration-150
  247. `}
  248. style={{ maxWidth: 'calc(100vw - 24px)' }}
  249. >
  250. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  251. {isEmpty ? (
  252. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  253. Slot {index + 1} — Empty
  254. </div>
  255. ) : (
  256. <div className="p-2.5 space-y-1.5">
  257. {/* Diameter */}
  258. <div className="flex items-center justify-between">
  259. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  260. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  261. </div>
  262. {/* Type */}
  263. {typeFull && (
  264. <div className="flex items-center justify-between">
  265. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  266. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  267. </div>
  268. )}
  269. {/* Flow (hide if empty) */}
  270. {flowFull && (
  271. <div className="flex items-center justify-between">
  272. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  273. <span className="text-xs text-white font-semibold">{flowFull}</span>
  274. </div>
  275. )}
  276. {/* Status badge */}
  277. <div className="flex items-center justify-between">
  278. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  279. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  280. activeStatus || isMounted
  281. ? 'bg-green-900/50 text-green-400'
  282. : 'bg-bambu-dark-tertiary text-bambu-gray'
  283. }`}>
  284. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  285. </span>
  286. </div>
  287. {/* Wear (hide if null) */}
  288. {slot.wear != null && (
  289. <div className="flex items-center justify-between">
  290. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  291. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  292. </div>
  293. )}
  294. {/* Max Temp (hide if 0) */}
  295. {slot.max_temp > 0 && (
  296. <div className="flex items-center justify-between">
  297. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  298. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  299. </div>
  300. )}
  301. {/* Serial (hide if empty) */}
  302. {slot.serial_number && (
  303. <div className="flex items-center justify-between">
  304. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  305. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  306. </div>
  307. )}
  308. {/* Filament: material type + color swatch (hide if no color) */}
  309. {(filamentCss || slot.filament_type) && (
  310. <div className="flex items-center justify-between">
  311. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  312. <div className="flex items-center gap-1">
  313. {filamentCss && (
  314. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  315. )}
  316. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  317. </div>
  318. </div>
  319. )}
  320. </div>
  321. )}
  322. </div>
  323. {/* Arrow pointer */}
  324. <div
  325. className={`
  326. absolute left-1/2 -translate-x-1/2 w-0 h-0
  327. border-l-[6px] border-l-transparent
  328. border-r-[6px] border-r-transparent
  329. ${position === 'top'
  330. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  331. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  332. `}
  333. />
  334. </div>
  335. )}
  336. </div>
  337. );
  338. }
  339. // Dual-nozzle hover card showing L and R nozzle details side by side
  340. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  341. leftSlot?: import('../api/client').NozzleRackSlot;
  342. rightSlot?: import('../api/client').NozzleRackSlot;
  343. activeNozzle: 'L' | 'R';
  344. filamentInfo?: Record<string, { name: string; k: number | null }>;
  345. children: React.ReactNode;
  346. }) {
  347. const { t } = useTranslation();
  348. const [isVisible, setIsVisible] = useState(false);
  349. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  350. const triggerRef = useRef<HTMLDivElement>(null);
  351. const cardRef = useRef<HTMLDivElement>(null);
  352. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  353. useEffect(() => {
  354. if (isVisible && triggerRef.current && cardRef.current) {
  355. const triggerRect = triggerRef.current.getBoundingClientRect();
  356. const cardHeight = cardRef.current.offsetHeight;
  357. const headerHeight = 56;
  358. const spaceAbove = triggerRect.top - headerHeight;
  359. const spaceBelow = window.innerHeight - triggerRect.bottom;
  360. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  361. setPosition('bottom');
  362. } else {
  363. setPosition('top');
  364. }
  365. }
  366. }, [isVisible]);
  367. const handleMouseEnter = () => {
  368. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  369. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  370. };
  371. const handleMouseLeave = () => {
  372. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  373. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  374. };
  375. useEffect(() => {
  376. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  377. }, []);
  378. if (!leftSlot && !rightSlot) return <>{children}</>;
  379. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  380. const isActive = activeNozzle === side;
  381. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  382. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  383. const filamentCss = parseFilamentColor(slot.filament_color);
  384. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  385. return (
  386. <div className="flex-1 space-y-1.5">
  387. <div className={`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  388. {side === 'L' ? t('common.left') : t('common.right')}
  389. </div>
  390. {slot.nozzle_diameter && (
  391. <div className="flex items-center justify-between">
  392. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  393. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  394. </div>
  395. )}
  396. {typeFull && (
  397. <div className="flex items-center justify-between">
  398. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  399. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  400. </div>
  401. )}
  402. {flowFull && (
  403. <div className="flex items-center justify-between">
  404. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  405. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  406. </div>
  407. )}
  408. <div className="flex items-center justify-between">
  409. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  410. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  411. isActive
  412. ? 'bg-green-900/50 text-green-400'
  413. : 'bg-bambu-dark-tertiary text-bambu-gray'
  414. }`}>
  415. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  416. </span>
  417. </div>
  418. {slot.wear != null && (
  419. <div className="flex items-center justify-between">
  420. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  421. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  422. </div>
  423. )}
  424. {/* Serial and max temp only available on the right (removable) nozzle */}
  425. {side === 'R' && slot.max_temp > 0 && (
  426. <div className="flex items-center justify-between">
  427. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  428. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  429. </div>
  430. )}
  431. {side === 'R' && slot.serial_number && (
  432. <div className="flex items-center justify-between">
  433. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  434. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  435. </div>
  436. )}
  437. {(filamentCss || slot.filament_type || slot.filament_id) && (
  438. <div className="flex items-center justify-between">
  439. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  440. <div className="flex items-center gap-1">
  441. {filamentCss && (
  442. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  443. )}
  444. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  445. {filamentName || slot.filament_type || slot.filament_id || ''}
  446. </span>
  447. </div>
  448. </div>
  449. )}
  450. </div>
  451. );
  452. };
  453. return (
  454. <div
  455. ref={triggerRef}
  456. className="relative flex-1"
  457. onMouseEnter={handleMouseEnter}
  458. onMouseLeave={handleMouseLeave}
  459. >
  460. {children}
  461. {isVisible && (
  462. <div
  463. ref={cardRef}
  464. className={`
  465. absolute left-1/2 -translate-x-1/2 z-50
  466. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  467. animate-in fade-in-0 zoom-in-95 duration-150
  468. `}
  469. style={{ maxWidth: 'calc(100vw - 24px)' }}
  470. >
  471. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  472. <div className="p-2.5 flex gap-3">
  473. {leftSlot && renderColumn(leftSlot, 'L')}
  474. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  475. {rightSlot && renderColumn(rightSlot, 'R')}
  476. </div>
  477. </div>
  478. {/* Arrow pointer */}
  479. <div
  480. className={`
  481. absolute left-1/2 -translate-x-1/2 w-0 h-0
  482. border-l-[6px] border-l-transparent
  483. border-r-[6px] border-r-transparent
  484. ${position === 'top'
  485. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  486. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  487. `}
  488. />
  489. </div>
  490. )}
  491. </div>
  492. );
  493. }
  494. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  495. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  496. const { t } = useTranslation();
  497. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  498. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  499. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  500. // base — computing it from min(present IDs) shifts everything left when slot 16
  501. // is the one currently mounted (#943).
  502. const rackNozzles = slots.filter(s => s.id >= 2);
  503. const RACK_SIZE = 6;
  504. const RACK_BASE_ID = 16;
  505. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  506. { length: RACK_SIZE },
  507. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  508. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  509. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  510. },
  511. );
  512. return (
  513. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  514. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  515. <div className="flex gap-[3px] justify-center">
  516. {rackSlots.map((slot, i) => {
  517. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  518. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  519. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  520. return (
  521. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  522. <div
  523. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  524. isEmpty
  525. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  526. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  527. }`}
  528. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  529. >
  530. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  531. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  532. >
  533. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  534. </span>
  535. </div>
  536. </NozzleSlotHoverCard>
  537. );
  538. })}
  539. </div>
  540. </div>
  541. );
  542. }
  543. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  544. function WaterDropEmpty({ className }: { className?: string }) {
  545. return (
  546. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  547. <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"/>
  548. </svg>
  549. );
  550. }
  551. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  552. function WaterDropHalf({ className }: { className?: string }) {
  553. return (
  554. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  555. <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"/>
  556. <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"/>
  557. </svg>
  558. );
  559. }
  560. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  561. function WaterDropFull({ className }: { className?: string }) {
  562. return (
  563. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  564. <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"/>
  565. <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"/>
  566. </svg>
  567. );
  568. }
  569. // Thermometer SVG - empty outline
  570. function ThermometerEmpty({ className }: { className?: string }) {
  571. return (
  572. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  573. <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"/>
  574. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  575. </svg>
  576. );
  577. }
  578. // Thermometer SVG - half filled (gold - same as humidity fair)
  579. function ThermometerHalf({ className }: { className?: string }) {
  580. return (
  581. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  582. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  583. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  584. <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"/>
  585. </svg>
  586. );
  587. }
  588. // Thermometer SVG - fully filled (red - same as humidity bad)
  589. function ThermometerFull({ className }: { className?: string }) {
  590. return (
  591. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  592. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  593. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  594. <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"/>
  595. </svg>
  596. );
  597. }
  598. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  599. // Added for visual parity with the thermometer icons on the dual-nozzle card
  600. // that previously had no icon at all (#1115, design by @m4rtini2).
  601. function NozzleIcon({ className }: { className?: string }) {
  602. return (
  603. <svg
  604. className={className}
  605. viewBox="0 0 24 24"
  606. fill="none"
  607. xmlns="http://www.w3.org/2000/svg"
  608. stroke="currentColor"
  609. strokeWidth="1.5"
  610. strokeLinecap="round"
  611. strokeLinejoin="round"
  612. >
  613. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  614. <rect x="6" y="11.5" width="12.1" height="3.7" />
  615. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  616. </svg>
  617. );
  618. }
  619. // Heater thermometer icon - filled when heating, outline when off
  620. interface HeaterThermometerProps {
  621. className?: string;
  622. color: string; // The color class (e.g., "text-orange-400")
  623. isHeating: boolean;
  624. }
  625. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  626. // Extract the actual color from Tailwind class for SVG fill
  627. const colorMap: Record<string, string> = {
  628. 'text-orange-400': '#fb923c',
  629. 'text-blue-400': '#60a5fa',
  630. 'text-green-400': '#4ade80',
  631. };
  632. const fillColor = colorMap[color] || '#888';
  633. // Glow style when heating
  634. const glowStyle = isHeating ? {
  635. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  636. } : {};
  637. if (isHeating) {
  638. // Filled thermometer with glow - heater is ON
  639. return (
  640. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  641. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  642. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  643. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  644. </svg>
  645. );
  646. }
  647. // Empty thermometer - heater is OFF
  648. return (
  649. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  650. <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"/>
  651. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  652. </svg>
  653. );
  654. }
  655. // AMS Filament Backup tri-state indicator + toggle.
  656. // state=true → ON, click to disable
  657. // state=false → OFF, click opens modal
  658. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  659. interface AmsBackupBadgeProps {
  660. state: boolean | null;
  661. onClick: () => void;
  662. }
  663. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  664. const { t } = useTranslation();
  665. const known = state !== null;
  666. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  667. let title: string;
  668. if (state === true) {
  669. className += known
  670. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  671. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  672. title = t('printers.amsBackup.titleOn');
  673. } else if (state === false) {
  674. className += known
  675. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  676. : 'bg-bambu-dark text-bambu-gray cursor-default';
  677. title = t('printers.amsBackup.titleOff');
  678. } else {
  679. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  680. title = t('printers.amsBackup.titleUnknown');
  681. }
  682. return (
  683. <button
  684. type="button"
  685. disabled={!known}
  686. onClick={() => known && onClick()}
  687. className={className}
  688. title={title}
  689. aria-label={title}
  690. >
  691. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  692. </button>
  693. );
  694. }
  695. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  696. // Reference: https://github.com/theicedmango/bambu-humidity
  697. interface HumidityIndicatorProps {
  698. humidity: number | string;
  699. goodThreshold?: number; // <= this is green
  700. fairThreshold?: number; // <= this is orange, > is red
  701. onClick?: () => void;
  702. compact?: boolean; // Smaller version for grid layout
  703. }
  704. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  705. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  706. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  707. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  708. // Status thresholds (configurable via settings)
  709. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  710. let textColor: string;
  711. let statusText: string;
  712. if (isNaN(humidityValue)) {
  713. textColor = '#C3C2C1';
  714. statusText = 'Unknown';
  715. } else if (humidityValue <= good) {
  716. textColor = '#22a352'; // Green - Good
  717. statusText = 'Good';
  718. } else if (humidityValue <= fair) {
  719. textColor = '#d4a017'; // Gold - Fair
  720. statusText = 'Fair';
  721. } else {
  722. textColor = '#c62828'; // Red - Bad
  723. statusText = 'Bad';
  724. }
  725. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  726. let DropComponent: React.FC<{ className?: string }>;
  727. if (isNaN(humidityValue)) {
  728. DropComponent = WaterDropEmpty;
  729. } else if (humidityValue <= good) {
  730. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  731. } else if (humidityValue <= fair) {
  732. DropComponent = WaterDropHalf; // Fair - half filled
  733. } else {
  734. DropComponent = WaterDropFull; // Bad - full (too humid)
  735. }
  736. return (
  737. <button
  738. type="button"
  739. onClick={onClick}
  740. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  741. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  742. >
  743. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  744. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  745. </button>
  746. );
  747. }
  748. // Temperature indicator with dynamic icon and coloring
  749. interface TemperatureIndicatorProps {
  750. temp: number;
  751. goodThreshold?: number; // <= this is blue
  752. fairThreshold?: number; // <= this is orange, > is red
  753. onClick?: () => void;
  754. compact?: boolean; // Smaller version for grid layout
  755. }
  756. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  757. // Ensure thresholds are numbers
  758. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  759. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  760. let textColor: string;
  761. let statusText: string;
  762. let ThermoComponent: React.FC<{ className?: string }>;
  763. if (temp <= good) {
  764. textColor = '#22a352'; // Green - good (same as humidity)
  765. statusText = 'Good';
  766. ThermoComponent = ThermometerEmpty;
  767. } else if (temp <= fair) {
  768. textColor = '#d4a017'; // Gold - fair (same as humidity)
  769. statusText = 'Fair';
  770. ThermoComponent = ThermometerHalf;
  771. } else {
  772. textColor = '#c62828'; // Red - bad (same as humidity)
  773. statusText = 'Bad';
  774. ThermoComponent = ThermometerFull;
  775. }
  776. return (
  777. <button
  778. type="button"
  779. onClick={onClick}
  780. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  781. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  782. >
  783. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  784. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  785. </button>
  786. );
  787. }
  788. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  789. *
  790. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  791. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  792. * every empty-by-bitmask slot lands here regardless of firmware payload
  793. * shape.
  794. *
  795. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  796. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  797. * the user cleared with "Reset Slot" where a physical spool may still be
  798. * loaded but unassigned.
  799. *
  800. * Returns null when the slot is loaded (tray_type is present).
  801. */
  802. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  803. if (tray?.tray_type) return null;
  804. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  805. // spool the firmware can't identify is physically present (exists === true)
  806. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  807. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  808. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  809. if (tray?.exists === true) return 'reset';
  810. if (tray?.exists === false) return 'physical';
  811. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  812. }
  813. // How long to wait for an AMS to report a live drying cycle after the printer
  814. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  815. // within a couple of seconds; 30s covers the slowest observed push cadence
  816. // without leaving the user waiting on a verdict.
  817. const DRY_START_CONFIRM_MS = 30_000;
  818. function CoverImage({
  819. url,
  820. printName,
  821. className = 'w-20 h-20',
  822. radiusClass = 'rounded-lg',
  823. }: {
  824. url: string | null;
  825. printName?: string;
  826. className?: string;
  827. radiusClass?: string;
  828. }) {
  829. const { t } = useTranslation();
  830. const [loaded, setLoaded] = useState(false);
  831. const [error, setError] = useState(false);
  832. const [showOverlay, setShowOverlay] = useState(false);
  833. // Cache-bust the image URL when the print name changes so the browser
  834. // fetches the new cover instead of serving the stale cached image.
  835. const cacheBustedUrl = useMemo(() => {
  836. if (!url) return null;
  837. const sep = url.includes('?') ? '&' : '?';
  838. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  839. }, [url, printName]);
  840. // Reset loaded/error state when the image URL changes
  841. useEffect(() => {
  842. setLoaded(false);
  843. setError(false);
  844. }, [cacheBustedUrl]);
  845. return (
  846. <>
  847. <div
  848. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  849. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  850. >
  851. {cacheBustedUrl && !error ? (
  852. <>
  853. <img
  854. src={cacheBustedUrl}
  855. alt={t('printers.printPreview')}
  856. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  857. onLoad={() => setLoaded(true)}
  858. onError={() => setError(true)}
  859. />
  860. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  861. </>
  862. ) : (
  863. <Box className="w-8 h-8 text-bambu-gray" />
  864. )}
  865. </div>
  866. {/* Cover Image Overlay */}
  867. {showOverlay && cacheBustedUrl && (
  868. <div
  869. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  870. onClick={() => setShowOverlay(false)}
  871. >
  872. <div className="relative max-w-2xl max-h-full">
  873. <img
  874. src={cacheBustedUrl}
  875. alt={t('printers.printPreview')}
  876. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  877. />
  878. {printName && (
  879. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  880. )}
  881. </div>
  882. </div>
  883. )}
  884. </>
  885. );
  886. }
  887. interface PrinterMaintenanceInfo {
  888. due_count: number;
  889. warning_count: number;
  890. total_print_hours: number;
  891. }
  892. // Status summary bar component - uses queryClient to read cached statuses
  893. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  894. const { t } = useTranslation();
  895. const queryClient = useQueryClient();
  896. // Subscribe to query cache changes to re-render when status updates
  897. // Throttled to prevent rapid re-renders from causing tab crashes
  898. const [cacheTick, setCacheTick] = useState(0);
  899. useEffect(() => {
  900. let pending = false;
  901. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  902. if (!pending) {
  903. pending = true;
  904. requestAnimationFrame(() => {
  905. setCacheTick(t => t + 1);
  906. pending = false;
  907. });
  908. }
  909. });
  910. return () => unsubscribe();
  911. }, [queryClient]);
  912. const { counts, nextFinish } = useMemo(() => {
  913. let printing = 0;
  914. let paused = 0;
  915. let finished = 0;
  916. let idle = 0;
  917. let offline = 0;
  918. let loading = 0;
  919. let error = 0;
  920. let nextPrinterName: string | null = null;
  921. let nextRemainingMin: number | null = null;
  922. let nextProgress: number = 0;
  923. printers?.forEach((printer) => {
  924. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  925. if (status === undefined) {
  926. // Status not yet loaded - don't count as offline yet
  927. loading++;
  928. } else if (!status.connected) {
  929. offline++;
  930. } else {
  931. // Count printers with active HMS errors as problems
  932. const knownHmsCount =
  933. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  934. if (knownHmsCount > 0) {
  935. error++;
  936. }
  937. switch (status.state) {
  938. case 'RUNNING':
  939. printing++;
  940. if (status.remaining_time != null && status.remaining_time > 0) {
  941. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  942. nextRemainingMin = status.remaining_time;
  943. nextPrinterName = printer.name;
  944. nextProgress = status.progress || 0;
  945. }
  946. }
  947. break;
  948. case 'PAUSE':
  949. paused++;
  950. break;
  951. case 'FINISH':
  952. finished++;
  953. break;
  954. case 'FAILED':
  955. // FAILED is the printer's terminal gcode_state after a print stops —
  956. // including user cancellations, where there's no actual fault. Only
  957. // count it as a "problem" when an HMS error is also active; otherwise
  958. // it's just a print that ended unsuccessfully and the plate needs
  959. // clearing (same as FINISH from the operator's perspective).
  960. if (knownHmsCount > 0) {
  961. // Already counted above
  962. } else {
  963. finished++;
  964. }
  965. break;
  966. default:
  967. idle++;
  968. break;
  969. }
  970. }
  971. });
  972. return {
  973. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  974. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  975. };
  976. // eslint-disable-next-line react-hooks/exhaustive-deps
  977. }, [printers, queryClient, cacheTick]);
  978. if (!printers?.length) return null;
  979. const badges: { count: number; dot: string; label: string }[] = [
  980. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  981. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  982. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  983. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  984. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  985. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  986. ];
  987. return (
  988. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  989. {badges.map(({ count, dot, label }) => count > 0 && (
  990. <div key={label} className="flex items-center gap-1.5">
  991. <div className={`w-2 h-2 rounded-full ${dot}`} />
  992. <span className="text-bambu-gray">
  993. <span className="text-white font-medium">{count}</span> {label}
  994. </span>
  995. </div>
  996. ))}
  997. {nextFinish && (
  998. <>
  999. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1000. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1001. <div className="flex items-center gap-2">
  1002. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1003. <span className="text-white font-medium">{nextFinish.name}</span>
  1004. </div>
  1005. <div className="flex items-center gap-2 w-full sm:w-auto">
  1006. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1007. <div
  1008. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1009. style={{ width: `${nextFinish.progress}%` }}
  1010. />
  1011. </div>
  1012. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1013. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1014. </div>
  1015. </div>
  1016. </>
  1017. )}
  1018. </div>
  1019. );
  1020. }
  1021. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1022. type ViewMode = 'expanded' | 'compact';
  1023. type ToolbarDropdownOption<T extends string> = {
  1024. value: T;
  1025. label: string;
  1026. };
  1027. function ToolbarDropdown<T extends string>({
  1028. value,
  1029. options,
  1030. onChange,
  1031. fullWidth = false,
  1032. }: {
  1033. value: T;
  1034. options: ToolbarDropdownOption<T>[];
  1035. onChange: (value: T) => void;
  1036. fullWidth?: boolean;
  1037. }) {
  1038. const [isOpen, setIsOpen] = useState(false);
  1039. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1040. return (
  1041. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1042. <button
  1043. type="button"
  1044. onClick={() => setIsOpen(open => !open)}
  1045. 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'}`}
  1046. >
  1047. <span className="truncate">{selectedOption?.label}</span>
  1048. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1049. </button>
  1050. {isOpen && (
  1051. <>
  1052. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1053. <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">
  1054. {options.map(option => (
  1055. <button
  1056. key={option.value}
  1057. type="button"
  1058. onClick={() => {
  1059. onChange(option.value);
  1060. setIsOpen(false);
  1061. }}
  1062. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1063. option.value === value ? 'text-bambu-green' : 'text-white'
  1064. }`}
  1065. >
  1066. {option.label}
  1067. </button>
  1068. ))}
  1069. </div>
  1070. </>
  1071. )}
  1072. </div>
  1073. );
  1074. }
  1075. function ToolbarMenu({
  1076. label,
  1077. icon,
  1078. children,
  1079. }: {
  1080. label: string;
  1081. icon: React.ReactNode;
  1082. children: React.ReactNode;
  1083. }) {
  1084. const [isOpen, setIsOpen] = useState(false);
  1085. return (
  1086. <div className="relative">
  1087. <button
  1088. type="button"
  1089. onClick={() => setIsOpen(open => !open)}
  1090. 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"
  1091. aria-label={label}
  1092. title={label}
  1093. >
  1094. {icon}
  1095. </button>
  1096. {isOpen && (
  1097. <>
  1098. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1099. <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">
  1100. {children}
  1101. </div>
  1102. </>
  1103. )}
  1104. </div>
  1105. );
  1106. }
  1107. function IndicatorControlPopover({
  1108. title,
  1109. options = [],
  1110. unit,
  1111. customMin,
  1112. customMax,
  1113. customStep = 1,
  1114. widthClass = 'w-[240px]',
  1115. popoverWidth = 240,
  1116. popoverHeight = 280,
  1117. isPending,
  1118. onClose,
  1119. onSubmit,
  1120. children,
  1121. }: {
  1122. title: string;
  1123. options?: Array<{ label: string; value: number }>;
  1124. unit?: string;
  1125. customMin?: number;
  1126. customMax?: number;
  1127. customStep?: number;
  1128. widthClass?: string;
  1129. popoverWidth?: number;
  1130. popoverHeight?: number;
  1131. isPending?: boolean;
  1132. onClose: () => void;
  1133. onSubmit?: (value: number) => void;
  1134. children?: React.ReactNode;
  1135. }) {
  1136. const anchorRef = useRef<HTMLSpanElement>(null);
  1137. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1138. const [customValue, setCustomValue] = useState('');
  1139. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1140. // can position via fixed coords. Portaling to document.body escapes
  1141. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1142. // own contexts and would otherwise cover the popover even at z-[60].
  1143. useLayoutEffect(() => {
  1144. const trigger = anchorRef.current?.parentElement;
  1145. if (!trigger) return;
  1146. const measure = () => {
  1147. const rect = trigger.getBoundingClientRect();
  1148. setCoords(computePopoverPosition({
  1149. triggerRect: rect,
  1150. popoverWidth,
  1151. estimatedHeight: popoverHeight,
  1152. horizontalAlign: 'center',
  1153. }));
  1154. };
  1155. measure();
  1156. window.addEventListener('resize', measure);
  1157. window.addEventListener('scroll', measure, true);
  1158. return () => {
  1159. window.removeEventListener('resize', measure);
  1160. window.removeEventListener('scroll', measure, true);
  1161. };
  1162. }, [popoverWidth, popoverHeight]);
  1163. const showCustomInput = unit !== undefined;
  1164. const submitCustom = () => {
  1165. const value = Number(customValue);
  1166. if (!Number.isFinite(value)) return;
  1167. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1168. onSubmit?.(Math.round(bounded));
  1169. };
  1170. return (
  1171. <>
  1172. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1173. {createPortal(
  1174. <>
  1175. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1176. <div
  1177. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1178. style={{
  1179. top: coords?.top ?? -9999,
  1180. left: coords?.left ?? -9999,
  1181. visibility: coords ? 'visible' : 'hidden',
  1182. }}
  1183. onClick={e => e.stopPropagation()}
  1184. >
  1185. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1186. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1187. {options.length > 0 && (
  1188. <div className="px-3 py-2.5">
  1189. <div className="grid grid-cols-2 gap-1.5">
  1190. {options.map(option => (
  1191. <button
  1192. key={`${option.label}-${option.value}`}
  1193. type="button"
  1194. disabled={isPending}
  1195. onClick={() => onSubmit?.(option.value)}
  1196. 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"
  1197. >
  1198. {option.label}
  1199. </button>
  1200. ))}
  1201. </div>
  1202. </div>
  1203. )}
  1204. {children}
  1205. {showCustomInput && (
  1206. <>
  1207. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1208. <form
  1209. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1210. onSubmit={(e) => {
  1211. e.preventDefault();
  1212. submitCustom();
  1213. }}
  1214. >
  1215. <input
  1216. type="number"
  1217. min={customMin}
  1218. max={customMax}
  1219. step={customStep}
  1220. value={customValue}
  1221. onChange={e => setCustomValue(e.target.value)}
  1222. placeholder="Custom"
  1223. 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"
  1224. />
  1225. <button
  1226. type="submit"
  1227. disabled={isPending || customValue.trim() === ''}
  1228. 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"
  1229. >
  1230. Set
  1231. </button>
  1232. </form>
  1233. </>
  1234. )}
  1235. </div>
  1236. </>,
  1237. document.body
  1238. )}
  1239. </>
  1240. );
  1241. }
  1242. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1243. function NozzleTemperatureControlBox({
  1244. label,
  1245. current,
  1246. target,
  1247. isActive,
  1248. isPending,
  1249. onSubmit,
  1250. options = NOZZLE_TEMPERATURE_OPTIONS,
  1251. }: {
  1252. label: string;
  1253. current?: number;
  1254. target?: number;
  1255. isActive: boolean;
  1256. isPending?: boolean;
  1257. onSubmit: (value: number) => void;
  1258. options?: Array<{ label: string; value: number }>;
  1259. }) {
  1260. const [customValue, setCustomValue] = useState('');
  1261. const submitCustom = () => {
  1262. const value = Number(customValue);
  1263. if (!Number.isFinite(value)) return;
  1264. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1265. };
  1266. return (
  1267. <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'}`}>
  1268. <div className="mb-1.5 flex items-center justify-between gap-2">
  1269. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1270. <span className="text-[10px] text-bambu-gray">
  1271. {Math.round(current ?? 0)}°C
  1272. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1273. </span>
  1274. </div>
  1275. <div className="grid grid-cols-2 gap-1">
  1276. {options.map(option => (
  1277. <button
  1278. key={`${label}-${option.value}`}
  1279. type="button"
  1280. disabled={isPending}
  1281. onClick={() => onSubmit(option.value)}
  1282. 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"
  1283. >
  1284. {option.label}
  1285. </button>
  1286. ))}
  1287. </div>
  1288. <form
  1289. className="mt-1.5 flex gap-1"
  1290. onSubmit={(e) => {
  1291. e.preventDefault();
  1292. submitCustom();
  1293. }}
  1294. >
  1295. <input
  1296. type="number"
  1297. min={0}
  1298. max={320}
  1299. step={1}
  1300. value={customValue}
  1301. onChange={e => setCustomValue(e.target.value)}
  1302. placeholder="Custom"
  1303. 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"
  1304. />
  1305. <button
  1306. type="submit"
  1307. disabled={isPending || customValue.trim() === ''}
  1308. 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"
  1309. >
  1310. Set
  1311. </button>
  1312. </form>
  1313. </div>
  1314. );
  1315. }
  1316. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1317. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1318. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1319. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1320. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1321. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1322. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1323. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1324. };
  1325. /** Classify a printer into one of the UI status buckets. */
  1326. function classifyPrinterStatus(
  1327. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1328. ): PrinterState {
  1329. if (!status?.connected) return 'offline';
  1330. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1331. if (hmsErrors.length > 0) return 'error';
  1332. switch (status.state) {
  1333. case 'RUNNING': return 'printing';
  1334. case 'PAUSE': return 'paused';
  1335. case 'FINISH': return 'finished';
  1336. // FAILED without an active HMS error is the printer's terminal state after
  1337. // any unsuccessful end — including user-cancellations. Treat the same as
  1338. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1339. // HMS code is actually attached (handled by the early-return above).
  1340. case 'FAILED': return 'finished';
  1341. default: return 'idle';
  1342. }
  1343. }
  1344. /**
  1345. * Get human-readable status display text for a printer.
  1346. * Uses stg_cur_name for detailed calibration/preparation stages,
  1347. * otherwise formats the gcode_state nicely.
  1348. */
  1349. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1350. // If we have a specific stage name (calibration, heating, etc.), use it
  1351. if (stg_cur_name) {
  1352. return stg_cur_name;
  1353. }
  1354. // Format the gcode_state nicely
  1355. switch (state) {
  1356. case 'RUNNING':
  1357. return 'Printing';
  1358. case 'PAUSE':
  1359. return 'Paused';
  1360. case 'FINISH':
  1361. return 'Finished';
  1362. case 'FAILED':
  1363. return 'Failed';
  1364. case 'IDLE':
  1365. return 'Idle';
  1366. default:
  1367. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1368. }
  1369. }
  1370. // Bambu models that ship with an enclosure chamber fan (firmware field
  1371. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1372. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1373. // widget is hidden in fanItems instead of rendered greyed-out.
  1374. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1375. 'X1C',
  1376. 'X1',
  1377. 'X1E',
  1378. 'X2D',
  1379. 'P1S',
  1380. 'P2S',
  1381. 'H2D',
  1382. 'H2D Pro',
  1383. 'H2C',
  1384. 'H2S',
  1385. ]);
  1386. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1387. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1388. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1389. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1390. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1391. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1392. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1393. 'P2S',
  1394. 'X2D',
  1395. ]);
  1396. // Map SSDP model codes to display names
  1397. function mapModelCode(ssdpModel: string | null): string {
  1398. if (!ssdpModel) return '';
  1399. const modelMap: Record<string, string> = {
  1400. // H2 Series
  1401. 'O1D': 'H2D',
  1402. 'O1E': 'H2D Pro',
  1403. 'O2D': 'H2D Pro',
  1404. 'O1C': 'H2C',
  1405. 'O1C2': 'H2C',
  1406. 'O1S': 'H2S',
  1407. // X1 Series
  1408. 'BL-P001': 'X1C',
  1409. 'BL-P002': 'X1',
  1410. 'BL-P003': 'X1E',
  1411. // X2 Series
  1412. 'N6': 'X2D',
  1413. // A2 Series
  1414. 'N9': 'A2L',
  1415. // P Series
  1416. 'C11': 'P1S',
  1417. 'C12': 'P1P',
  1418. 'C13': 'P2S',
  1419. // A1 Series
  1420. 'N2S': 'A1',
  1421. 'N1': 'A1 Mini',
  1422. // Direct matches
  1423. 'X1C': 'X1C',
  1424. 'X1': 'X1',
  1425. 'X1E': 'X1E',
  1426. 'X2D': 'X2D',
  1427. 'P1S': 'P1S',
  1428. 'P1P': 'P1P',
  1429. 'P2S': 'P2S',
  1430. 'A1': 'A1',
  1431. 'A1 Mini': 'A1 Mini',
  1432. 'A2L': 'A2L',
  1433. 'H2D': 'H2D',
  1434. 'H2D Pro': 'H2D Pro',
  1435. 'H2C': 'H2C',
  1436. 'H2S': 'H2S',
  1437. };
  1438. return modelMap[ssdpModel] || ssdpModel;
  1439. }
  1440. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1441. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1442. // • User-defined friendly name (editable, protected by printers:update)
  1443. // • AMS serial number
  1444. // • AMS firmware version
  1445. export function AmsNameHoverCard({
  1446. ams,
  1447. printerId,
  1448. label,
  1449. amsLabels,
  1450. canEdit,
  1451. onSaved,
  1452. children,
  1453. }: {
  1454. ams: import('../api/client').AMSUnit;
  1455. printerId: number;
  1456. label: string; // auto-generated label, e.g. "AMS-A"
  1457. amsLabels?: Record<number, string>;
  1458. canEdit: boolean;
  1459. onSaved: () => void;
  1460. children: React.ReactNode;
  1461. }) {
  1462. const { t } = useTranslation();
  1463. const [isVisible, setIsVisible] = useState(false);
  1464. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1465. const [editValue, setEditValue] = useState('');
  1466. const [isSaving, setIsSaving] = useState(false);
  1467. const [saveError, setSaveError] = useState<string | null>(null);
  1468. const [isInputFocused, setIsInputFocused] = useState(false);
  1469. const triggerRef = useRef<HTMLDivElement>(null);
  1470. const cardRef = useRef<HTMLDivElement>(null);
  1471. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1472. useEffect(() => {
  1473. if (isVisible) {
  1474. setEditValue(amsLabels?.[ams.id] ?? '');
  1475. setSaveError(null);
  1476. requestAnimationFrame(() => {
  1477. if (triggerRef.current && cardRef.current) {
  1478. const rect = triggerRef.current.getBoundingClientRect();
  1479. const spaceAbove = rect.top - 56;
  1480. const spaceBelow = window.innerHeight - rect.bottom;
  1481. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1482. }
  1483. });
  1484. }
  1485. }, [isVisible, amsLabels, ams.id]);
  1486. const handleMouseEnter = () => {
  1487. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1488. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1489. };
  1490. const handleMouseLeave = () => {
  1491. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1492. if (!isInputFocused) {
  1493. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1494. }
  1495. };
  1496. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1497. const handleSave = async () => {
  1498. if (!canEdit) return;
  1499. setIsSaving(true);
  1500. setSaveError(null);
  1501. try {
  1502. const trimmed = editValue.trim();
  1503. if (trimmed) {
  1504. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1505. } else {
  1506. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1507. }
  1508. onSaved();
  1509. setIsVisible(false);
  1510. } catch (err) {
  1511. setSaveError(err instanceof Error ? err.message : String(err));
  1512. } finally {
  1513. setIsSaving(false);
  1514. }
  1515. };
  1516. const handleClear = async () => {
  1517. if (!canEdit) return;
  1518. setIsSaving(true);
  1519. setSaveError(null);
  1520. try {
  1521. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1522. onSaved();
  1523. setIsVisible(false);
  1524. } catch (err) {
  1525. setSaveError(err instanceof Error ? err.message : String(err));
  1526. } finally {
  1527. setIsSaving(false);
  1528. }
  1529. };
  1530. return (
  1531. <div
  1532. ref={triggerRef}
  1533. className="relative inline-block"
  1534. onMouseEnter={handleMouseEnter}
  1535. onMouseLeave={handleMouseLeave}
  1536. >
  1537. {children}
  1538. {isVisible && (
  1539. <div
  1540. ref={cardRef}
  1541. className={`
  1542. absolute left-0 z-50
  1543. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1544. animate-in fade-in-0 zoom-in-95 duration-150
  1545. `}
  1546. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1547. onMouseEnter={handleMouseEnter}
  1548. onMouseLeave={handleMouseLeave}
  1549. >
  1550. <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">
  1551. {/* AMS auto-label */}
  1552. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1553. {/* Serial number */}
  1554. <div className="flex items-center justify-between gap-2">
  1555. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1556. {t('printers.amsPopup.serialNumber')}
  1557. </span>
  1558. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1559. </div>
  1560. {/* Firmware version */}
  1561. <div className="flex items-center justify-between gap-2">
  1562. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1563. {t('printers.amsPopup.firmwareVersion')}
  1564. </span>
  1565. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1566. </div>
  1567. {/* Friendly name editor */}
  1568. <div className="space-y-1">
  1569. <div className="flex items-center gap-2">
  1570. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1571. {t('printers.amsPopup.friendlyName')}
  1572. </span>
  1573. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1574. </div>
  1575. <input
  1576. type="text"
  1577. value={editValue}
  1578. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1579. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1580. onFocus={() => setIsInputFocused(true)}
  1581. onBlur={() => {
  1582. setIsInputFocused(false);
  1583. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1584. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1585. }}
  1586. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1587. disabled={!canEdit}
  1588. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1589. 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"
  1590. maxLength={100}
  1591. />
  1592. {canEdit && (
  1593. <div className="space-y-1">
  1594. {saveError && (
  1595. <p className="text-[10px] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1596. )}
  1597. <div className="flex gap-1 justify-end">
  1598. <button
  1599. onClick={handleSave}
  1600. disabled={isSaving}
  1601. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1602. >
  1603. {t('printers.amsPopup.save')}
  1604. </button>
  1605. {amsLabels?.[ams.id] && (
  1606. <button
  1607. onClick={handleClear}
  1608. disabled={isSaving}
  1609. className="px-2 py-0.5 text-[10px] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1610. >
  1611. {t('printers.amsPopup.clear')}
  1612. </button>
  1613. )}
  1614. </div>
  1615. </div>
  1616. )}
  1617. </div>
  1618. </div>
  1619. </div>
  1620. )}
  1621. </div>
  1622. );
  1623. }
  1624. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1625. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1626. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1627. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1628. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1629. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1630. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1631. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1632. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1633. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1634. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1635. };
  1636. function PrinterCard({
  1637. printer,
  1638. hideIfDisconnected,
  1639. maintenanceInfo,
  1640. viewMode = 'expanded',
  1641. cardSize = 2,
  1642. amsThresholds,
  1643. spoolmanEnabled = false,
  1644. linkedSpools,
  1645. spoolmanUrl,
  1646. spoolmanSyncMode,
  1647. onGetAssignment,
  1648. onUnassignSpool,
  1649. spoolmanSpools,
  1650. spoolmanSlotAssignments,
  1651. spoolmanLoading = false,
  1652. onUnassignSpoolmanSpool,
  1653. timeFormat = 'system',
  1654. cameraViewMode = 'window',
  1655. onOpenEmbeddedCamera,
  1656. checkPrinterFirmware = true,
  1657. dryingPresets = DRYING_PRESETS,
  1658. requirePlateClear = false,
  1659. selectionMode = false,
  1660. isSelected = false,
  1661. onToggleSelect,
  1662. onOpenCompactCard,
  1663. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1664. bedTempPresets = BED_TEMP_DEFAULTS,
  1665. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1666. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1667. aiDetectionEnabled = false,
  1668. aiDetection,
  1669. aiLastError = null,
  1670. }: {
  1671. printer: Printer;
  1672. hideIfDisconnected?: boolean;
  1673. maintenanceInfo?: PrinterMaintenanceInfo;
  1674. viewMode?: ViewMode;
  1675. cardSize?: number;
  1676. amsThresholds?: {
  1677. humidityGood: number;
  1678. humidityFair: number;
  1679. tempGood: number;
  1680. tempFair: number;
  1681. };
  1682. spoolmanEnabled?: boolean;
  1683. hasUnlinkedSpools?: boolean;
  1684. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1685. spoolmanUrl?: string | null;
  1686. spoolmanSyncMode?: string | null;
  1687. spoolAssignments?: SpoolAssignment[];
  1688. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1689. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1690. spoolmanSpools?: InventorySpool[];
  1691. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1692. spoolmanLoading?: boolean;
  1693. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1694. timeFormat?: 'system' | '12h' | '24h';
  1695. cameraViewMode?: 'window' | 'embedded';
  1696. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1697. checkPrinterFirmware?: boolean;
  1698. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1699. requirePlateClear?: boolean;
  1700. selectionMode?: boolean;
  1701. isSelected?: boolean;
  1702. onToggleSelect?: (id: number) => void;
  1703. onOpenCompactCard?: (id: number) => void;
  1704. nozzleTempPresets?: readonly [number, number, number];
  1705. bedTempPresets?: readonly [number, number, number];
  1706. chamberTempPresets?: readonly [number, number, number];
  1707. fanSpeedPresets?: readonly [number, number, number];
  1708. aiDetectionEnabled?: boolean;
  1709. aiDetection?: { class: string; frame_count: number; score: number };
  1710. aiLastError?: string | null;
  1711. }) {
  1712. const { t } = useTranslation();
  1713. const queryClient = useQueryClient();
  1714. const navigate = useNavigate();
  1715. const { showToast } = useToast();
  1716. const { hasPermission } = useAuth();
  1717. const [showMenu, setShowMenu] = useState(false);
  1718. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1719. const [deleteArchives, setDeleteArchives] = useState(true);
  1720. const [showEditModal, setShowEditModal] = useState(false);
  1721. const [showFileManager, setShowFileManager] = useState(false);
  1722. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1723. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1724. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1725. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1726. const [showHMSModal, setShowHMSModal] = useState(false);
  1727. // #1546: AI failure detection modal — opens from the AI badge.
  1728. const [showAiModal, setShowAiModal] = useState(false);
  1729. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1730. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1731. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1732. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1733. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1734. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1735. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1736. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1737. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1738. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1739. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1740. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1741. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1742. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1743. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1744. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1745. // AMS drying popover state: which AMS unit has the popover open
  1746. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1747. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1748. const [dryingFilament, setDryingFilament] = useState('PLA');
  1749. const [dryingTemp, setDryingTemp] = useState(50);
  1750. const [dryingDuration, setDryingDuration] = useState(4);
  1751. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1752. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1753. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  1754. // an object rather than a bare id so restarting drying on the SAME unit produces
  1755. // a new identity and rearms the timeout below.
  1756. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  1757. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1758. const [isDropUploading, setIsDropUploading] = useState(false);
  1759. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1760. const dragCounterRef = useRef(0);
  1761. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1762. amsId: number;
  1763. amsLabel: string;
  1764. mode: 'humidity' | 'temperature';
  1765. } | null>(null);
  1766. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1767. initialKind: HeaterSensorKind;
  1768. availableKinds: HeaterSensorKind[];
  1769. } | null>(null);
  1770. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1771. tagUid: string;
  1772. trayUuid: string;
  1773. printerId: number;
  1774. amsId: number;
  1775. trayId: number;
  1776. } | null>(null);
  1777. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1778. printerId: number;
  1779. amsId: number;
  1780. trayId: number;
  1781. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1782. } | null>(null);
  1783. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1784. amsId: number;
  1785. trayId: number;
  1786. trayCount: number;
  1787. trayType?: string;
  1788. trayColor?: string;
  1789. traySubBrands?: string;
  1790. trayInfoIdx?: string;
  1791. extruderId?: number;
  1792. caliIdx?: number | null;
  1793. savedPresetId?: string;
  1794. } | null>(null);
  1795. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1796. const [plateCheckResult, setPlateCheckResult] = useState<{
  1797. is_empty: boolean;
  1798. confidence: number;
  1799. difference_percent: number;
  1800. message: string;
  1801. debug_image_url?: string;
  1802. needs_calibration: boolean;
  1803. light_warning?: boolean;
  1804. reference_count?: number;
  1805. max_references?: number;
  1806. roi?: { x: number; y: number; w: number; h: number };
  1807. } | null>(null);
  1808. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1809. const [isCalibrating, setIsCalibrating] = useState(false);
  1810. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1811. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1812. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1813. const { data: status } = useQuery({
  1814. queryKey: ['printerStatus', printer.id],
  1815. queryFn: () => api.getPrinterStatus(printer.id),
  1816. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1817. });
  1818. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1819. const { data: firmwareInfo } = useQuery({
  1820. queryKey: ['firmwareUpdate', printer.id],
  1821. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1822. staleTime: 5 * 60 * 1000,
  1823. refetchInterval: 5 * 60 * 1000,
  1824. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1825. });
  1826. // Collect unique tray_info_idx values for cloud filament info lookup
  1827. const trayInfoIds = useMemo(() => {
  1828. const ids = new Set<string>();
  1829. if (status?.ams) {
  1830. for (const ams of status.ams) {
  1831. for (const tray of ams.tray || []) {
  1832. if (tray.tray_info_idx) {
  1833. ids.add(tray.tray_info_idx);
  1834. }
  1835. }
  1836. }
  1837. }
  1838. for (const vt of status?.vt_tray ?? []) {
  1839. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1840. }
  1841. if (status?.nozzle_rack) {
  1842. for (const slot of status.nozzle_rack) {
  1843. if (slot.filament_id) {
  1844. ids.add(slot.filament_id);
  1845. }
  1846. }
  1847. }
  1848. return Array.from(ids);
  1849. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1850. // Collect loaded filament types for queue widget filtering
  1851. const loadedFilamentTypes = useMemo(() => {
  1852. const types = new Set<string>();
  1853. if (status?.ams) {
  1854. for (const ams of status.ams) {
  1855. for (const tray of ams.tray || []) {
  1856. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1857. }
  1858. }
  1859. }
  1860. for (const vt of status?.vt_tray ?? []) {
  1861. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1862. }
  1863. return types;
  1864. }, [status?.ams, status?.vt_tray]);
  1865. // Collect loaded filament type+color pairs for queue widget override matching
  1866. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1867. const loadedFilaments = useMemo(() => {
  1868. const filaments = new Set<string>();
  1869. if (status?.ams) {
  1870. for (const ams of status.ams) {
  1871. for (const tray of ams.tray || []) {
  1872. if (tray.tray_type && tray.tray_color) {
  1873. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1874. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1875. }
  1876. }
  1877. }
  1878. }
  1879. for (const vt of status?.vt_tray ?? []) {
  1880. if (vt.tray_type && vt.tray_color) {
  1881. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1882. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1883. }
  1884. }
  1885. return filaments;
  1886. }, [status?.ams, status?.vt_tray]);
  1887. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  1888. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  1889. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  1890. const loadedVariants = useMemo(() => {
  1891. const variants = new Set<string>();
  1892. if (status?.ams) {
  1893. for (const ams of status.ams) {
  1894. for (const tray of ams.tray || []) {
  1895. if (tray.tray_type && tray.tray_color) {
  1896. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1897. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  1898. }
  1899. }
  1900. }
  1901. }
  1902. for (const vt of status?.vt_tray ?? []) {
  1903. if (vt.tray_type && vt.tray_color) {
  1904. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1905. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  1906. }
  1907. }
  1908. return variants;
  1909. }, [status?.ams, status?.vt_tray]);
  1910. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1911. const { data: filamentInfo } = useQuery({
  1912. queryKey: ['filamentInfo', trayInfoIds],
  1913. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1914. enabled: trayInfoIds.length > 0,
  1915. staleTime: 5 * 60 * 1000, // 5 minutes
  1916. });
  1917. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1918. const { data: slotPresets } = useQuery({
  1919. queryKey: ['slotPresets', printer.id],
  1920. queryFn: () => api.getSlotPresets(printer.id),
  1921. staleTime: 2 * 60 * 1000, // 2 minutes
  1922. });
  1923. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1924. // Only queried when there's a running print backed by an archive; shared
  1925. // React Query cache with the Queue / Archives pages keeps it cheap.
  1926. const activeArchiveId =
  1927. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1928. const { data: activeArchivePlates } = useQuery({
  1929. queryKey: ['archive-plates', activeArchiveId],
  1930. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1931. enabled: activeArchiveId != null,
  1932. staleTime: 5 * 60 * 1000,
  1933. });
  1934. const activePlateLabel = (() => {
  1935. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1936. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1937. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1938. })();
  1939. // Fetch user-defined AMS friendly names from the database
  1940. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1941. queryKey: ['amsLabels', printer.id],
  1942. queryFn: () => api.getAmsLabels(printer.id),
  1943. staleTime: 5 * 60 * 1000, // 5 minutes
  1944. });
  1945. // Cache WiFi signal to prevent it disappearing on updates
  1946. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1947. useEffect(() => {
  1948. if (status?.wifi_signal != null) {
  1949. setCachedWifiSignal(status.wifi_signal);
  1950. }
  1951. }, [status?.wifi_signal]);
  1952. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1953. // Cache connected state to prevent flicker when status briefly becomes undefined
  1954. const cachedConnected = useRef<boolean | undefined>(undefined);
  1955. useEffect(() => {
  1956. if (status?.connected !== undefined) {
  1957. cachedConnected.current = status.connected;
  1958. }
  1959. }, [status?.connected]);
  1960. const isConnected = status?.connected ?? cachedConnected.current;
  1961. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1962. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1963. useEffect(() => {
  1964. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1965. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1966. }
  1967. }, [status?.ams_extruder_map]);
  1968. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1969. ? status.ams_extruder_map
  1970. : cachedAmsExtruderMap.current;
  1971. // Cache AMS data to prevent it disappearing on idle/offline printers
  1972. const cachedAmsData = useRef<AMSUnit[]>([]);
  1973. useEffect(() => {
  1974. if (status?.ams && status.ams.length > 0) {
  1975. cachedAmsData.current = status.ams;
  1976. }
  1977. }, [status?.ams]);
  1978. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1979. // Confirm a drying cycle actually started (#2533). Firmware answers
  1980. // ams_filament_drying with result=success even when it then silently declines,
  1981. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  1982. // reason guard is blind there and the card just sits unchanged. Watch the unit
  1983. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  1984. // means the printer took the command and dropped it.
  1985. useEffect(() => {
  1986. if (!dryStartWatch) return;
  1987. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  1988. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  1989. }, [dryStartWatch, amsData]);
  1990. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  1991. // otherwise rearm the timeout on every frame, so it would never elapse.
  1992. useEffect(() => {
  1993. if (!dryStartWatch) return;
  1994. const timer = setTimeout(() => {
  1995. setDryStartWatch(null);
  1996. showToast(t('printers.drying.toastNotStarted'), 'error');
  1997. }, DRY_START_CONFIRM_MS);
  1998. return () => clearTimeout(timer);
  1999. }, [dryStartWatch, showToast, t]);
  2000. // Cache tray_now to prevent flickering when undefined values come in
  2001. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2002. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2003. const cachedTrayNow = useRef<number | undefined>(undefined);
  2004. const currentTrayNow = status?.tray_now;
  2005. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2006. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2007. cachedTrayNow.current = currentTrayNow;
  2008. } else if (currentTrayNow === 255) {
  2009. cachedTrayNow.current = undefined;
  2010. }
  2011. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2012. ? currentTrayNow
  2013. : cachedTrayNow.current;
  2014. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2015. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2016. // expectedTray = the slot the firmware now expects filament in
  2017. // previousTray = the slot that ran out
  2018. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2019. // so these are often different — the graphic highlights the expected one.
  2020. const expectedTray = status?.expected_tray ?? null;
  2021. const previousTray = status?.previous_tray ?? null;
  2022. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2023. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2024. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2025. if (globalId === null) return null;
  2026. if (globalId === 254) return t('printers.expectedSlot.external');
  2027. if (globalId >= 128 && globalId <= 135) {
  2028. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2029. }
  2030. const amsId = Math.floor(globalId / 4);
  2031. const slot = globalId % 4;
  2032. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2033. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2034. };
  2035. const runoutGuidance = status?.state === 'PAUSE'
  2036. ? {
  2037. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2038. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2039. }
  2040. : null;
  2041. // Fetch smart plug for this printer
  2042. const { data: smartPlug } = useQuery({
  2043. queryKey: ['smartPlugByPrinter', printer.id],
  2044. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2045. });
  2046. // Fetch script plugs for this printer (for multi-device control)
  2047. const { data: scriptPlugs } = useQuery({
  2048. queryKey: ['scriptPlugsByPrinter', printer.id],
  2049. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2050. });
  2051. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2052. const { data: plugStatus } = useQuery({
  2053. queryKey: ['smartPlugStatus', smartPlug?.id],
  2054. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2055. enabled: !!smartPlug,
  2056. refetchInterval: 10000, // 10 seconds for real-time power display
  2057. });
  2058. // Fetch queue count for this printer
  2059. const { data: queueItems } = useQuery({
  2060. queryKey: ['queue', printer.id, 'pending'],
  2061. queryFn: () => api.getQueue(printer.id, 'pending'),
  2062. });
  2063. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2064. // so the badge only shows on printers that can actually run the queued jobs.
  2065. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2066. const queueCount = useMemo(() => {
  2067. if (!queueItems?.length) return 0;
  2068. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2069. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2070. // Fetch currently printing queue item to show who started it (Issue #206)
  2071. const { data: printingQueueItems } = useQuery({
  2072. queryKey: ['queue', printer.id, 'printing'],
  2073. queryFn: () => api.getQueue(printer.id, 'printing'),
  2074. enabled: status?.state === 'RUNNING',
  2075. });
  2076. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2077. const { data: reprintUser } = useQuery({
  2078. queryKey: ['currentPrintUser', printer.id],
  2079. queryFn: () => api.getCurrentPrintUser(printer.id),
  2080. enabled: status?.state === 'RUNNING',
  2081. });
  2082. // Combine both sources: queue item user takes precedence, then reprint user
  2083. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2084. // Fetch last completed print for this printer
  2085. const { data: lastPrints } = useQuery({
  2086. queryKey: ['archives', printer.id, 'last'],
  2087. queryFn: () => api.getArchives(printer.id, 1, 0),
  2088. enabled: status?.connected && status?.state !== 'RUNNING',
  2089. });
  2090. const lastPrint = lastPrints?.[0];
  2091. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2092. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2093. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2094. const activePrintName = status?.current_print && isPrintingOrPaused
  2095. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2096. : null;
  2097. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2098. useEffect(() => {
  2099. if (activePrintName) {
  2100. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2101. } else if (!needsPlateClear) {
  2102. setRetainedPrintJob(null);
  2103. }
  2104. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2105. const plateStatus = (() => {
  2106. if (!requirePlateClear || !status?.connected) return null;
  2107. if (isPrintingOrPaused) {
  2108. return {
  2109. label: t('printers.plateStatus.inUse'),
  2110. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2111. };
  2112. }
  2113. if (status.awaiting_plate_clear) {
  2114. return {
  2115. label: t('printers.plateStatus.notCleared'),
  2116. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2117. };
  2118. }
  2119. return {
  2120. label: t('printers.plateStatus.cleared'),
  2121. className: 'bg-status-ok/20 text-status-ok',
  2122. };
  2123. })();
  2124. const plateStatusPill = plateStatus ? (
  2125. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2126. {plateStatus.label}
  2127. </span>
  2128. ) : null;
  2129. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2130. const shouldHide = hideIfDisconnected && isConnected === false;
  2131. const deleteMutation = useMutation({
  2132. mutationFn: (options: { deleteArchives: boolean }) =>
  2133. api.deletePrinter(printer.id, options.deleteArchives),
  2134. onSuccess: () => {
  2135. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2136. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2137. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2138. },
  2139. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2140. });
  2141. const connectMutation = useMutation({
  2142. mutationFn: () => api.connectPrinter(printer.id),
  2143. onSuccess: () => {
  2144. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2145. },
  2146. });
  2147. const forceRefreshMutation = useMutation({
  2148. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2149. onSuccess: () => {
  2150. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2151. showToast(t('printers.forceRefreshSuccess'), 'success');
  2152. },
  2153. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2154. });
  2155. const unlinkSpoolMutation = useMutation({
  2156. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2157. onSuccess: (result) => {
  2158. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2159. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2160. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2161. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2162. },
  2163. onError: (error: Error) => {
  2164. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2165. },
  2166. });
  2167. // AMS drying mutations
  2168. const startDryingMutation = useMutation({
  2169. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2170. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2171. onSuccess: (_data, { amsId }) => {
  2172. setDryingPopoverAmsId(null);
  2173. setDryStartWatch({ amsId });
  2174. // "Command sent", not "drying started" — at this point the printer has only
  2175. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2176. // the cycle is genuinely live; the watcher below covers the case where it
  2177. // never appears.
  2178. showToast(t('printers.drying.toastCommandSent'), 'success');
  2179. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2180. },
  2181. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2182. });
  2183. const stopDryingMutation = useMutation({
  2184. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2185. onSuccess: () => {
  2186. setDryStartWatch(null);
  2187. showToast(t('printers.drying.toastStopped'), 'success');
  2188. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2189. },
  2190. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2191. });
  2192. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2193. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2194. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2195. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2196. // showing the old backup state until the user reopens it.
  2197. const setAmsBackupMutation = useMutation({
  2198. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2199. onSuccess: (_data, enabled) => {
  2200. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2201. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2202. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2203. },
  2204. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2205. });
  2206. // Smart plug control mutations
  2207. const powerControlMutation = useMutation({
  2208. mutationFn: (action: 'on' | 'off') =>
  2209. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2210. onSuccess: () => {
  2211. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2212. },
  2213. });
  2214. const toggleAutoOffMutation = useMutation({
  2215. mutationFn: (enabled: boolean) =>
  2216. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2217. onSuccess: () => {
  2218. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2219. // Also invalidate the smart-plugs list to keep Settings page in sync
  2220. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2221. },
  2222. });
  2223. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2224. const runScriptMutation = useMutation({
  2225. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2226. onSuccess: () => {
  2227. showToast(t('printers.toast.scriptTriggered'));
  2228. },
  2229. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2230. });
  2231. // Print control mutations
  2232. const stopPrintMutation = useMutation({
  2233. mutationFn: () => api.stopPrint(printer.id),
  2234. onSuccess: () => {
  2235. showToast(t('printers.toast.printStopped'));
  2236. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2237. },
  2238. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2239. });
  2240. const pausePrintMutation = useMutation({
  2241. mutationFn: () => api.pausePrint(printer.id),
  2242. onSuccess: () => {
  2243. showToast(t('printers.toast.printPaused'));
  2244. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2245. },
  2246. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2247. });
  2248. const resumePrintMutation = useMutation({
  2249. mutationFn: () => api.resumePrint(printer.id),
  2250. onSuccess: () => {
  2251. showToast(t('printers.toast.printResumed'));
  2252. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2253. },
  2254. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2255. });
  2256. const clearPlateMutation = useMutation({
  2257. mutationFn: () => api.clearPlate(printer.id),
  2258. onSuccess: () => {
  2259. showToast(t('queue.clearPlateSuccess'));
  2260. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2261. old ? { ...old, awaiting_plate_clear: false } : old
  2262. );
  2263. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2264. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2265. },
  2266. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2267. });
  2268. const nozzleTemperatureMutation = useMutation({
  2269. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2270. api.setNozzleTemperature(printer.id, target, nozzle),
  2271. onSuccess: (result) => {
  2272. setStatusControlMenu(null);
  2273. showToast(result.message);
  2274. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2275. },
  2276. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2277. });
  2278. const bedTemperatureMutation = useMutation({
  2279. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2280. onSuccess: (result) => {
  2281. setStatusControlMenu(null);
  2282. showToast(result.message);
  2283. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2284. },
  2285. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2286. });
  2287. const chamberTemperatureMutation = useMutation({
  2288. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2289. onSuccess: (result) => {
  2290. setStatusControlMenu(null);
  2291. showToast(result.message);
  2292. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2293. },
  2294. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2295. });
  2296. const fanSpeedMutation = useMutation({
  2297. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2298. api.setFanSpeed(printer.id, fan, speed),
  2299. onMutate: async ({ fan, speed }) => {
  2300. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2301. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2302. const fanField = {
  2303. part: 'cooling_fan_speed',
  2304. aux: 'big_fan1_speed',
  2305. aux2: 'left_aux_fan_speed',
  2306. chamber: 'big_fan2_speed',
  2307. }[fan];
  2308. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2309. old ? { ...old, [fanField]: speed } : old
  2310. );
  2311. return { previousStatus };
  2312. },
  2313. onSuccess: (result) => {
  2314. setStatusControlMenu(null);
  2315. showToast(result.message);
  2316. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2317. },
  2318. onError: (error: Error, _variables, context) => {
  2319. if (context?.previousStatus) {
  2320. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2321. }
  2322. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2323. },
  2324. });
  2325. const selectExtruderMutation = useMutation({
  2326. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2327. onMutate: async (extruder) => {
  2328. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2329. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2330. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2331. old ? { ...old, active_extruder: extruder } : old
  2332. );
  2333. return { previousStatus };
  2334. },
  2335. onSuccess: (result) => {
  2336. setStatusControlMenu(null);
  2337. showToast(result.message);
  2338. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2339. },
  2340. onError: (error: Error, _extruder, context) => {
  2341. if (context?.previousStatus) {
  2342. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2343. }
  2344. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2345. },
  2346. });
  2347. // Chamber light mutation with optimistic update
  2348. const chamberLightMutation = useMutation({
  2349. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2350. onMutate: async (on) => {
  2351. // Cancel any outgoing refetches
  2352. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2353. // Snapshot the previous value
  2354. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2355. // Optimistically update
  2356. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2357. ...old,
  2358. chamber_light: on,
  2359. }));
  2360. return { previousStatus };
  2361. },
  2362. onSuccess: (_, on) => {
  2363. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2364. },
  2365. onError: (error: Error, _, context) => {
  2366. // Rollback on error
  2367. if (context?.previousStatus) {
  2368. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2369. }
  2370. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2371. },
  2372. });
  2373. // Print speed mutation with optimistic update
  2374. const printSpeedMutation = useMutation({
  2375. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2376. onMutate: async (mode) => {
  2377. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2378. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2379. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2380. ...old,
  2381. speed_level: mode,
  2382. }));
  2383. return { previousStatus };
  2384. },
  2385. onError: (error: Error, _, context) => {
  2386. if (context?.previousStatus) {
  2387. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2388. }
  2389. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2390. },
  2391. });
  2392. const airductMutation = useMutation({
  2393. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2394. onMutate: async (mode) => {
  2395. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2396. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2397. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2398. ...old,
  2399. airduct_mode: mode === 'cooling' ? 0 : 1,
  2400. }));
  2401. return { previousStatus };
  2402. },
  2403. onError: (error: Error, _, context) => {
  2404. if (context?.previousStatus) {
  2405. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2406. }
  2407. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2408. },
  2409. });
  2410. const bedJogMutation = useMutation({
  2411. mutationFn: ({ distance }: { distance: number }) =>
  2412. api.bedJog(printer.id, distance),
  2413. onError: (error: Error) =>
  2414. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2415. });
  2416. const xyJogMutation = useMutation({
  2417. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2418. api.xyJog(printer.id, x, y),
  2419. onError: (error: Error) =>
  2420. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2421. });
  2422. const extruderJogMutation = useMutation({
  2423. mutationFn: (distance: number) =>
  2424. api.extruderJog(printer.id, distance),
  2425. onError: (error: Error) =>
  2426. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2427. });
  2428. const homeAxesMutation = useMutation({
  2429. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2430. onSuccess: () => {
  2431. showToast(t('printers.bedJog.homingStarted'));
  2432. },
  2433. onError: (error: Error) =>
  2434. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2435. });
  2436. // Plate detection setting mutation
  2437. const plateDetectionMutation = useMutation({
  2438. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2439. onSuccess: () => {
  2440. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2441. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2442. },
  2443. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2444. });
  2445. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2446. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2447. // metrics, and the print picker — so flipping this flag puts the printer
  2448. // out of service across every consumer in one place. Used from the
  2449. // overflow menu and EditPrinterModal.
  2450. const maintenanceMutation = useMutation({
  2451. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2452. onSuccess: (_data, isActive) => {
  2453. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2454. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2455. showToast(
  2456. isActive
  2457. ? t('printers.maintenance.toastExited', { name: printer.name })
  2458. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2459. 'success',
  2460. );
  2461. },
  2462. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2463. });
  2464. // Confirm before entering maintenance on a printing printer (entering mode
  2465. // disconnects MQTT, which stops progress tracking + completion notifications
  2466. // for the in-flight job).
  2467. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2468. const handleEnterMaintenance = () => {
  2469. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2470. setConfirmMaintenanceEnter(true);
  2471. } else {
  2472. maintenanceMutation.mutate(false);
  2473. }
  2474. };
  2475. // Query for printable objects (for skip functionality)
  2476. // Fetch when printing with 2+ objects OR when modal is open
  2477. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2478. const { data: objectsData } = useQuery({
  2479. queryKey: ['printableObjects', printer.id],
  2480. queryFn: () => api.getPrintableObjects(printer.id),
  2481. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2482. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2483. });
  2484. // State for tracking which AMS slot is being refreshed
  2485. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2486. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2487. const seenBusyStateRef = useRef<boolean>(false);
  2488. // Fallback timeout ref
  2489. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2490. // Minimum display time passed
  2491. const minTimePassedRef = useRef<boolean>(false);
  2492. // AMS slot refresh mutation
  2493. const refreshAmsSlotMutation = useMutation({
  2494. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2495. api.refreshAmsSlot(printer.id, amsId, slotId),
  2496. onMutate: ({ amsId, slotId }) => {
  2497. // Clear any existing timeout
  2498. if (refreshTimeoutRef.current) {
  2499. clearTimeout(refreshTimeoutRef.current);
  2500. }
  2501. // Reset state
  2502. seenBusyStateRef.current = false;
  2503. minTimePassedRef.current = false;
  2504. setRefreshingSlot({ amsId, slotId });
  2505. // Minimum display time (2 seconds)
  2506. setTimeout(() => {
  2507. minTimePassedRef.current = true;
  2508. }, 2000);
  2509. // Fallback timeout (30 seconds max)
  2510. refreshTimeoutRef.current = setTimeout(() => {
  2511. setRefreshingSlot(null);
  2512. }, 30000);
  2513. },
  2514. onSuccess: (data) => {
  2515. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2516. },
  2517. onError: (error: Error) => {
  2518. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2519. if (refreshTimeoutRef.current) {
  2520. clearTimeout(refreshTimeoutRef.current);
  2521. }
  2522. setRefreshingSlot(null);
  2523. },
  2524. });
  2525. // AMS load/unload mutations (#891)
  2526. const loadAmsTrayMutation = useMutation({
  2527. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2528. onSuccess: (data) => {
  2529. showToast(data.message || t('printers.toast.loadInitiated'));
  2530. },
  2531. onError: (error: Error) => {
  2532. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2533. },
  2534. });
  2535. const unloadAmsMutation = useMutation({
  2536. mutationFn: () => api.unloadAms(printer.id),
  2537. onSuccess: (data) => {
  2538. showToast(data.message || t('printers.toast.unloadInitiated'));
  2539. },
  2540. onError: (error: Error) => {
  2541. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2542. },
  2543. });
  2544. // Plate references state
  2545. const [plateReferences, setPlateReferences] = useState<{
  2546. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2547. max_references: number;
  2548. } | null>(null);
  2549. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2550. // Fetch plate references
  2551. const fetchPlateReferences = async () => {
  2552. try {
  2553. const data = await api.getPlateReferences(printer.id);
  2554. setPlateReferences(data);
  2555. } catch {
  2556. // Ignore errors - references will show as empty
  2557. }
  2558. };
  2559. // Toggle plate detection enabled/disabled
  2560. const handleTogglePlateDetection = () => {
  2561. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2562. };
  2563. // Open plate detection management modal (for calibration/references)
  2564. const handleOpenPlateManagement = async () => {
  2565. setIsCheckingPlate(true);
  2566. setPlateCheckResult(null);
  2567. // Auto-turn on light if it's off
  2568. const lightWasOff = status?.chamber_light === false;
  2569. setPlateCheckLightWasOff(lightWasOff);
  2570. if (lightWasOff) {
  2571. await api.setChamberLight(printer.id, true);
  2572. // Wait for light to physically turn on and camera to adjust exposure
  2573. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2574. await new Promise(resolve => setTimeout(resolve, 2500));
  2575. }
  2576. try {
  2577. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2578. setPlateCheckResult(result);
  2579. fetchPlateReferences();
  2580. } catch (error) {
  2581. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2582. // Restore light if check failed
  2583. if (lightWasOff) {
  2584. await api.setChamberLight(printer.id, false);
  2585. setPlateCheckLightWasOff(false);
  2586. }
  2587. } finally {
  2588. setIsCheckingPlate(false);
  2589. }
  2590. };
  2591. // Close plate check modal and restore light state
  2592. const closePlateCheckModal = useCallback(async () => {
  2593. setPlateCheckResult(null);
  2594. // Restore light to original state if we turned it on
  2595. if (plateCheckLightWasOff) {
  2596. await api.setChamberLight(printer.id, false);
  2597. setPlateCheckLightWasOff(false);
  2598. }
  2599. }, [plateCheckLightWasOff, printer.id]);
  2600. // Calibrate plate detection handler
  2601. const handleCalibratePlate = async (label?: string) => {
  2602. setIsCalibrating(true);
  2603. try {
  2604. const result = await api.calibratePlateDetection(printer.id, { label });
  2605. if (result.success) {
  2606. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2607. // Refresh references and re-check
  2608. fetchPlateReferences();
  2609. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2610. setPlateCheckResult(checkResult);
  2611. } else {
  2612. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2613. }
  2614. } catch (error) {
  2615. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2616. } finally {
  2617. setIsCalibrating(false);
  2618. }
  2619. };
  2620. // Update reference label
  2621. const handleUpdateRefLabel = async (index: number, label: string) => {
  2622. try {
  2623. await api.updatePlateReferenceLabel(printer.id, index, label);
  2624. setEditingRefLabel(null);
  2625. fetchPlateReferences();
  2626. } catch (error) {
  2627. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2628. }
  2629. };
  2630. // Delete reference
  2631. const handleDeleteRef = async (index: number) => {
  2632. try {
  2633. await api.deletePlateReference(printer.id, index);
  2634. showToast(t('printers.toast.referenceDeleted'), 'success');
  2635. fetchPlateReferences();
  2636. // Re-check to update counts
  2637. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2638. setPlateCheckResult(checkResult);
  2639. } catch (error) {
  2640. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2641. }
  2642. };
  2643. // Save ROI settings
  2644. const handleSaveRoi = async () => {
  2645. if (!editingRoi) return;
  2646. setIsSavingRoi(true);
  2647. try {
  2648. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2649. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2650. setEditingRoi(null);
  2651. // Re-check to see new ROI in action
  2652. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2653. setPlateCheckResult(checkResult);
  2654. } catch (error) {
  2655. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2656. } finally {
  2657. setIsSavingRoi(false);
  2658. }
  2659. };
  2660. // Close plate check modal on Escape key
  2661. useEffect(() => {
  2662. const handleEscape = (e: KeyboardEvent) => {
  2663. if (e.key === 'Escape' && plateCheckResult) {
  2664. closePlateCheckModal();
  2665. }
  2666. };
  2667. window.addEventListener('keydown', handleEscape);
  2668. return () => window.removeEventListener('keydown', handleEscape);
  2669. }, [plateCheckResult, closePlateCheckModal]);
  2670. // Watch ams_status_main to detect when RFID read completes
  2671. // ams_status_main: 0=idle, 2=rfid_identifying
  2672. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2673. useEffect(() => {
  2674. if (!refreshingSlot) return;
  2675. const amsStatus = status?.ams_status_main ?? 0;
  2676. // Track when we see non-idle state (printer is working)
  2677. if (amsStatus !== 0) {
  2678. seenBusyStateRef.current = true;
  2679. // Cancel any deferred clear since we're back to busy
  2680. if (deferredClearRef.current) {
  2681. clearTimeout(deferredClearRef.current);
  2682. deferredClearRef.current = null;
  2683. }
  2684. }
  2685. // When we've seen busy and now idle, clear (with min time check)
  2686. if (seenBusyStateRef.current && amsStatus === 0) {
  2687. if (minTimePassedRef.current) {
  2688. // Min time passed - clear now
  2689. if (refreshTimeoutRef.current) {
  2690. clearTimeout(refreshTimeoutRef.current);
  2691. }
  2692. setRefreshingSlot(null);
  2693. } else {
  2694. // Schedule clear after min time (2 seconds from start)
  2695. if (!deferredClearRef.current) {
  2696. deferredClearRef.current = setTimeout(() => {
  2697. if (refreshTimeoutRef.current) {
  2698. clearTimeout(refreshTimeoutRef.current);
  2699. }
  2700. setRefreshingSlot(null);
  2701. }, 2000);
  2702. }
  2703. }
  2704. }
  2705. return () => {
  2706. if (deferredClearRef.current) {
  2707. clearTimeout(deferredClearRef.current);
  2708. }
  2709. };
  2710. }, [status?.ams_status_main, refreshingSlot]);
  2711. useEffect(() => {
  2712. if (!showMenu) return;
  2713. const handleClickOutside = (event: MouseEvent) => {
  2714. const target = event.target as Node;
  2715. if (!printerActionsMenuRef.current?.contains(target)) {
  2716. setShowMenu(false);
  2717. }
  2718. };
  2719. document.addEventListener('mousedown', handleClickOutside);
  2720. return () => document.removeEventListener('mousedown', handleClickOutside);
  2721. }, [showMenu]);
  2722. if (shouldHide) {
  2723. return null;
  2724. }
  2725. // Size-based styling helpers
  2726. const getImageSize = () => {
  2727. switch (cardSize) {
  2728. case 1: return 'w-10 h-10';
  2729. case 2: return 'w-14 h-14';
  2730. case 3: return 'w-16 h-16';
  2731. case 4: return 'w-20 h-20';
  2732. default: return 'w-14 h-14';
  2733. }
  2734. };
  2735. const getTitleSize = () => {
  2736. switch (cardSize) {
  2737. case 1: return 'text-base truncate';
  2738. case 2: return 'text-lg';
  2739. case 3: return 'text-xl';
  2740. case 4: return 'text-2xl';
  2741. default: return 'text-lg';
  2742. }
  2743. };
  2744. const getSpacing = () => {
  2745. switch (cardSize) {
  2746. case 1: return 'mb-2';
  2747. case 2: return 'mb-4';
  2748. case 3: return 'mb-5';
  2749. case 4: return 'mb-6';
  2750. default: return 'mb-4';
  2751. }
  2752. };
  2753. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2754. const handleCardDragEnter = (e: React.DragEvent) => {
  2755. e.preventDefault();
  2756. dragCounterRef.current++;
  2757. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2758. };
  2759. const handleCardDragOver = (e: React.DragEvent) => {
  2760. e.preventDefault();
  2761. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2762. };
  2763. const handleCardDragLeave = (e: React.DragEvent) => {
  2764. e.preventDefault();
  2765. dragCounterRef.current--;
  2766. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2767. };
  2768. const handleCardDrop = async (e: React.DragEvent) => {
  2769. e.preventDefault();
  2770. dragCounterRef.current = 0;
  2771. setIsDraggingFile(false);
  2772. if (!canDrop) return;
  2773. const droppedFiles = Array.from(e.dataTransfer.files);
  2774. const file = droppedFiles[0];
  2775. if (!file) return;
  2776. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2777. const lower = file.name.toLowerCase();
  2778. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2779. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2780. return;
  2781. }
  2782. setIsDropUploading(true);
  2783. try {
  2784. const result = await api.uploadLibraryFile(file, null);
  2785. // Check printer compatibility if sliced_for_model is available in metadata
  2786. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2787. const printerModel = mapModelCode(printer.model);
  2788. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2789. await api.deleteLibraryFile(result.id).catch(() => {});
  2790. showToast(
  2791. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2792. 'error'
  2793. );
  2794. return;
  2795. }
  2796. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2797. } catch {
  2798. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2799. } finally {
  2800. setIsDropUploading(false);
  2801. }
  2802. };
  2803. const handleCardClick = (e: React.MouseEvent) => {
  2804. if (viewMode !== 'compact' || selectionMode) return;
  2805. const target = e.target as HTMLElement;
  2806. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2807. onOpenCompactCard?.(printer.id);
  2808. };
  2809. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2810. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2811. const renderAmsSlotActions = ({
  2812. amsId,
  2813. slotId,
  2814. loadTrayId,
  2815. isRefreshing,
  2816. includeRfid = true,
  2817. }: {
  2818. amsId: number;
  2819. slotId: number;
  2820. loadTrayId: number;
  2821. isRefreshing?: boolean;
  2822. includeRfid?: boolean;
  2823. }) => {
  2824. const printerBusy = status?.state === 'RUNNING';
  2825. return (
  2826. <>
  2827. {includeRfid && (
  2828. <button
  2829. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2830. hasPermission('printers:ams_rfid')
  2831. ? 'text-white hover:bg-bambu-dark-tertiary'
  2832. : 'text-bambu-gray/50 cursor-not-allowed'
  2833. }`}
  2834. onClick={(e) => {
  2835. e.stopPropagation();
  2836. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2837. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2838. }}
  2839. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2840. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2841. >
  2842. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2843. {t('printers.rfid.reread')}
  2844. </button>
  2845. )}
  2846. <button
  2847. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2848. hasPermission('printers:control')
  2849. ? 'text-white hover:bg-bambu-dark-tertiary'
  2850. : 'text-bambu-gray/50 cursor-not-allowed'
  2851. }`}
  2852. onClick={(e) => {
  2853. e.stopPropagation();
  2854. if (printerBusy || !hasPermission('printers:control')) return;
  2855. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2856. }}
  2857. disabled={printerBusy || !hasPermission('printers:control')}
  2858. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2859. >
  2860. <LogIn className="w-3 h-3" />
  2861. {t('printers.ams.load')}
  2862. </button>
  2863. <button
  2864. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2865. hasPermission('printers:control')
  2866. ? 'text-white hover:bg-bambu-dark-tertiary'
  2867. : 'text-bambu-gray/50 cursor-not-allowed'
  2868. }`}
  2869. onClick={(e) => {
  2870. e.stopPropagation();
  2871. if (printerBusy || !hasPermission('printers:control')) return;
  2872. unloadAmsMutation.mutate();
  2873. }}
  2874. disabled={printerBusy || !hasPermission('printers:control')}
  2875. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2876. >
  2877. <LogOut className="w-3 h-3" />
  2878. {t('printers.ams.unload')}
  2879. </button>
  2880. </>
  2881. );
  2882. };
  2883. const printerActionsMenu = (
  2884. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2885. <Button
  2886. variant="secondary"
  2887. size="sm"
  2888. onClick={() => setShowMenu(!showMenu)}
  2889. title={t('common.more', 'More')}
  2890. className={footerIconButtonClass}
  2891. >
  2892. <MoreVertical className="w-4 h-4" />
  2893. </Button>
  2894. {showMenu && (
  2895. <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">
  2896. <button
  2897. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2898. hasPermission('printers:update')
  2899. ? 'hover:bg-bambu-dark-tertiary'
  2900. : 'opacity-50 cursor-not-allowed'
  2901. }`}
  2902. onClick={() => {
  2903. if (!hasPermission('printers:update')) return;
  2904. setShowEditModal(true);
  2905. setShowMenu(false);
  2906. }}
  2907. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2908. >
  2909. <Pencil className="w-4 h-4" />
  2910. {t('common.edit')}
  2911. </button>
  2912. <button
  2913. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2914. onClick={() => {
  2915. setShowPrinterInfo(true);
  2916. setShowMenu(false);
  2917. }}
  2918. >
  2919. <Info className="w-4 h-4" />
  2920. {t('printers.printerInformation')}
  2921. </button>
  2922. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2923. <button
  2924. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2925. hasPermission('printers:update')
  2926. ? 'hover:bg-bambu-dark-tertiary'
  2927. : 'opacity-50 cursor-not-allowed'
  2928. }`}
  2929. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2930. onClick={() => {
  2931. if (!hasPermission('printers:update')) return;
  2932. setShowMenu(false);
  2933. if (printer.is_active !== false) {
  2934. handleEnterMaintenance();
  2935. } else {
  2936. maintenanceMutation.mutate(true);
  2937. }
  2938. }}
  2939. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2940. >
  2941. <Wrench className="w-4 h-4" />
  2942. {printer.is_active !== false
  2943. ? t('printers.maintenance.menuEnter')
  2944. : t('printers.maintenance.menuExit')}
  2945. </button>
  2946. <button
  2947. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2948. onClick={() => {
  2949. connectMutation.mutate();
  2950. setShowMenu(false);
  2951. }}
  2952. >
  2953. <RefreshCw className="w-4 h-4" />
  2954. {t('printers.reconnect')}
  2955. </button>
  2956. <button
  2957. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2958. disabled={forceRefreshMutation.isPending}
  2959. onClick={() => {
  2960. forceRefreshMutation.mutate();
  2961. setShowMenu(false);
  2962. }}
  2963. >
  2964. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2965. {t('printers.forceRefresh')}
  2966. </button>
  2967. <button
  2968. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2969. onClick={() => {
  2970. setShowMQTTDebug(true);
  2971. setShowMenu(false);
  2972. }}
  2973. >
  2974. <Terminal className="w-4 h-4" />
  2975. {t('printers.mqttDebug')}
  2976. </button>
  2977. <button
  2978. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2979. onClick={() => {
  2980. setShowDiagnostic(true);
  2981. setShowMenu(false);
  2982. }}
  2983. >
  2984. <Stethoscope className="w-4 h-4" />
  2985. {t('diagnostic.runButton')}
  2986. </button>
  2987. <button
  2988. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2989. hasPermission('printers:delete')
  2990. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  2991. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  2992. }`}
  2993. onClick={() => {
  2994. if (!hasPermission('printers:delete')) return;
  2995. setShowDeleteConfirm(true);
  2996. setShowMenu(false);
  2997. }}
  2998. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2999. >
  3000. <Trash2 className="w-4 h-4" />
  3001. {t('common.delete')}
  3002. </button>
  3003. </div>
  3004. )}
  3005. </div>
  3006. );
  3007. return (
  3008. <Card
  3009. id={`printer-card-${printer.id}`}
  3010. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3011. onClick={handleCardClick}
  3012. onDragEnter={handleCardDragEnter}
  3013. onDragOver={handleCardDragOver}
  3014. onDragLeave={handleCardDragLeave}
  3015. onDrop={handleCardDrop}
  3016. >
  3017. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3018. {selectionMode && (
  3019. <div
  3020. className="absolute inset-0 z-20 flex items-start p-2"
  3021. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3022. >
  3023. {isSelected ? (
  3024. <CheckSquare className="w-5 h-5 text-bambu-green" />
  3025. ) : (
  3026. <Square className="w-5 h-5 text-bambu-gray" />
  3027. )}
  3028. </div>
  3029. )}
  3030. {/* Drop zone overlay */}
  3031. {(isDraggingFile || isDropUploading) && (
  3032. <div
  3033. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3034. isDropUploading
  3035. ? 'bg-bambu-green/10 border-bambu-green/50'
  3036. : canDrop
  3037. ? 'bg-bambu-green/10 border-bambu-green'
  3038. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3039. }`}
  3040. >
  3041. <div className="text-center">
  3042. {isDropUploading ? (
  3043. <>
  3044. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3045. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3046. </>
  3047. ) : canDrop ? (
  3048. <>
  3049. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3050. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  3051. </>
  3052. ) : (
  3053. <>
  3054. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3055. <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  3056. </>
  3057. )}
  3058. </div>
  3059. </div>
  3060. )}
  3061. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3062. {/* Header */}
  3063. <div className={getSpacing()}>
  3064. {/* Top row: Image, Name, Menu */}
  3065. <div className="flex items-start justify-between gap-2">
  3066. <div className="flex items-center gap-3 min-w-0 flex-1">
  3067. {/* Printer Model Image */}
  3068. <img
  3069. src={getPrinterImage(printer.model)}
  3070. alt={printer.model || t('common.printer')}
  3071. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3072. />
  3073. <div className="min-w-0 flex-1">
  3074. <div className="flex items-center justify-between gap-2">
  3075. <div className="flex min-w-0 items-center gap-2">
  3076. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3077. {/* Connection indicator dot for compact mode */}
  3078. {viewMode === 'compact' && (() => {
  3079. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3080. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3081. const hasWarning = hmsErrors.length > 0;
  3082. const pipColor = !status?.connected
  3083. ? 'bg-status-error'
  3084. : hasSevere
  3085. ? 'bg-status-error'
  3086. : hasWarning
  3087. ? 'bg-status-warning'
  3088. : 'bg-status-ok';
  3089. const pipTitle = !status?.connected
  3090. ? t('printers.connection.offline')
  3091. : hasWarning
  3092. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3093. : t('printers.connection.connected');
  3094. return (
  3095. <div
  3096. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  3097. title={pipTitle}
  3098. />
  3099. );
  3100. })()}
  3101. </div>
  3102. {viewMode === 'compact' && showClearPlateButton && (
  3103. <button
  3104. type="button"
  3105. onClick={() => clearPlateMutation.mutate()}
  3106. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3107. aria-label={t('printers.plateStatus.markCleared')}
  3108. 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"
  3109. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3110. >
  3111. {clearPlateMutation.isPending ? (
  3112. <Loader2 className="w-3 h-3 animate-spin" />
  3113. ) : (
  3114. <PlateClearedIcon className="w-3 h-3" />
  3115. )}
  3116. </button>
  3117. )}
  3118. </div>
  3119. <p className="text-sm text-bambu-gray">
  3120. {printer.model || 'Unknown Model'}
  3121. {/* Nozzle Info - only in expanded */}
  3122. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3123. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3124. • {status.nozzles[0].nozzle_diameter}mm
  3125. </span>
  3126. )}
  3127. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3128. <span className="ml-2 text-bambu-gray">
  3129. <Clock className="w-3 h-3 inline-block mr-1" />
  3130. {Math.round(maintenanceInfo.total_print_hours)}h
  3131. </span>
  3132. )}
  3133. </p>
  3134. </div>
  3135. </div>
  3136. </div>
  3137. {/* Badges row - only in expanded mode */}
  3138. {viewMode === 'expanded' && (
  3139. <div className="mt-2">
  3140. <div className="flex flex-wrap items-center gap-2">
  3141. {/* Connection status badge (or Maintenance pill when out of service).
  3142. Defensive: only swap when is_active is EXPLICITLY false. An
  3143. undefined / missing field defaults to "active" so the regular
  3144. pill renders — matches the backend default and prevents test
  3145. fixtures (or stale clients) from accidentally tripping the
  3146. maintenance UI. */}
  3147. {printer.is_active === false ? (
  3148. <span
  3149. 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"
  3150. title={t('printers.maintenance.subtitle')}
  3151. >
  3152. <Wrench className="w-3 h-3" />
  3153. {t('printers.maintenance.pillLabel')}
  3154. </span>
  3155. ) : (
  3156. <span
  3157. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3158. status?.connected
  3159. ? 'bg-status-ok/20 text-status-ok'
  3160. : 'bg-status-error/20 text-status-error'
  3161. }`}
  3162. >
  3163. {status?.connected ? (
  3164. <Link className="w-3 h-3" />
  3165. ) : (
  3166. <Unlink className="w-3 h-3" />
  3167. )}
  3168. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3169. </span>
  3170. )}
  3171. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3172. {printer.is_active !== false && !status?.connected && (
  3173. <button
  3174. onClick={() => setShowDiagnostic(true)}
  3175. 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"
  3176. title={t('diagnostic.runButton')}
  3177. >
  3178. <Stethoscope className="w-3 h-3" />
  3179. {t('diagnostic.runButton')}
  3180. </button>
  3181. )}
  3182. {/* Network connection indicator */}
  3183. {status?.connected && status?.wired_network && (
  3184. <span
  3185. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3186. title={t('printers.connection.ethernet', 'Ethernet')}
  3187. >
  3188. <Cable className="w-3 h-3" />
  3189. {t('printers.connection.ethernet', 'Ethernet')}
  3190. </span>
  3191. )}
  3192. {/* WiFi signal indicator */}
  3193. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3194. <span
  3195. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3196. wifiSignal >= -50
  3197. ? 'bg-status-ok/20 text-status-ok'
  3198. : wifiSignal >= -60
  3199. ? 'bg-status-ok/20 text-status-ok'
  3200. : wifiSignal >= -70
  3201. ? 'bg-status-warning/20 text-status-warning'
  3202. : wifiSignal >= -80
  3203. ? 'bg-orange-500/20 text-orange-600'
  3204. : 'bg-status-error/20 text-status-error'
  3205. }`}
  3206. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3207. >
  3208. <Signal className="w-3 h-3" />
  3209. {wifiSignal}dBm
  3210. </span>
  3211. )}
  3212. {/* HMS Status Indicator */}
  3213. {status?.connected && (() => {
  3214. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3215. return (
  3216. <button
  3217. onClick={() => setShowHMSModal(true)}
  3218. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3219. knownErrors.length > 0
  3220. ? knownErrors.some(e => e.severity <= 2)
  3221. ? 'bg-status-error/20 text-status-error'
  3222. : 'bg-status-warning/20 text-status-warning'
  3223. : 'bg-status-ok/20 text-status-ok'
  3224. }`}
  3225. title={t('printers.clickToViewHmsErrors')}
  3226. >
  3227. <AlertTriangle className="w-3 h-3" />
  3228. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3229. </button>
  3230. );
  3231. })()}
  3232. {/* AI failure detection badge (#1546) — always shown while detection
  3233. is enabled for this printer, like the other health badges. Gray
  3234. "Idle" outside a monitored print, class-colored during one. */}
  3235. {aiDetectionEnabled && (() => {
  3236. const cls = aiDetection
  3237. ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
  3238. : 'idle';
  3239. const colorClass =
  3240. cls === 'failure'
  3241. ? 'bg-status-error/20 text-status-error'
  3242. : cls === 'warning'
  3243. ? 'bg-status-warning/20 text-status-warning'
  3244. : cls === 'safe'
  3245. ? 'bg-status-ok/20 text-status-ok'
  3246. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3247. return (
  3248. <button
  3249. onClick={() => setShowAiModal(true)}
  3250. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3251. title={
  3252. aiDetection
  3253. ? t('printers.aiDetection.tooltip', {
  3254. status: t(`printers.aiDetection.${cls}`),
  3255. score: aiDetection.score.toFixed(3),
  3256. })
  3257. : t('printers.aiDetection.tooltipIdle')
  3258. }
  3259. >
  3260. <ScanEye className="w-3 h-3" />
  3261. {t(`printers.aiDetection.${cls}`)}
  3262. </button>
  3263. );
  3264. })()}
  3265. {/* Maintenance Status Indicator */}
  3266. {maintenanceInfo && (
  3267. <button
  3268. onClick={() => navigate('/maintenance')}
  3269. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3270. maintenanceInfo.due_count > 0
  3271. ? 'bg-status-error/20 text-status-error'
  3272. : maintenanceInfo.warning_count > 0
  3273. ? 'bg-status-warning/20 text-status-warning'
  3274. : 'bg-status-ok/20 text-status-ok'
  3275. }`}
  3276. title={
  3277. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3278. ? `${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`
  3279. : t('printers.maintenanceUpToDate')
  3280. }
  3281. >
  3282. <Wrench className="w-3 h-3" />
  3283. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3284. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3285. : 'OK'}
  3286. </button>
  3287. )}
  3288. {/* Queue Count Badge */}
  3289. {queueCount > 0 && (
  3290. <button
  3291. onClick={() => navigate('/queue')}
  3292. 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"
  3293. title={t('printers.queue.inQueue', { count: queueCount })}
  3294. >
  3295. <Layers className="w-3 h-3" />
  3296. {queueCount}
  3297. </button>
  3298. )}
  3299. {/* Firmware Version Badge */}
  3300. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3301. <button
  3302. onClick={() => setShowFirmwareModal(true)}
  3303. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3304. firmwareInfo.update_available
  3305. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3306. : 'bg-status-ok/20 text-status-ok'
  3307. }`}
  3308. title={
  3309. firmwareInfo.update_available
  3310. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3311. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3312. }
  3313. >
  3314. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3315. {firmwareInfo.current_version}
  3316. </button>
  3317. ) : status?.firmware_version ? (
  3318. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3319. {status.firmware_version}
  3320. </span>
  3321. ) : null}
  3322. {/* Enclosure Door Badge — models with an actual door sensor.
  3323. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3324. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3325. <span
  3326. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3327. status.door_open
  3328. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3329. : 'bg-status-ok/20 text-status-ok'
  3330. }`}
  3331. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3332. >
  3333. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3334. </span>
  3335. )}
  3336. </div>
  3337. </div>
  3338. )}
  3339. </div>
  3340. {/* Delete Confirmation */}
  3341. {showDeleteConfirm && (
  3342. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3343. <Card className="w-full max-w-md mx-4">
  3344. <CardContent>
  3345. <div className="flex items-start gap-3 mb-4">
  3346. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3347. <AlertTriangle className="w-5 h-5 text-red-600 dark:text-red-400" />
  3348. </div>
  3349. <div>
  3350. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3351. <p className="text-sm text-bambu-gray mt-1">
  3352. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3353. </p>
  3354. </div>
  3355. </div>
  3356. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3357. <label className="flex items-start gap-3 cursor-pointer">
  3358. <input
  3359. type="checkbox"
  3360. checked={deleteArchives}
  3361. onChange={(e) => setDeleteArchives(e.target.checked)}
  3362. className="mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3363. />
  3364. <div>
  3365. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3366. <p className="text-xs text-bambu-gray mt-0.5">
  3367. {deleteArchives
  3368. ? t('printers.confirm.deleteArchivesNote')
  3369. : t('printers.confirm.keepArchivesNote')}
  3370. </p>
  3371. </div>
  3372. </label>
  3373. </div>
  3374. <div className="flex justify-end gap-2">
  3375. <Button
  3376. variant="secondary"
  3377. onClick={() => {
  3378. setShowDeleteConfirm(false);
  3379. setDeleteArchives(true);
  3380. }}
  3381. >
  3382. {t('common.cancel')}
  3383. </Button>
  3384. <Button
  3385. variant="danger"
  3386. onClick={() => {
  3387. deleteMutation.mutate({ deleteArchives });
  3388. setShowDeleteConfirm(false);
  3389. setDeleteArchives(true);
  3390. }}
  3391. >
  3392. Delete
  3393. </Button>
  3394. </div>
  3395. </CardContent>
  3396. </Card>
  3397. </div>
  3398. )}
  3399. {/* Status — see the equivalent defensive `=== false` check on the
  3400. header pill above for why this is not `!printer.is_active`. */}
  3401. {printer.is_active === false ? (
  3402. // Maintenance mode (#1476) — replaces the cover/progress container
  3403. // so the card keeps the same height. Renders for both compact and
  3404. // expanded view modes so the printer stays visible but plainly
  3405. // out-of-service.
  3406. <>
  3407. {viewMode === 'compact' ? (
  3408. <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">
  3409. <Wrench className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  3410. <span className="text-[11px] text-amber-700 dark:text-amber-400 font-medium truncate">
  3411. {t('printers.maintenance.pillLabel')}
  3412. </span>
  3413. </div>
  3414. ) : (
  3415. <>
  3416. <div className="flex items-center gap-2 mb-2">
  3417. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3418. {t('printers.status.title', 'Status')}
  3419. </span>
  3420. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3421. </div>
  3422. <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">
  3423. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3424. <div className="flex-1 min-w-0">
  3425. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3426. {t('printers.maintenance.title')}
  3427. </p>
  3428. <p className="text-xs text-bambu-gray mt-0.5">
  3429. {t('printers.maintenance.subtitle')}
  3430. </p>
  3431. </div>
  3432. <Button
  3433. variant="secondary"
  3434. size="sm"
  3435. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3436. onClick={() => maintenanceMutation.mutate(true)}
  3437. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3438. >
  3439. {t('printers.maintenance.exitButton')}
  3440. </Button>
  3441. </div>
  3442. </>
  3443. )}
  3444. </>
  3445. ) : status?.connected && (
  3446. <>
  3447. {/* Compact: Simple status bar */}
  3448. {viewMode === 'compact' ? (
  3449. (() => {
  3450. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3451. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3452. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3453. ? Math.max(0, Math.min(100, status.progress || 0))
  3454. : showClearPlateButton
  3455. ? 100
  3456. : hasProblem
  3457. ? 100
  3458. : 0;
  3459. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3460. const compactProgressClass = hasProblem
  3461. ? 'bg-status-error'
  3462. : status.state === 'PAUSE'
  3463. ? 'bg-status-warning'
  3464. : 'bg-bambu-green';
  3465. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  3466. const hasCompactLayers =
  3467. isActiveCompactPrint &&
  3468. status.layer_num != null &&
  3469. status.total_layers != null &&
  3470. status.total_layers > 0;
  3471. return (
  3472. <>
  3473. <div className="relative mt-2 flex items-center gap-2">
  3474. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3475. <div
  3476. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3477. style={{ width: `${compactProgress}%` }}
  3478. />
  3479. </div>
  3480. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3481. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3482. </span>
  3483. </div>
  3484. {/* #2674: size S showed only a name, a pip and a progress bar — not
  3485. enough to answer "which printer finishes first", which is what a
  3486. wall-mounted fleet view is for. One line of the metrics the
  3487. expanded card already renders, using the same formatters and the
  3488. same ETA styling so S and M read alike. The row keeps its height
  3489. when idle so cards don't shift as prints start and stop. */}
  3490. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[11px] leading-none text-bambu-gray">
  3491. {hasCompactEta && (
  3492. <>
  3493. <span className="flex shrink-0 items-center gap-1">
  3494. <Clock className="w-3 h-3" />
  3495. {formatDuration(status.remaining_time! * 60)}
  3496. </span>
  3497. <span
  3498. className="shrink-0 font-medium text-bambu-green"
  3499. title={t('printers.estimatedCompletion')}
  3500. >
  3501. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  3502. </span>
  3503. </>
  3504. )}
  3505. {hasCompactLayers && (
  3506. <span className="flex min-w-0 items-center gap-1 truncate">
  3507. <Layers className="w-3 h-3 shrink-0" />
  3508. {status.layer_num}/{status.total_layers}
  3509. </span>
  3510. )}
  3511. </div>
  3512. </>
  3513. );
  3514. })()
  3515. ) : (
  3516. /* Expanded: Full status section */
  3517. <>
  3518. <div className="flex items-center gap-2 mb-2">
  3519. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3520. {t('printers.status.title', 'Status')}
  3521. </span>
  3522. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3523. </div>
  3524. {/* Current Print or Idle Placeholder */}
  3525. {(() => {
  3526. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3527. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3528. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3529. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3530. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3531. return (
  3532. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3533. <button
  3534. onClick={() => setShowSkipObjectsModal(true)}
  3535. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3536. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3537. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3538. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3539. : 'text-bambu-gray/30 cursor-not-allowed'
  3540. }`}
  3541. title={
  3542. !hasPermission('printers:control')
  3543. ? t('printers.permission.noControl')
  3544. : !isActivePrint
  3545. ? t('printers.skipObjects.onlyWhilePrinting')
  3546. : (status.printable_objects_count ?? 0) >= 2
  3547. ? t('printers.skipObjects.tooltip')
  3548. : t('printers.skipObjects.requiresMultiple')
  3549. }
  3550. >
  3551. <SkipObjectsIcon className="w-4 h-4" />
  3552. {objectsData && objectsData.skipped_count > 0 && (
  3553. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full">
  3554. {objectsData.skipped_count}
  3555. </span>
  3556. )}
  3557. </button>
  3558. <div className="flex items-stretch gap-2">
  3559. <CoverImage
  3560. url={coverUrl}
  3561. printName={printName || undefined}
  3562. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3563. />
  3564. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3565. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3566. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3567. {plateStatusPill}
  3568. </div>
  3569. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3570. {printName || t('printers.noActiveJob', 'No active job')}
  3571. </p>
  3572. <div className="flex h-3 items-center gap-2 text-sm">
  3573. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3574. <div
  3575. 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`}
  3576. style={{ width: `${progress}%` }}
  3577. />
  3578. </div>
  3579. <span className={`w-9 shrink-0 pr-1 text-right text-[11px] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  3580. </div>
  3581. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3582. {isActivePrint ? (
  3583. <>
  3584. {status.remaining_time != null && status.remaining_time > 0 && (
  3585. <>
  3586. <span className="flex items-center gap-1">
  3587. <Clock className="w-3 h-3" />
  3588. {formatDuration(status.remaining_time * 60)}
  3589. </span>
  3590. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3591. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3592. </span>
  3593. </>
  3594. )}
  3595. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3596. <span className="flex items-center gap-1">
  3597. <Layers className="w-3 h-3" />
  3598. {status.layer_num}/{status.total_layers}
  3599. </span>
  3600. )}
  3601. {currentPrintUser && (
  3602. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3603. <User className="w-3 h-3" />
  3604. {currentPrintUser}
  3605. </span>
  3606. )}
  3607. </>
  3608. ) : lastPrint ? (
  3609. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3610. Last: {lastPrint.print_name || lastPrint.filename}
  3611. {lastPrint.completed_at && (
  3612. <span className="ml-1 text-bambu-gray/60">
  3613. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3614. </span>
  3615. )}
  3616. </p>
  3617. ) : (
  3618. <span>{t('printers.readyToPrint')}</span>
  3619. )}
  3620. </div>
  3621. </div>
  3622. </div>
  3623. <PrinterQueueWidget
  3624. printerId={printer.id}
  3625. printerModel={printer.model}
  3626. loadedFilamentTypes={loadedFilamentTypes}
  3627. loadedFilaments={loadedFilaments}
  3628. loadedVariants={loadedVariants}
  3629. variant="panelExtension"
  3630. />
  3631. </div>
  3632. );
  3633. })()}
  3634. </>
  3635. )}
  3636. {/* Temperatures */}
  3637. {status.temperatures && viewMode === 'expanded' && (() => {
  3638. // Use actual heater states from MQTT stream
  3639. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3640. const bedHeating = status.temperatures.bed_heating || false;
  3641. const chamberHeating = status.temperatures.chamber_heating || false;
  3642. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3643. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3644. const kinds: HeaterSensorKind[] = ['nozzle'];
  3645. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3646. kinds.push('bed');
  3647. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3648. return kinds;
  3649. })();
  3650. // active_extruder: 0=right, 1=left
  3651. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3652. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3653. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3654. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3655. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3656. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3657. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3658. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3659. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3660. 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 ${
  3661. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3662. }`;
  3663. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3664. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3665. // the widget there is at best dead UI and at worst suggests a
  3666. // control that does nothing. Mirrors the enclosure-door badge
  3667. // gate above.
  3668. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3669. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  3670. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  3671. // show it only when the printer actually reports it (airduct part id 3,
  3672. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  3673. // have a built-in chamber fan that's always present, so they keep the
  3674. // existing model-list gate and the "Chamber Fan" label.
  3675. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  3676. const chamberFanLabel = isExhaustModel
  3677. ? t('printers.fans.exhaust')
  3678. : t('printers.fans.chamber');
  3679. // Composed rather than either/or so both lists stay live for
  3680. // P2S/X2D: the model must have an enclosure fan at all, AND —
  3681. // where that fan is an add-on kit — actually report it. Written
  3682. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  3683. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  3684. // which reads as if removing them were safe.
  3685. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  3686. const fanItems: {
  3687. key: string;
  3688. label: string;
  3689. value: number;
  3690. Icon: typeof Fan;
  3691. activeClass: string;
  3692. }[] = [
  3693. {
  3694. key: 'part',
  3695. label: t('printers.fans.partCooling'),
  3696. value: status.cooling_fan_speed ?? 0,
  3697. Icon: Fan,
  3698. activeClass: 'text-cyan-600 dark:text-cyan-400',
  3699. },
  3700. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  3701. // Only reported (non-null) when the firmware lists airduct part
  3702. // id 10, i.e. when the fan is physically installed. Placed
  3703. // before the right-hand auxiliary fan so the two aux badges read
  3704. // left-to-right in the same order as the physical hardware.
  3705. ...(status.left_aux_fan_speed != null
  3706. ? [
  3707. {
  3708. key: 'aux2',
  3709. label: t('printers.fans.leftAuxiliary'),
  3710. value: status.left_aux_fan_speed,
  3711. Icon: Wind,
  3712. activeClass: 'text-indigo-600 dark:text-indigo-400',
  3713. },
  3714. ]
  3715. : []),
  3716. {
  3717. key: 'aux',
  3718. label: t('printers.fans.auxiliary'),
  3719. value: status.big_fan1_speed ?? 0,
  3720. Icon: Wind,
  3721. activeClass: 'text-blue-600 dark:text-blue-400',
  3722. },
  3723. ...(showChamberFan
  3724. ? [
  3725. {
  3726. key: 'chamber',
  3727. label: chamberFanLabel,
  3728. value: status.big_fan2_speed ?? 0,
  3729. Icon: AirVent,
  3730. activeClass: 'text-green-600 dark:text-green-400',
  3731. },
  3732. ]
  3733. : []),
  3734. ];
  3735. return (
  3736. <>
  3737. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3738. {/* Nozzle temp - combined for dual nozzle */}
  3739. <div
  3740. className={statusControlClass}
  3741. title={statusControlTitle}
  3742. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3743. >
  3744. <button
  3745. type="button"
  3746. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3747. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3748. onClick={(e) => {
  3749. e.stopPropagation();
  3750. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3751. }}
  3752. >
  3753. <LineChartIcon className="w-2.5 h-2.5" />
  3754. </button>
  3755. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3756. {status.temperatures.nozzle_2 !== undefined ? (
  3757. <>
  3758. <p className="text-[9px] text-bambu-gray">L / R</p>
  3759. <p className="text-[11px] text-white">
  3760. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3761. </p>
  3762. </>
  3763. ) : singleNozzleSlot ? (
  3764. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3765. <div className="cursor-default">
  3766. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3767. <p className="text-[11px] text-white">
  3768. {Math.round(status.temperatures.nozzle || 0)}°C
  3769. </p>
  3770. </div>
  3771. </NozzleSlotHoverCard>
  3772. ) : (
  3773. <>
  3774. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3775. <p className="text-[11px] text-white">
  3776. {Math.round(status.temperatures.nozzle || 0)}°C
  3777. </p>
  3778. </>
  3779. )}
  3780. {statusControlMenu === 'nozzle-temp' && (
  3781. isDualNozzle ? (
  3782. <IndicatorControlPopover
  3783. title="Set Nozzle Temperatures"
  3784. widthClass="w-[300px]"
  3785. popoverWidth={300}
  3786. popoverHeight={260}
  3787. isPending={nozzleTemperatureMutation.isPending}
  3788. onClose={() => setStatusControlMenu(null)}
  3789. >
  3790. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3791. <NozzleTemperatureControlBox
  3792. label="Left Temp"
  3793. current={status.temperatures.nozzle}
  3794. target={status.temperatures.nozzle_target}
  3795. isActive={activeNozzle === 'L'}
  3796. isPending={nozzleTemperatureMutation.isPending}
  3797. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3798. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3799. />
  3800. <NozzleTemperatureControlBox
  3801. label="Right Temp"
  3802. current={status.temperatures.nozzle_2}
  3803. target={status.temperatures.nozzle_2_target}
  3804. isActive={activeNozzle === 'R'}
  3805. isPending={nozzleTemperatureMutation.isPending}
  3806. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3807. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3808. />
  3809. </div>
  3810. </IndicatorControlPopover>
  3811. ) : (
  3812. <IndicatorControlPopover
  3813. title="Set Nozzle Temperature"
  3814. unit="°C"
  3815. customMin={0}
  3816. customMax={320}
  3817. isPending={nozzleTemperatureMutation.isPending}
  3818. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3819. onClose={() => setStatusControlMenu(null)}
  3820. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3821. />
  3822. )
  3823. )}
  3824. </div>
  3825. <div
  3826. className={statusControlClass}
  3827. title={statusControlTitle}
  3828. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3829. >
  3830. <button
  3831. type="button"
  3832. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3833. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3834. onClick={(e) => {
  3835. e.stopPropagation();
  3836. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3837. }}
  3838. >
  3839. <LineChartIcon className="w-2.5 h-2.5" />
  3840. </button>
  3841. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3842. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3843. <p className="text-[11px] text-white">
  3844. {Math.round(status.temperatures.bed || 0)}°C
  3845. </p>
  3846. {statusControlMenu === 'bed-temp' && (
  3847. <IndicatorControlPopover
  3848. title="Set Bed Temperature"
  3849. unit="°C"
  3850. customMin={0}
  3851. customMax={140}
  3852. isPending={bedTemperatureMutation.isPending}
  3853. options={buildPresetOptions(bedTempPresets, 'C')}
  3854. onClose={() => setStatusControlMenu(null)}
  3855. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3856. />
  3857. )}
  3858. </div>
  3859. {status.temperatures.chamber !== undefined && (() => {
  3860. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3861. // but can't act on M141, so we keep the card read-only there.
  3862. const hasChamberHeater = status.supports_chamber_heater === true;
  3863. return (
  3864. <div
  3865. className={hasChamberHeater
  3866. ? statusControlClass
  3867. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3868. title={hasChamberHeater ? statusControlTitle : undefined}
  3869. onClick={hasChamberHeater
  3870. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3871. : undefined}
  3872. >
  3873. <button
  3874. type="button"
  3875. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3876. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3877. onClick={(e) => {
  3878. e.stopPropagation();
  3879. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3880. }}
  3881. >
  3882. <LineChartIcon className="w-2.5 h-2.5" />
  3883. </button>
  3884. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3885. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3886. <p className="text-[11px] text-white">
  3887. {Math.round(status.temperatures.chamber || 0)}°C
  3888. </p>
  3889. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3890. <IndicatorControlPopover
  3891. title="Set Chamber Temperature"
  3892. unit="°C"
  3893. customMin={0}
  3894. customMax={MAX_CHAMBER_TEMP_C}
  3895. isPending={chamberTemperatureMutation.isPending}
  3896. options={buildPresetOptions(chamberTempPresets, 'C')}
  3897. onClose={() => setStatusControlMenu(null)}
  3898. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3899. />
  3900. )}
  3901. </div>
  3902. );
  3903. })()}
  3904. {/* Active nozzle indicator for dual-nozzle printers */}
  3905. {isDualNozzle && (
  3906. <DualNozzleHoverCard
  3907. leftSlot={leftNozzleSlot}
  3908. rightSlot={rightNozzleSlot}
  3909. activeNozzle={activeNozzle}
  3910. filamentInfo={filamentInfo}
  3911. >
  3912. <div
  3913. 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 ${
  3914. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3915. }`}
  3916. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3917. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3918. >
  3919. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-600 dark:text-amber-400" />
  3920. <div className="flex items-center gap-2">
  3921. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3922. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3923. </span>
  3924. <span className="text-[9px] text-bambu-gray/40">·</span>
  3925. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3926. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3927. </span>
  3928. </div>
  3929. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3930. {statusControlMenu === 'nozzle-select' && (
  3931. <IndicatorControlPopover
  3932. title="Set Nozzle Selection"
  3933. widthClass="w-[300px]"
  3934. popoverWidth={300}
  3935. popoverHeight={140}
  3936. isPending={selectExtruderMutation.isPending}
  3937. options={[
  3938. { label: 'Left', value: 1 },
  3939. { label: 'Right', value: 0 },
  3940. ]}
  3941. onClose={() => setStatusControlMenu(null)}
  3942. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3943. />
  3944. )}
  3945. </div>
  3946. </DualNozzleHoverCard>
  3947. )}
  3948. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3949. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3950. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3951. )}
  3952. </div>
  3953. <div className="mt-2 flex items-center gap-1.5">
  3954. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3955. const active = value > 0;
  3956. return (
  3957. <div
  3958. key={key}
  3959. 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 ${
  3960. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3961. }`}
  3962. title={canUseStatusControls ? label : statusControlTitle}
  3963. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3964. >
  3965. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3966. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3967. {value}%
  3968. </span>
  3969. {statusControlMenu === `fan-${key}` && (
  3970. <IndicatorControlPopover
  3971. title={`Set ${label} Speed`}
  3972. unit="%"
  3973. customMin={0}
  3974. customMax={100}
  3975. isPending={fanSpeedMutation.isPending}
  3976. options={buildPresetOptions(fanSpeedPresets, '%')}
  3977. onClose={() => setStatusControlMenu(null)}
  3978. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  3979. />
  3980. )}
  3981. </div>
  3982. );
  3983. })}
  3984. </div>
  3985. </>
  3986. );
  3987. })()}
  3988. {viewMode === 'expanded' && showClearPlateButton && (
  3989. <button
  3990. type="button"
  3991. onClick={() => clearPlateMutation.mutate()}
  3992. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3993. 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"
  3994. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3995. >
  3996. {clearPlateMutation.isPending ? (
  3997. <Loader2 className="w-3 h-3 animate-spin" />
  3998. ) : (
  3999. <PlateClearedIcon className="w-4 h-4" />
  4000. )}
  4001. {t('printers.plateStatus.markCleared')}
  4002. </button>
  4003. )}
  4004. {/* Controls */}
  4005. {viewMode === 'expanded' && (() => {
  4006. // Determine print state for control buttons
  4007. const isRunning = status.state === 'RUNNING';
  4008. const isPaused = status.state === 'PAUSE';
  4009. const isPrinting = isRunning || isPaused;
  4010. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4011. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4012. 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';
  4013. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4014. return (
  4015. <div className="mt-3">
  4016. {/* Section Header */}
  4017. <div className="flex items-center gap-2 mb-2">
  4018. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4019. {t('printers.controls')}
  4020. </span>
  4021. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4022. </div>
  4023. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4024. {/* Left: Secondary controls */}
  4025. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4026. <button
  4027. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4028. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4029. className={`${iconControlClass} ${
  4030. status.chamber_light
  4031. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4032. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4033. }`}
  4034. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4035. >
  4036. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  4037. </button>
  4038. {/* Airduct Mode (P2S / X2D / H2*) */}
  4039. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4040. const isHeating = status.airduct_mode === 1;
  4041. const Icon = isHeating ? Flame : Snowflake;
  4042. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4043. 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';
  4044. return (
  4045. <div className="relative">
  4046. <button
  4047. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4048. disabled={!hasPermission('printers:control')}
  4049. className={`${iconControlClass} ${bg}`}
  4050. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4051. >
  4052. <Icon className={`w-4 h-4 ${color}`} />
  4053. </button>
  4054. {showAirductMenu === printer.id && (
  4055. <>
  4056. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4057. <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]">
  4058. {([
  4059. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4060. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4061. ] as const).map(({ mode, label, modeId }) => (
  4062. <button
  4063. key={mode}
  4064. onClick={() => {
  4065. airductMutation.mutate(mode);
  4066. setShowAirductMenu(null);
  4067. }}
  4068. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4069. status.airduct_mode === modeId
  4070. ? 'text-bambu-green bg-bambu-green/10'
  4071. : 'text-white hover:bg-bambu-dark-tertiary'
  4072. }`}
  4073. >
  4074. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  4075. {label}
  4076. </button>
  4077. ))}
  4078. </div>
  4079. </>
  4080. )}
  4081. </div>
  4082. );
  4083. })()}
  4084. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4085. {(() => {
  4086. const canControl = hasPermission('printers:control');
  4087. const disabled = isPrinting || !canControl;
  4088. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  4089. 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';
  4090. const requestZJog = (direction: 1 | -1) => {
  4091. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  4092. // The jog never disables the soft endstops (#2579), so it's always
  4093. // safe: the firmware clamps the move at the travel limit, or refuses
  4094. // it if the printer isn't homed. No not-homed bypass to gate.
  4095. bedJogMutation.mutate({ distance: signed });
  4096. };
  4097. const requestXyJog = (x: number, y: number) => {
  4098. xyJogMutation.mutate({ x, y });
  4099. };
  4100. const requestExtruderJog = (distance: number) => {
  4101. extruderJogMutation.mutate(distance);
  4102. };
  4103. return (
  4104. <div className="relative">
  4105. <button
  4106. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4107. disabled={disabled}
  4108. className={`${iconControlClass} ${
  4109. disabled
  4110. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4111. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4112. }`}
  4113. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4114. >
  4115. <Move className="w-4 h-4" />
  4116. </button>
  4117. {showBedJogMenu === printer.id && (
  4118. <>
  4119. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4120. <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">
  4121. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4122. {t('printers.bedJog.title')}
  4123. </div>
  4124. <div className="h-px bg-bambu-dark-tertiary" />
  4125. {/* #2579: Bambu firmware does not enforce soft endstops on
  4126. G-code sent over MQTT, so manual moves can drive past the
  4127. travel limits and cause a collision. Not fixable from our
  4128. side — warn prominently. */}
  4129. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[11px] leading-snug text-yellow-700 dark:text-yellow-400">
  4130. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4131. <span>{t('printers.bedJog.limitWarning')}</span>
  4132. </div>
  4133. <div className="h-px bg-bambu-dark-tertiary" />
  4134. <div className="flex justify-center px-3 py-2.5">
  4135. <div className="flex items-center justify-center gap-3">
  4136. <div className="grid grid-cols-3 gap-1">
  4137. <div />
  4138. <button
  4139. onClick={() => requestXyJog(0, bedJogStep)}
  4140. disabled={xyJogMutation.isPending}
  4141. className={jogButtonClass}
  4142. aria-label="Move Y forward"
  4143. >
  4144. <ArrowUp className="w-4 h-4" />
  4145. </button>
  4146. <div />
  4147. <button
  4148. onClick={() => requestXyJog(-bedJogStep, 0)}
  4149. disabled={xyJogMutation.isPending}
  4150. className={jogButtonClass}
  4151. aria-label="Move X left"
  4152. >
  4153. <ArrowLeft className="w-4 h-4" />
  4154. </button>
  4155. <button
  4156. onClick={() => {
  4157. setShowBedJogMenu(null);
  4158. homeAxesMutation.mutate('all');
  4159. }}
  4160. disabled={homeAxesMutation.isPending}
  4161. className={jogButtonClass}
  4162. aria-label={t('printers.bedJog.homeZ')}
  4163. >
  4164. <Home className="w-4 h-4" />
  4165. </button>
  4166. <button
  4167. onClick={() => requestXyJog(bedJogStep, 0)}
  4168. disabled={xyJogMutation.isPending}
  4169. className={jogButtonClass}
  4170. aria-label="Move X right"
  4171. >
  4172. <ArrowRight className="w-4 h-4" />
  4173. </button>
  4174. <div />
  4175. <button
  4176. onClick={() => requestXyJog(0, -bedJogStep)}
  4177. disabled={xyJogMutation.isPending}
  4178. className={jogButtonClass}
  4179. aria-label="Move Y back"
  4180. >
  4181. <ArrowDown className="w-4 h-4" />
  4182. </button>
  4183. <div />
  4184. </div>
  4185. <div className="flex flex-col items-center gap-1">
  4186. <button
  4187. onClick={() => requestZJog(-1)}
  4188. disabled={bedJogMutation.isPending}
  4189. className={jogButtonClass}
  4190. aria-label={t('printers.bedJog.up')}
  4191. >
  4192. <ArrowUp className="w-4 h-4" />
  4193. </button>
  4194. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4195. <Layers className="w-4 h-4" />
  4196. </div>
  4197. <button
  4198. onClick={() => requestZJog(1)}
  4199. disabled={bedJogMutation.isPending}
  4200. className={jogButtonClass}
  4201. aria-label={t('printers.bedJog.down')}
  4202. >
  4203. <ArrowDown className="w-4 h-4" />
  4204. </button>
  4205. </div>
  4206. <div className="flex flex-col items-center gap-1">
  4207. <button
  4208. onClick={() => requestExtruderJog(-bedJogStep)}
  4209. disabled={extruderJogMutation.isPending}
  4210. className={jogButtonClass}
  4211. aria-label="Retract filament"
  4212. >
  4213. <ArrowUp className="w-4 h-4" />
  4214. </button>
  4215. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4216. <span className="text-sm font-semibold leading-none">E</span>
  4217. </div>
  4218. <button
  4219. onClick={() => requestExtruderJog(bedJogStep)}
  4220. disabled={extruderJogMutation.isPending}
  4221. className={jogButtonClass}
  4222. aria-label="Extrude filament"
  4223. >
  4224. <ArrowDown className="w-4 h-4" />
  4225. </button>
  4226. </div>
  4227. </div>
  4228. </div>
  4229. <div className="h-px bg-bambu-dark-tertiary" />
  4230. <div className="px-3 pt-2.5 pb-3">
  4231. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4232. {t('printers.bedJog.step')}
  4233. </div>
  4234. <div className="flex gap-1">
  4235. {[1, 10, 50].map((step) => (
  4236. <button
  4237. key={step}
  4238. onClick={() => setBedJogStep(step)}
  4239. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4240. bedJogStep === step
  4241. ? 'bg-bambu-green/20 text-bambu-green'
  4242. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4243. }`}
  4244. >
  4245. {step}
  4246. </button>
  4247. ))}
  4248. </div>
  4249. </div>
  4250. </div>
  4251. </>
  4252. )}
  4253. </div>
  4254. );
  4255. })()}
  4256. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4257. <button
  4258. onClick={handleTogglePlateDetection}
  4259. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4260. className={`${iconControlClass} rounded-r-none ${
  4261. printer.plate_detection_enabled
  4262. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4263. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4264. }`}
  4265. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4266. >
  4267. {plateDetectionMutation.isPending ? (
  4268. <Loader2 className="w-4 h-4 animate-spin" />
  4269. ) : (
  4270. <ScanSearch className="w-4 h-4" />
  4271. )}
  4272. </button>
  4273. <button
  4274. onClick={handleOpenPlateManagement}
  4275. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4276. 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 ${
  4277. printer.plate_detection_enabled
  4278. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4279. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4280. }`}
  4281. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4282. >
  4283. {isCheckingPlate ? (
  4284. <Loader2 className="w-4 h-4 animate-spin" />
  4285. ) : (
  4286. <ChevronDown className="w-4 h-4" />
  4287. )}
  4288. </button>
  4289. </div>
  4290. {/* Print Speed */}
  4291. {(() => (
  4292. <div className="relative">
  4293. <button
  4294. data-testid="speed-control"
  4295. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4296. disabled={!isPrinting || !hasPermission('printers:control')}
  4297. className={`${iconControlClass} ${
  4298. isPrinting
  4299. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4300. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4301. }`}
  4302. title={isPrinting ? t('printers.speed.title') : undefined}
  4303. >
  4304. <Gauge className="w-4 h-4" />
  4305. </button>
  4306. {showSpeedMenu === printer.id && (
  4307. <>
  4308. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4309. <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]">
  4310. {([
  4311. { mode: 1, label: t('printers.speed.silent') },
  4312. { mode: 2, label: t('printers.speed.standard') },
  4313. { mode: 3, label: t('printers.speed.sport') },
  4314. { mode: 4, label: t('printers.speed.ludicrous') },
  4315. ] as const).map(({ mode, label }) => (
  4316. <button
  4317. key={mode}
  4318. onClick={() => {
  4319. printSpeedMutation.mutate(mode);
  4320. setShowSpeedMenu(null);
  4321. }}
  4322. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4323. status.speed_level === mode
  4324. ? 'text-bambu-green bg-bambu-green/10'
  4325. : 'text-white hover:bg-bambu-dark-tertiary'
  4326. }`}
  4327. >
  4328. {label}
  4329. </button>
  4330. ))}
  4331. </div>
  4332. </>
  4333. )}
  4334. </div>
  4335. ))()}
  4336. </div>
  4337. {/* Right: Print Control Buttons */}
  4338. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4339. {/* Pause/Resume button */}
  4340. {(() => {
  4341. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4342. return (
  4343. <button
  4344. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4345. disabled={pauseUnavailable}
  4346. className={`
  4347. ${printControlClass}
  4348. ${pauseUnavailable
  4349. ? unavailablePrintActionClass
  4350. : isPaused
  4351. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4352. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4353. }
  4354. `}
  4355. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4356. >
  4357. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4358. {isPaused ? t('printers.resume') : t('printers.pause')}
  4359. </button>
  4360. );
  4361. })()}
  4362. {/* Stop button */}
  4363. {(() => {
  4364. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4365. return (
  4366. <button
  4367. onClick={() => setShowStopConfirm(true)}
  4368. disabled={stopUnavailable}
  4369. className={`
  4370. ${printControlClass}
  4371. ${stopUnavailable
  4372. ? unavailablePrintActionClass
  4373. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4374. }
  4375. `}
  4376. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4377. >
  4378. <Square className="w-3 h-3" />
  4379. {t('printers.stop')}
  4380. </button>
  4381. );
  4382. })()}
  4383. </div>
  4384. </div>
  4385. </div>
  4386. );
  4387. })()}
  4388. {/* AMS Units - 2-Column Grid Layout */}
  4389. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4390. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4391. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4392. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4393. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4394. const filamentSlotClass = 'min-w-14';
  4395. // #1762 (comment 2): while a print is running/paused, overlay a small
  4396. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4397. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4398. // staged to a printer with mismatched filament: the wrong-slot pill
  4399. // is visible the instant printing starts.
  4400. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4401. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4402. ? status.ams_mapping
  4403. : [];
  4404. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4405. const boundedSlotCount = Math.max(1, slotCount);
  4406. const gapCount = Math.max(0, boundedSlotCount - 1);
  4407. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4408. return {
  4409. flex: `1 1 ${minWidth}`,
  4410. minWidth,
  4411. };
  4412. };
  4413. return (
  4414. <div className="mt-3">
  4415. {/* Section Header */}
  4416. <div className="flex items-center gap-2 mb-2">
  4417. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4418. {t('printers.filaments')}
  4419. </span>
  4420. <AmsBackupBadge
  4421. state={status.ams_filament_backup}
  4422. onClick={() => setAmsBackupModalOpen(true)}
  4423. />
  4424. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4425. </div>
  4426. {/* AMS Content */}
  4427. <div className="flex flex-wrap gap-2">
  4428. {/* Regular AMS units */}
  4429. {regularAms.map((ams) => {
  4430. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4431. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4432. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4433. const isLeftNozzle = extruderId === 1;
  4434. const isRightNozzle = extruderId === 0;
  4435. return (
  4436. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4437. {/* Header: Label + Stats (no icon) */}
  4438. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4439. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4440. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4441. <AmsNameHoverCard
  4442. ams={ams}
  4443. printerId={printer.id}
  4444. label={getAmsLabel(ams.id, ams.tray.length)}
  4445. amsLabels={amsLabels}
  4446. canEdit={hasPermission('printers:update')}
  4447. onSaved={refetchAmsLabels}
  4448. >
  4449. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4450. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4451. </span>
  4452. </AmsNameHoverCard>
  4453. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4454. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4455. )}
  4456. </div>
  4457. {(ams.humidity != null || ams.temp != null) && (
  4458. <div className="flex shrink-0 items-center gap-1.5">
  4459. {ams.humidity != null && (
  4460. <HumidityIndicator
  4461. humidity={ams.humidity}
  4462. goodThreshold={amsThresholds?.humidityGood}
  4463. fairThreshold={amsThresholds?.humidityFair}
  4464. onClick={() => setAmsHistoryModal({
  4465. amsId: ams.id,
  4466. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4467. mode: 'humidity',
  4468. })}
  4469. compact
  4470. />
  4471. )}
  4472. {ams.temp != null && (
  4473. <div className="mr-1">
  4474. <TemperatureIndicator
  4475. temp={ams.temp}
  4476. goodThreshold={amsThresholds?.tempGood}
  4477. fairThreshold={amsThresholds?.tempFair}
  4478. onClick={() => setAmsHistoryModal({
  4479. amsId: ams.id,
  4480. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4481. mode: 'temperature',
  4482. })}
  4483. compact
  4484. />
  4485. </div>
  4486. )}
  4487. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4488. Screen-only models (P1 series) keep the control but can't
  4489. be commanded: it stays disabled and says why (#2533). */}
  4490. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4491. <button
  4492. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4493. onClick={(e) => {
  4494. if (ams.dry_time > 0) {
  4495. stopDryingMutation.mutate(ams.id);
  4496. } else if (dryingPopoverAmsId === ams.id) {
  4497. setDryingPopoverAmsId(null);
  4498. } else {
  4499. const firstTray = ams.tray.find(t => t.tray_type);
  4500. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4501. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4502. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4503. setDryingFilament(filType);
  4504. setDryingTemp(preset[moduleType] || preset.n3f);
  4505. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4506. setDryingRotateTray(false);
  4507. setDryingPopoverModuleType(ams.module_type);
  4508. setDryingPopoverAmsId(ams.id);
  4509. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4510. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4511. }
  4512. }}
  4513. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4514. ams.dry_time > 0
  4515. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4516. : status.drying_screen_only || ams.dry_sf_reason?.length
  4517. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4518. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4519. }`}
  4520. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
  4521. >
  4522. <Flame className="w-3 h-3" />
  4523. </button>
  4524. )}
  4525. </div>
  4526. )}
  4527. </div>
  4528. {/* Drying status bar */}
  4529. {ams.dry_time > 0 && (
  4530. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  4531. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4532. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4533. {ams.dry_filament && ams.dry_target_temp != null && (
  4534. <span className="text-amber-700/80 dark:text-amber-300/70">
  4535. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4536. </span>
  4537. )}
  4538. <span className="text-amber-700/80 dark:text-amber-300/70">
  4539. {t('printers.drying.timeRemaining', {
  4540. time: ams.dry_time >= 60
  4541. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4542. : `${ams.dry_time}m`
  4543. })}
  4544. </span>
  4545. {/* A cycle on a screen-only model was started at the printer
  4546. and can only be stopped there (#2533). */}
  4547. {!status.drying_screen_only && (
  4548. <button
  4549. onClick={() => stopDryingMutation.mutate(ams.id)}
  4550. disabled={stopDryingMutation.isPending}
  4551. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  4552. title={t('printers.drying.stop')}
  4553. >
  4554. <X className="w-3 h-3" />
  4555. </button>
  4556. )}
  4557. </div>
  4558. )}
  4559. {/* Slots grid: 4 columns - always render 4 slots */}
  4560. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4561. {[0, 1, 2, 3].map((slotIdx) => {
  4562. // Find tray data for this slot (may be undefined if data incomplete)
  4563. // Use array index if available, as tray.id may not always be set
  4564. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4565. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4566. const isEmpty = !tray?.tray_type;
  4567. const emptyKind = getEmptySlotKind(tray);
  4568. // Check if this is the currently loaded tray
  4569. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4570. const globalTrayId = ams.id * 4 + slotIdx;
  4571. const isActive = effectiveTrayNow === globalTrayId;
  4572. // Runout guidance (#2587): the slot the paused print now
  4573. // expects filament in, and the slot that ran out.
  4574. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4575. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4576. // Get cloud preset info if available
  4577. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4578. // Get saved slot preset mapping (for user-configured slots)
  4579. const slotPreset = slotPresets?.[globalTrayId];
  4580. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4581. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4582. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4583. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4584. // Slot-assigned-only spool fill (no tag link required)
  4585. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4586. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4587. : undefined;
  4588. const slotSpoolForFill = slotAssignmentForFill
  4589. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4590. : undefined;
  4591. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4592. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4593. : null;
  4594. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4595. const inventoryFill = (() => {
  4596. const sp = inventoryAssignment?.spool;
  4597. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4598. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4599. }
  4600. return null;
  4601. })();
  4602. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4603. // (inventory weight_used may be stale or over-counted — #676)
  4604. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4605. ? null : inventoryFill;
  4606. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4607. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4608. : resolvedInventoryFill !== null ? 'inventory' as const
  4609. : hasFillLevel ? 'ams' as const
  4610. : undefined;
  4611. // Build filament data for hover card
  4612. const filamentData = tray?.tray_type ? {
  4613. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4614. // Spoolman spool name wins over cloud lookup so a slot bound to
  4615. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4616. // Design PLA") instead of whatever the printer's filament_id
  4617. // resolves to in the cloud catalog (often "Generic PLA" for
  4618. // P-prefix local presets). Spoolman's filament.name is just the
  4619. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4620. // the hover card shows "Devil Design PLA Basic" rather than the
  4621. // vendor-less form. Strip the "@<printer>..." suffix that
  4622. // BambuStudio appends to user-preset names.
  4623. profile: slotPreset?.preset_name || (slotSpoolForFill ? [slotSpoolForFill.brand, slotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || slotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || inventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  4624. colorName: getColorName(tray.tray_color || ''),
  4625. colorHex: tray.tray_color || null,
  4626. kFactor: formatKValue(tray.k),
  4627. fillLevel: effectiveFill,
  4628. trayUuid: tray.tray_uuid || null,
  4629. tagUid: tray.tag_uid || null,
  4630. fillSource,
  4631. } : null;
  4632. // Check if this specific slot is being refreshed
  4633. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4634. refreshingSlot?.slotId === slotIdx;
  4635. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4636. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4637. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4638. ? `P${activePrintSlotIdx + 1}`
  4639. : null;
  4640. // Slot visual content (goes inside hover card)
  4641. const slotVisual = (
  4642. <div
  4643. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4644. isExpectedSlot
  4645. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4646. : isRanOutSlot
  4647. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4648. : isActive
  4649. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4650. : ''
  4651. }`}
  4652. >
  4653. {isExpectedSlot && (
  4654. <span
  4655. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  4656. title={t('printers.expectedSlot.title')}
  4657. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4658. >
  4659. </span>
  4660. )}
  4661. {activePrintSlotLabel && (
  4662. <span
  4663. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4664. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4665. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4666. >
  4667. {activePrintSlotLabel}
  4668. </span>
  4669. )}
  4670. {/* Filament color circle with 1-based slot number centered inside */}
  4671. <FilamentSlotCircle
  4672. trayColor={tray?.tray_color}
  4673. trayType={tray?.tray_type}
  4674. isEmpty={isEmpty}
  4675. emptyKind={emptyKind}
  4676. slotNumber={slotIdx + 1}
  4677. />
  4678. <div className="text-[9px] text-white font-bold truncate">
  4679. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4680. </div>
  4681. {/* Fill bar */}
  4682. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4683. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4684. <div
  4685. className="h-full rounded-full transition-all"
  4686. style={{
  4687. width: `${effectiveFill}%`,
  4688. backgroundColor: getFillBarColor(effectiveFill),
  4689. }}
  4690. />
  4691. )}
  4692. </div>
  4693. </div>
  4694. );
  4695. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4696. return (
  4697. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4698. {/* Loading overlay during RFID re-read */}
  4699. {isRefreshing && (
  4700. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4701. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4702. </div>
  4703. )}
  4704. {/* Hover card wraps only the visual content */}
  4705. {filamentData ? (
  4706. <FilamentHoverCard
  4707. data={filamentData}
  4708. actions={renderAmsSlotActions({
  4709. amsId: ams.id,
  4710. slotId: slotIdx,
  4711. loadTrayId: ams.id * 4 + slotIdx,
  4712. isRefreshing,
  4713. })}
  4714. spoolman={{
  4715. enabled: spoolmanEnabled,
  4716. // #1457: slot assignment is the user's most explicit action — it must
  4717. // outrank the tag-link, which can be stale when a non-RFID slot's
  4718. // fallback tag is still attached to a previous spool in Spoolman.
  4719. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4720. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4721. spoolmanUrl,
  4722. syncMode: spoolmanSyncMode,
  4723. // Suppress Link button when slot is already occupied by ANY assignment
  4724. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4725. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4726. // still appearing on slots with a local Devil Design PLA assigned.
  4727. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4728. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4729. setLinkSpoolModal({
  4730. tagUid: filamentData.tagUid || linkTag,
  4731. trayUuid: filamentData.trayUuid || '',
  4732. printerId: printer.id,
  4733. amsId: ams.id,
  4734. trayId: slotIdx,
  4735. });
  4736. } : undefined,
  4737. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4738. }}
  4739. inventory={(() => {
  4740. if (spoolmanEnabled) {
  4741. if (spoolmanLoading) return undefined;
  4742. const slotAssignment = slotAssignmentForFill;
  4743. const spoolmanSpool = slotSpoolForFill;
  4744. return {
  4745. assignedSpool: spoolmanSpool ? {
  4746. id: spoolmanSpool.id,
  4747. material: spoolmanSpool.material,
  4748. brand: spoolmanSpool.brand ?? null,
  4749. color_name: spoolmanSpool.color_name ?? null,
  4750. remainingWeightGrams: spoolmanSpool.label_weight
  4751. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4752. : undefined,
  4753. } : null,
  4754. onAssignSpool: () => setAssignSpoolModal({
  4755. printerId: printer.id,
  4756. amsId: ams.id,
  4757. trayId: slotIdx,
  4758. trayInfo: {
  4759. type: tray?.tray_type || filamentData.profile,
  4760. material: tray?.tray_type ?? undefined,
  4761. profile: filamentData.profile,
  4762. color: filamentData.colorHex || '',
  4763. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4764. },
  4765. }),
  4766. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4767. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4768. };
  4769. }
  4770. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4771. return {
  4772. assignedSpool: assignment?.spool ? {
  4773. id: assignment.spool.id,
  4774. material: assignment.spool.material,
  4775. brand: assignment.spool.brand,
  4776. color_name: assignment.spool.color_name,
  4777. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4778. } : null,
  4779. onAssignSpool: () => setAssignSpoolModal({
  4780. printerId: printer.id,
  4781. amsId: ams.id,
  4782. trayId: slotIdx,
  4783. trayInfo: {
  4784. type: tray?.tray_type || filamentData.profile,
  4785. material: tray?.tray_type ?? undefined,
  4786. profile: filamentData.profile,
  4787. color: filamentData.colorHex || '',
  4788. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4789. },
  4790. }),
  4791. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4792. isAssigned: !!assignment || isBambuLabSpool(tray),
  4793. };
  4794. })()}
  4795. configureSlot={{
  4796. enabled: hasPermission('printers:control'),
  4797. onConfigure: () => setConfigureSlotModal({
  4798. amsId: ams.id,
  4799. trayId: slotIdx,
  4800. trayCount: ams.tray.length,
  4801. trayType: tray?.tray_type || undefined,
  4802. trayColor: tray?.tray_color || undefined,
  4803. traySubBrands: tray?.tray_sub_brands || undefined,
  4804. trayInfoIdx: tray?.tray_info_idx || undefined,
  4805. extruderId: mappedExtruderId,
  4806. caliIdx: tray?.cali_idx,
  4807. savedPresetId: slotPreset?.preset_id,
  4808. }),
  4809. }}
  4810. >
  4811. {slotVisual}
  4812. </FilamentHoverCard>
  4813. ) : (
  4814. <EmptySlotHoverCard
  4815. kind={emptyKind ?? undefined}
  4816. actions={renderAmsSlotActions({
  4817. amsId: ams.id,
  4818. slotId: slotIdx,
  4819. loadTrayId: ams.id * 4 + slotIdx,
  4820. isRefreshing,
  4821. })}
  4822. configureSlot={{
  4823. enabled: hasPermission('printers:control'),
  4824. onConfigure: () => setConfigureSlotModal({
  4825. amsId: ams.id,
  4826. trayId: slotIdx,
  4827. trayCount: ams.tray.length,
  4828. extruderId: mappedExtruderId,
  4829. }),
  4830. }}
  4831. onAssignSpool={() => setAssignSpoolModal({
  4832. printerId: printer.id,
  4833. amsId: ams.id,
  4834. trayId: slotIdx,
  4835. trayInfo: {
  4836. type: '',
  4837. material: undefined,
  4838. profile: '',
  4839. color: '',
  4840. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4841. },
  4842. })}
  4843. >
  4844. {slotVisual}
  4845. </EmptySlotHoverCard>
  4846. )}
  4847. </div>
  4848. );
  4849. })}
  4850. </div>
  4851. </div>
  4852. );
  4853. })}
  4854. {/* HT AMS units */}
  4855. {htAms.map((ams) => {
  4856. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4857. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4858. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4859. const isLeftNozzle = extruderId === 1;
  4860. const isRightNozzle = extruderId === 0;
  4861. const tray = ams.tray[0];
  4862. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4863. const isEmpty = !tray?.tray_type;
  4864. const emptyKind = getEmptySlotKind(tray);
  4865. // Check if this is the currently loaded tray
  4866. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4867. const isActive = effectiveTrayNow === globalTrayId;
  4868. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  4869. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4870. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4871. // Get cloud preset info if available
  4872. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4873. // Get saved slot preset mapping (for user-configured slots)
  4874. const slotPreset = slotPresets?.[globalTrayId];
  4875. const htSlotId = tray?.id ?? 0;
  4876. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4877. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4878. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4879. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4880. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4881. const htInventoryFill = (() => {
  4882. const sp = htInventoryAssignment?.spool;
  4883. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4884. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4885. }
  4886. return null;
  4887. })();
  4888. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4889. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4890. ? null : htInventoryFill;
  4891. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4892. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4893. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4894. : undefined;
  4895. const htSlotSpoolForFill = htSlotAssignmentForFill
  4896. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4897. : undefined;
  4898. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4899. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4900. : null;
  4901. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4902. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4903. : htResolvedInventoryFill !== null ? 'inventory' as const
  4904. : hasFillLevel ? 'ams' as const
  4905. : undefined;
  4906. // Build filament data for hover card
  4907. const filamentData = tray?.tray_type ? {
  4908. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4909. profile: slotPreset?.preset_name || (htSlotSpoolForFill ? [htSlotSpoolForFill.brand, htSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || htSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || htInventoryAssignment?.spool?.slicer_filament_name || cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  4910. colorName: getColorName(tray.tray_color || ''),
  4911. colorHex: tray.tray_color || null,
  4912. kFactor: formatKValue(tray.k),
  4913. fillLevel: htEffectiveFill,
  4914. trayUuid: tray.tray_uuid || null,
  4915. tagUid: tray.tag_uid || null,
  4916. fillSource: htFillSource,
  4917. } : null;
  4918. // Check if this specific slot is being refreshed
  4919. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4920. refreshingSlot?.slotId === htSlotId;
  4921. // #1762 (comment 2): active print-slot index for this HT slot.
  4922. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4923. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4924. ? `P${htActivePrintSlotIdx + 1}`
  4925. : null;
  4926. // Slot visual content (goes inside hover card)
  4927. const slotVisual = (
  4928. <div
  4929. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4930. isExpectedSlot
  4931. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4932. : isRanOutSlot
  4933. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4934. : isActive
  4935. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4936. : ''
  4937. }`}
  4938. >
  4939. {isExpectedSlot && (
  4940. <span
  4941. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  4942. title={t('printers.expectedSlot.title')}
  4943. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4944. >
  4945. </span>
  4946. )}
  4947. {htActivePrintSlotLabel && (
  4948. <span
  4949. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4950. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4951. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4952. >
  4953. {htActivePrintSlotLabel}
  4954. </span>
  4955. )}
  4956. {/* Filament color circle with 1-based slot number centered inside */}
  4957. <FilamentSlotCircle
  4958. trayColor={tray?.tray_color}
  4959. trayType={tray?.tray_type}
  4960. isEmpty={isEmpty}
  4961. emptyKind={emptyKind}
  4962. slotNumber={1}
  4963. />
  4964. <div className="text-[9px] text-white font-bold truncate">
  4965. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4966. </div>
  4967. {/* Fill bar */}
  4968. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4969. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4970. <div
  4971. className="h-full rounded-full transition-all"
  4972. style={{
  4973. width: `${htEffectiveFill}%`,
  4974. backgroundColor: getFillBarColor(htEffectiveFill),
  4975. }}
  4976. />
  4977. )}
  4978. </div>
  4979. </div>
  4980. );
  4981. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4982. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4983. // Without this override, the L view squishes HT into a sliver next to the
  4984. // 4-slot AMS neighbors.
  4985. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4986. return (
  4987. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4988. {/* Row 1: Label + Nozzle + Drying */}
  4989. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4990. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4991. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4992. <AmsNameHoverCard
  4993. ams={ams}
  4994. printerId={printer.id}
  4995. label={getAmsLabel(ams.id, ams.tray.length)}
  4996. amsLabels={amsLabels}
  4997. canEdit={hasPermission('printers:update')}
  4998. onSaved={refetchAmsLabels}
  4999. >
  5000. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  5001. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5002. </span>
  5003. </AmsNameHoverCard>
  5004. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  5005. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  5006. )}
  5007. </div>
  5008. {/* Drying button for HT AMS */}
  5009. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5010. <div className="relative ml-auto">
  5011. <button
  5012. disabled={status.drying_screen_only}
  5013. onClick={(e) => {
  5014. if (ams.dry_time > 0) {
  5015. stopDryingMutation.mutate(ams.id);
  5016. } else if (dryingPopoverAmsId === ams.id) {
  5017. setDryingPopoverAmsId(null);
  5018. } else {
  5019. const firstTray = ams.tray.find(t => t.tray_type);
  5020. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  5021. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  5022. const moduleType = ams.module_type as 'n3f' | 'n3s';
  5023. setDryingFilament(filType);
  5024. setDryingTemp(preset[moduleType] || preset.n3f);
  5025. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  5026. setDryingRotateTray(false);
  5027. setDryingPopoverModuleType(ams.module_type);
  5028. setDryingPopoverAmsId(ams.id);
  5029. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  5030. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  5031. }
  5032. }}
  5033. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  5034. ams.dry_time > 0
  5035. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5036. : status.drying_screen_only
  5037. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5038. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5039. }`}
  5040. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5041. >
  5042. <Flame className="w-3 h-3" />
  5043. </button>
  5044. </div>
  5045. )}
  5046. </div>
  5047. {/* HT AMS drying status bar */}
  5048. {ams.dry_time > 0 && (
  5049. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  5050. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  5051. {ams.dry_filament && ams.dry_target_temp != null && (
  5052. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  5053. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  5054. </span>
  5055. )}
  5056. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  5057. {ams.dry_time >= 60
  5058. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5059. : `${ams.dry_time}m`}
  5060. </span>
  5061. {!status.drying_screen_only && (
  5062. <button
  5063. onClick={() => stopDryingMutation.mutate(ams.id)}
  5064. disabled={stopDryingMutation.isPending}
  5065. 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"
  5066. title={t('printers.drying.stop')}
  5067. >
  5068. <X className="w-3 h-3" />
  5069. </button>
  5070. )}
  5071. </div>
  5072. )}
  5073. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5074. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5075. {/* Slot wrapper with loading overlay */}
  5076. <div className="relative group min-w-14 flex-1">
  5077. {/* Loading overlay during RFID re-read */}
  5078. {isHtRefreshing && (
  5079. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5080. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  5081. </div>
  5082. )}
  5083. {/* Hover card wraps only the visual content */}
  5084. {filamentData ? (
  5085. <FilamentHoverCard
  5086. data={filamentData}
  5087. actions={renderAmsSlotActions({
  5088. amsId: ams.id,
  5089. slotId: htSlotId,
  5090. loadTrayId: ams.id * 4 + htSlotId,
  5091. isRefreshing: isHtRefreshing,
  5092. })}
  5093. spoolman={{
  5094. enabled: spoolmanEnabled,
  5095. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5096. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5097. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5098. spoolmanUrl,
  5099. syncMode: spoolmanSyncMode,
  5100. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5101. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5102. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5103. setLinkSpoolModal({
  5104. tagUid: filamentData.tagUid || linkTag,
  5105. trayUuid: filamentData.trayUuid || '',
  5106. printerId: printer.id,
  5107. amsId: ams.id,
  5108. trayId: htSlotId,
  5109. });
  5110. } : undefined,
  5111. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5112. }}
  5113. inventory={(() => {
  5114. if (spoolmanEnabled) {
  5115. if (spoolmanLoading) return undefined;
  5116. const slotAssignment = htSlotAssignmentForFill;
  5117. const spoolmanSpool = htSlotSpoolForFill;
  5118. return {
  5119. assignedSpool: spoolmanSpool ? {
  5120. id: spoolmanSpool.id,
  5121. material: spoolmanSpool.material,
  5122. brand: spoolmanSpool.brand ?? null,
  5123. color_name: spoolmanSpool.color_name ?? null,
  5124. remainingWeightGrams: spoolmanSpool.label_weight
  5125. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5126. : undefined,
  5127. } : null,
  5128. onAssignSpool: () => setAssignSpoolModal({
  5129. printerId: printer.id,
  5130. amsId: ams.id,
  5131. trayId: htSlotId,
  5132. trayInfo: {
  5133. type: tray?.tray_type || filamentData.profile,
  5134. material: tray?.tray_type ?? undefined,
  5135. profile: filamentData.profile,
  5136. color: filamentData.colorHex || '',
  5137. location: getAmsLabel(ams.id, ams.tray.length),
  5138. },
  5139. }),
  5140. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5141. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5142. };
  5143. }
  5144. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5145. return {
  5146. assignedSpool: assignment?.spool ? {
  5147. id: assignment.spool.id,
  5148. material: assignment.spool.material,
  5149. brand: assignment.spool.brand,
  5150. color_name: assignment.spool.color_name,
  5151. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5152. } : null,
  5153. onAssignSpool: () => setAssignSpoolModal({
  5154. printerId: printer.id,
  5155. amsId: ams.id,
  5156. trayId: htSlotId,
  5157. trayInfo: {
  5158. type: tray?.tray_type || filamentData.profile,
  5159. material: tray?.tray_type ?? undefined,
  5160. profile: filamentData.profile,
  5161. color: filamentData.colorHex || '',
  5162. location: getAmsLabel(ams.id, ams.tray.length),
  5163. },
  5164. }),
  5165. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5166. isAssigned: !!assignment || isBambuLabSpool(tray),
  5167. };
  5168. })()}
  5169. configureSlot={{
  5170. enabled: hasPermission('printers:control'),
  5171. onConfigure: () => setConfigureSlotModal({
  5172. amsId: ams.id,
  5173. trayId: htSlotId,
  5174. trayCount: ams.tray.length,
  5175. trayType: tray?.tray_type || undefined,
  5176. trayColor: tray?.tray_color || undefined,
  5177. traySubBrands: tray?.tray_sub_brands || undefined,
  5178. trayInfoIdx: tray?.tray_info_idx || undefined,
  5179. extruderId: mappedExtruderId,
  5180. caliIdx: tray?.cali_idx,
  5181. savedPresetId: slotPreset?.preset_id,
  5182. }),
  5183. }}
  5184. >
  5185. {slotVisual}
  5186. </FilamentHoverCard>
  5187. ) : (
  5188. <EmptySlotHoverCard
  5189. kind={emptyKind ?? undefined}
  5190. actions={renderAmsSlotActions({
  5191. amsId: ams.id,
  5192. slotId: htSlotId,
  5193. loadTrayId: ams.id * 4 + htSlotId,
  5194. isRefreshing: isHtRefreshing,
  5195. })}
  5196. configureSlot={{
  5197. enabled: hasPermission('printers:control'),
  5198. onConfigure: () => setConfigureSlotModal({
  5199. amsId: ams.id,
  5200. trayId: htSlotId,
  5201. trayCount: ams.tray.length,
  5202. extruderId: mappedExtruderId,
  5203. }),
  5204. }}
  5205. onAssignSpool={() => setAssignSpoolModal({
  5206. printerId: printer.id,
  5207. amsId: ams.id,
  5208. trayId: htSlotId,
  5209. trayInfo: {
  5210. type: '',
  5211. material: undefined,
  5212. profile: '',
  5213. color: '',
  5214. location: getAmsLabel(ams.id, ams.tray.length),
  5215. },
  5216. })}
  5217. >
  5218. {slotVisual}
  5219. </EmptySlotHoverCard>
  5220. )}
  5221. </div>
  5222. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5223. {(ams.humidity != null || ams.temp != null) && (
  5224. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5225. {ams.temp != null && (
  5226. <TemperatureIndicator
  5227. temp={ams.temp}
  5228. goodThreshold={amsThresholds?.tempGood}
  5229. fairThreshold={amsThresholds?.tempFair}
  5230. onClick={() => setAmsHistoryModal({
  5231. amsId: ams.id,
  5232. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5233. mode: 'temperature',
  5234. })}
  5235. compact
  5236. />
  5237. )}
  5238. {ams.humidity != null && (
  5239. <HumidityIndicator
  5240. humidity={ams.humidity}
  5241. goodThreshold={amsThresholds?.humidityGood}
  5242. fairThreshold={amsThresholds?.humidityFair}
  5243. onClick={() => setAmsHistoryModal({
  5244. amsId: ams.id,
  5245. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5246. mode: 'humidity',
  5247. })}
  5248. compact
  5249. />
  5250. )}
  5251. </div>
  5252. )}
  5253. </div>
  5254. </div>
  5255. );
  5256. })}
  5257. {/* External spool(s) - grouped in one card like regular AMS */}
  5258. {status.vt_tray.length > 0 && (
  5259. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5260. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5261. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  5262. </div>
  5263. <div className={`grid w-full ${status.vt_tray.length > 1 ? 'grid-cols-[repeat(2,minmax(3.5rem,1fr))]' : 'grid-cols-[minmax(3.5rem,1fr)]'} gap-1`}>
  5264. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5265. const extTrayId = extTray.id ?? 254;
  5266. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5267. // generically — use active_extruder to determine L vs R:
  5268. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5269. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5270. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5271. (extTrayId === 255 && status.active_extruder === 0)
  5272. : effectiveTrayNow === extTrayId;
  5273. const slotTrayId = extTrayId - 254; // 0 or 1
  5274. const extLabel = isDualNozzle
  5275. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5276. : '';
  5277. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5278. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5279. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5280. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5281. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5282. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5283. const extInventoryFill = (() => {
  5284. const sp = extInventoryAssignment?.spool;
  5285. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5286. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5287. }
  5288. return null;
  5289. })();
  5290. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5291. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5292. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5293. ? null : extInventoryFill;
  5294. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5295. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5296. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5297. : undefined;
  5298. const extSlotSpoolForFill = extSlotAssignmentForFill
  5299. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5300. : undefined;
  5301. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5302. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5303. : null;
  5304. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5305. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5306. : extResolvedInventoryFill !== null ? 'inventory' as const
  5307. : extHasFillLevel ? 'ams' as const
  5308. : undefined;
  5309. const extFilamentData = {
  5310. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5311. profile: extSlotPreset?.preset_name || (extSlotSpoolForFill ? [extSlotSpoolForFill.brand, extSlotSpoolForFill.slicer_filament_name?.split('@')[0].trim() || extSlotSpoolForFill.material].filter(Boolean).join(' ').trim() : null) || extInventoryAssignment?.spool?.slicer_filament_name || extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
  5312. colorName: getColorName(extTray.tray_color || ''),
  5313. colorHex: extTray.tray_color || null,
  5314. kFactor: formatKValue(extTray.k),
  5315. fillLevel: extEffectiveFill,
  5316. trayUuid: extTray.tray_uuid || null,
  5317. tagUid: extTray.tag_uid || null,
  5318. fillSource: extFillSource,
  5319. };
  5320. const isEmpty = !extTray.tray_type;
  5321. const emptyKind = getEmptySlotKind(extTray);
  5322. const extSlotContent = (
  5323. <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' : ''}`}>
  5324. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5325. the separate Ext-L/Ext-R caption that made the row taller than
  5326. regular AMS slots), 1-based slot number on single-nozzle. */}
  5327. <FilamentSlotCircle
  5328. trayColor={extTray.tray_color}
  5329. trayType={extTray.tray_type}
  5330. isEmpty={isEmpty}
  5331. emptyKind={emptyKind}
  5332. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5333. />
  5334. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5335. {extTray.tray_type || t('ams.slotEmpty')}
  5336. </div>
  5337. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5338. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5339. <div
  5340. className="h-full rounded-full transition-all"
  5341. style={{
  5342. width: `${extEffectiveFill}%`,
  5343. backgroundColor: getFillBarColor(extEffectiveFill),
  5344. }}
  5345. />
  5346. )}
  5347. </div>
  5348. </div>
  5349. );
  5350. return (
  5351. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5352. {!isEmpty ? (
  5353. <FilamentHoverCard
  5354. data={extFilamentData}
  5355. actions={renderAmsSlotActions({
  5356. amsId: 255,
  5357. slotId: slotTrayId,
  5358. loadTrayId: extTrayId,
  5359. includeRfid: false,
  5360. })}
  5361. spoolman={{
  5362. enabled: spoolmanEnabled,
  5363. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5364. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5365. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5366. spoolmanUrl,
  5367. syncMode: spoolmanSyncMode,
  5368. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5369. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5370. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5371. setLinkSpoolModal({
  5372. tagUid: extFilamentData.tagUid || linkTag,
  5373. trayUuid: extFilamentData.trayUuid || '',
  5374. printerId: printer.id,
  5375. amsId: 255,
  5376. trayId: slotTrayId,
  5377. });
  5378. } : undefined,
  5379. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5380. }}
  5381. inventory={(() => {
  5382. if (spoolmanEnabled) {
  5383. if (spoolmanLoading) return undefined;
  5384. const slotAssignment = extSlotAssignmentForFill;
  5385. const spoolmanSpool = extSlotSpoolForFill;
  5386. return {
  5387. assignedSpool: spoolmanSpool ? {
  5388. id: spoolmanSpool.id,
  5389. material: spoolmanSpool.material,
  5390. brand: spoolmanSpool.brand ?? null,
  5391. color_name: spoolmanSpool.color_name ?? null,
  5392. remainingWeightGrams: spoolmanSpool.label_weight
  5393. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5394. : undefined,
  5395. } : null,
  5396. onAssignSpool: () => setAssignSpoolModal({
  5397. printerId: printer.id,
  5398. amsId: 255,
  5399. trayId: slotTrayId,
  5400. trayInfo: {
  5401. type: extTray.tray_type || extFilamentData.profile,
  5402. material: extTray.tray_type ?? undefined,
  5403. profile: extFilamentData.profile,
  5404. color: extFilamentData.colorHex || '',
  5405. location: extLabel || t('printers.external'),
  5406. },
  5407. }),
  5408. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5409. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5410. };
  5411. }
  5412. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5413. return {
  5414. assignedSpool: assignment?.spool ? {
  5415. id: assignment.spool.id,
  5416. material: assignment.spool.material,
  5417. brand: assignment.spool.brand,
  5418. color_name: assignment.spool.color_name,
  5419. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5420. } : null,
  5421. onAssignSpool: () => setAssignSpoolModal({
  5422. printerId: printer.id,
  5423. amsId: 255,
  5424. trayId: slotTrayId,
  5425. trayInfo: {
  5426. type: extTray.tray_type || extFilamentData.profile,
  5427. material: extTray.tray_type ?? undefined,
  5428. profile: extFilamentData.profile,
  5429. color: extFilamentData.colorHex || '',
  5430. location: extLabel || t('printers.external'),
  5431. },
  5432. }),
  5433. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5434. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5435. };
  5436. })()}
  5437. configureSlot={{
  5438. enabled: hasPermission('printers:control'),
  5439. onConfigure: () => setConfigureSlotModal({
  5440. amsId: 255,
  5441. trayId: slotTrayId,
  5442. trayCount: 1,
  5443. trayType: extTray.tray_type || undefined,
  5444. trayColor: extTray.tray_color || undefined,
  5445. traySubBrands: extTray.tray_sub_brands || undefined,
  5446. trayInfoIdx: extTray.tray_info_idx || undefined,
  5447. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5448. caliIdx: extTray.cali_idx,
  5449. savedPresetId: extSlotPreset?.preset_id,
  5450. }),
  5451. }}
  5452. >
  5453. {extSlotContent}
  5454. </FilamentHoverCard>
  5455. ) : (
  5456. <EmptySlotHoverCard
  5457. kind={emptyKind ?? undefined}
  5458. actions={renderAmsSlotActions({
  5459. amsId: 255,
  5460. slotId: slotTrayId,
  5461. loadTrayId: extTrayId,
  5462. includeRfid: false,
  5463. })}
  5464. configureSlot={{
  5465. enabled: hasPermission('printers:control'),
  5466. onConfigure: () => setConfigureSlotModal({
  5467. amsId: 255,
  5468. trayId: slotTrayId,
  5469. trayCount: 1,
  5470. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5471. }),
  5472. }}
  5473. onAssignSpool={() => setAssignSpoolModal({
  5474. printerId: printer.id,
  5475. amsId: 255,
  5476. trayId: slotTrayId,
  5477. trayInfo: {
  5478. type: '',
  5479. material: undefined,
  5480. profile: '',
  5481. color: '',
  5482. location: `External Slot ${slotTrayId + 1}`,
  5483. },
  5484. })}
  5485. >
  5486. {extSlotContent}
  5487. </EmptySlotHoverCard>
  5488. )}
  5489. </div>
  5490. );
  5491. })}
  5492. </div>
  5493. </div>
  5494. )}
  5495. </div>
  5496. </div>
  5497. );
  5498. })()}
  5499. </>
  5500. )}
  5501. {/* Bottom block (power row + action bar). Wrapped together so the
  5502. power row hugs the action bar at the card bottom instead of
  5503. floating up when there's less filament content above. */}
  5504. {viewMode === 'expanded' && (
  5505. <div className="mt-auto">
  5506. {smartPlug && (
  5507. <div className="pt-3">
  5508. <div className="flex items-center gap-2 mb-2">
  5509. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5510. {t('printers.power', 'Power')}
  5511. </span>
  5512. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5513. </div>
  5514. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5515. {/* Plug name + current power */}
  5516. <div className="flex items-center gap-2 min-w-0 pl-1">
  5517. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5518. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5519. <span
  5520. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5521. title={t('smartPlugs.power')}
  5522. >
  5523. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5524. </span>
  5525. </div>
  5526. {/* Spacer */}
  5527. <div className="flex-1" />
  5528. <div className="flex items-center gap-2">
  5529. {/* Auto-off */}
  5530. <button
  5531. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5532. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5533. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5534. 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 ${
  5535. !hasPermission('smart_plugs:control')
  5536. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5537. : smartPlug.auto_off || smartPlug.auto_off_executed
  5538. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5539. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5540. }`}
  5541. >
  5542. <Clock className="w-4 h-4" />
  5543. </button>
  5544. <button
  5545. onClick={() => {
  5546. if (plugStatus?.state === 'ON') {
  5547. setShowPowerOffConfirm(true);
  5548. } else {
  5549. setShowPowerOnConfirm(true);
  5550. }
  5551. }}
  5552. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5553. 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 ${
  5554. !hasPermission('smart_plugs:control')
  5555. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5556. : plugStatus?.state === 'ON'
  5557. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5558. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5559. }`}
  5560. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5561. >
  5562. <Zap className="w-4 h-4" />
  5563. </button>
  5564. </div>
  5565. </div>
  5566. {/* HA entity buttons row */}
  5567. {scriptPlugs && scriptPlugs.length > 0 && (
  5568. <div className="flex items-center gap-2 mt-2">
  5569. <Home className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
  5570. <span className="text-xs text-bambu-gray">HA:</span>
  5571. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5572. <div className="flex flex-wrap gap-1">
  5573. {scriptPlugs.map(script => {
  5574. const isScript = script.ha_entity_id?.startsWith('script.');
  5575. return (
  5576. <button
  5577. key={script.id}
  5578. onClick={() => {
  5579. if (isScript) {
  5580. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5581. } else {
  5582. setHaToggleConfirm(script);
  5583. }
  5584. }}
  5585. disabled={runScriptMutation.isPending}
  5586. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5587. 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"
  5588. >
  5589. <Play className="w-2.5 h-2.5" />
  5590. {script.name}
  5591. </button>
  5592. );
  5593. })}
  5594. </div>
  5595. </div>
  5596. )}
  5597. </div>
  5598. )}
  5599. {/* Connection Info & Actions */}
  5600. <div className="pt-4">
  5601. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5602. <div className="flex items-center justify-between gap-2">
  5603. {printerActionsMenu}
  5604. <div className="flex items-center justify-end gap-2 flex-wrap">
  5605. {/* Camera Button */}
  5606. <Button
  5607. variant="secondary"
  5608. size="sm"
  5609. onClick={() => {
  5610. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5611. onOpenEmbeddedCamera(printer.id, printer.name);
  5612. } else {
  5613. // Use saved window state or defaults
  5614. const saved = localStorage.getItem('cameraWindowState');
  5615. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5616. const features = [
  5617. `width=${state.width}`,
  5618. `height=${state.height}`,
  5619. state.left !== undefined ? `left=${state.left}` : '',
  5620. state.top !== undefined ? `top=${state.top}` : '',
  5621. // No `noopener`: same-origin popup needs opener so the browser
  5622. // copies sessionStorage (auth token) into the new window.
  5623. 'menubar=no,toolbar=no,location=no,status=no',
  5624. ].filter(Boolean).join(',');
  5625. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5626. }
  5627. }}
  5628. disabled={!status?.connected || !hasPermission('camera:view')}
  5629. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5630. className={footerIconButtonClass}
  5631. >
  5632. <Video className="w-4 h-4" />
  5633. </Button>
  5634. <Button
  5635. variant="secondary"
  5636. size="sm"
  5637. onClick={() => setShowFileManager(true)}
  5638. disabled={!isConnected || !hasPermission('printers:files')}
  5639. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5640. className={footerIconButtonClass}
  5641. >
  5642. <HardDrive className="w-4 h-4" />
  5643. </Button>
  5644. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5645. <Button
  5646. size="sm"
  5647. onClick={() => setShowUploadForPrint(true)}
  5648. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  5649. title={
  5650. !hasPermission('library:upload')
  5651. ? t('fileManager.noPermissionUpload')
  5652. : !hasPermission('queue:create')
  5653. ? t('fileManager.noPermissionAddToQueue')
  5654. : t('common.print')
  5655. }
  5656. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5657. >
  5658. <PrinterIcon className="w-4 h-4" />
  5659. {t('common.print')}
  5660. </Button>
  5661. )}
  5662. </div>
  5663. </div>
  5664. </div>
  5665. </div>
  5666. )}
  5667. </CardContent>
  5668. {/* File Manager Modal */}
  5669. {showFileManager && (
  5670. <FileManagerModal
  5671. printerId={printer.id}
  5672. printerName={printer.name}
  5673. onClose={() => setShowFileManager(false)}
  5674. />
  5675. )}
  5676. {/* Upload for Print Modal */}
  5677. {showUploadForPrint && (
  5678. <FileUploadModal
  5679. folderId={null}
  5680. onClose={() => setShowUploadForPrint(false)}
  5681. onUploadComplete={() => {}}
  5682. autoUpload
  5683. accept=".gcode,.3mf"
  5684. validateFile={(file) => {
  5685. const lower = file.name.toLowerCase();
  5686. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5687. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5688. }
  5689. }}
  5690. onFileUploaded={(uploadedFile) => {
  5691. // Check printer compatibility if sliced_for_model is available in metadata
  5692. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5693. const printerModel = mapModelCode(printer.model);
  5694. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5695. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5696. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5697. }
  5698. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5699. }}
  5700. />
  5701. )}
  5702. {/* Print Modal (after upload) */}
  5703. {printAfterUpload && (
  5704. <PrintModal
  5705. mode="create"
  5706. libraryFileId={printAfterUpload.id}
  5707. archiveName={printAfterUpload.filename}
  5708. initialSelectedPrinterIds={[printer.id]}
  5709. onClose={() => setPrintAfterUpload(null)}
  5710. onSuccess={() => setPrintAfterUpload(null)}
  5711. cleanupLibraryAfterDispatch
  5712. />
  5713. )}
  5714. {/* MQTT Debug Modal */}
  5715. {showMQTTDebug && (
  5716. <MQTTDebugModal
  5717. printerId={printer.id}
  5718. printerName={printer.name}
  5719. onClose={() => setShowMQTTDebug(false)}
  5720. />
  5721. )}
  5722. {showDiagnostic && (
  5723. <ConnectionDiagnosticModal
  5724. printerId={printer.id}
  5725. printerName={printer.name}
  5726. onClose={() => setShowDiagnostic(false)}
  5727. />
  5728. )}
  5729. {showPrinterInfo && (
  5730. <PrinterInfoModal
  5731. printer={printer}
  5732. status={status}
  5733. totalPrintHours={maintenanceInfo?.total_print_hours}
  5734. onClose={closePrinterInfo}
  5735. />
  5736. )}
  5737. {/* Plate Check Result Modal */}
  5738. {plateCheckResult && (
  5739. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5740. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5741. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5742. <div className="flex items-center gap-2">
  5743. {plateCheckResult.needs_calibration ? (
  5744. <ScanSearch className="w-5 h-5 text-blue-500" />
  5745. ) : plateCheckResult.is_empty ? (
  5746. <CheckCircle className="w-5 h-5 text-green-500" />
  5747. ) : (
  5748. <XCircle className="w-5 h-5 text-yellow-500" />
  5749. )}
  5750. <h2 className="text-lg font-semibold text-white">
  5751. Build Plate Check
  5752. </h2>
  5753. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5754. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5755. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5756. </span>
  5757. )}
  5758. </div>
  5759. <button
  5760. onClick={() => closePlateCheckModal()}
  5761. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5762. >
  5763. <X className="w-5 h-5" />
  5764. </button>
  5765. </div>
  5766. <div className="p-4 space-y-4">
  5767. {plateCheckResult.needs_calibration ? (
  5768. <>
  5769. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  5770. <p className="font-medium text-blue-700 dark:text-blue-400">
  5771. {t('printers.plateDetection.calibrationRequired')}
  5772. </p>
  5773. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5774. </div>
  5775. <div className="text-sm text-bambu-gray space-y-2">
  5776. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5777. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5778. </div>
  5779. </>
  5780. ) : (
  5781. <>
  5782. <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'}`}>
  5783. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  5784. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5785. </p>
  5786. <p className="text-sm text-bambu-gray mt-1">
  5787. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5788. </p>
  5789. </div>
  5790. {plateCheckResult.debug_image_url && (
  5791. <div>
  5792. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5793. <img
  5794. src={plateCheckResult.debug_image_url}
  5795. alt={t('printers.plateDetection.analysisPreview')}
  5796. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5797. />
  5798. <p className="text-xs text-bambu-gray mt-2">
  5799. {t('printers.plateDetection.analysisLegend')}
  5800. </p>
  5801. </div>
  5802. )}
  5803. <p className="text-xs text-bambu-gray">
  5804. {plateCheckResult.message}
  5805. </p>
  5806. </>
  5807. )}
  5808. {/* Saved References Grid */}
  5809. {plateReferences && plateReferences.references.length > 0 && (
  5810. <div className="mt-4">
  5811. <div className="flex items-center gap-2 mb-2">
  5812. <p className="text-sm font-medium text-white shrink-0">
  5813. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5814. </p>
  5815. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5816. </div>
  5817. <div className="grid grid-cols-5 gap-2">
  5818. {plateReferences.references.map((ref) => (
  5819. <div key={ref.index} className="relative group">
  5820. <img
  5821. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5822. alt={ref.label || `Reference ${ref.index + 1}`}
  5823. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5824. />
  5825. {/* Delete button */}
  5826. <button
  5827. onClick={() => handleDeleteRef(ref.index)}
  5828. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5829. title={t('printers.plateDetection.deleteReference')}
  5830. >
  5831. <X className="w-3 h-3 text-white" />
  5832. </button>
  5833. {/* Label */}
  5834. {editingRefLabel?.index === ref.index ? (
  5835. <input
  5836. type="text"
  5837. value={editingRefLabel.label}
  5838. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5839. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5840. onKeyDown={(e) => {
  5841. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5842. if (e.key === 'Escape') setEditingRefLabel(null);
  5843. }}
  5844. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5845. autoFocus
  5846. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5847. />
  5848. ) : (
  5849. <p
  5850. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5851. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5852. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5853. >
  5854. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5855. </p>
  5856. )}
  5857. {/* Timestamp */}
  5858. <p className="text-[10px] text-bambu-gray/60">
  5859. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5860. </p>
  5861. </div>
  5862. ))}
  5863. </div>
  5864. </div>
  5865. )}
  5866. {/* ROI Editor */}
  5867. {!plateCheckResult.needs_calibration && (
  5868. <div className="mt-4">
  5869. <div className="flex items-center justify-between mb-2">
  5870. <div className="flex min-w-0 flex-1 items-center gap-2">
  5871. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5872. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5873. </div>
  5874. {!editingRoi ? (
  5875. <Button
  5876. variant="ghost"
  5877. size="sm"
  5878. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5879. >
  5880. <Pencil className="w-3 h-3 mr-1" />
  5881. {t('common.edit')}
  5882. </Button>
  5883. ) : (
  5884. <div className="flex gap-1">
  5885. <Button
  5886. variant="ghost"
  5887. size="sm"
  5888. onClick={() => setEditingRoi(null)}
  5889. disabled={isSavingRoi}
  5890. >
  5891. {t('common.cancel')}
  5892. </Button>
  5893. <Button
  5894. size="sm"
  5895. onClick={handleSaveRoi}
  5896. disabled={isSavingRoi}
  5897. >
  5898. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5899. </Button>
  5900. </div>
  5901. )}
  5902. </div>
  5903. {editingRoi ? (
  5904. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5905. <div className="grid grid-cols-2 gap-3">
  5906. <div>
  5907. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5908. <input
  5909. type="range"
  5910. min="0"
  5911. max="0.9"
  5912. step="0.01"
  5913. value={editingRoi.x}
  5914. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5915. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5916. />
  5917. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5918. </div>
  5919. <div>
  5920. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5921. <input
  5922. type="range"
  5923. min="0"
  5924. max="0.9"
  5925. step="0.01"
  5926. value={editingRoi.y}
  5927. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5928. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5929. />
  5930. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5931. </div>
  5932. <div>
  5933. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5934. <input
  5935. type="range"
  5936. min="0.1"
  5937. max="1"
  5938. step="0.01"
  5939. value={editingRoi.w}
  5940. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5941. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5942. />
  5943. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5944. </div>
  5945. <div>
  5946. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5947. <input
  5948. type="range"
  5949. min="0.1"
  5950. max="1"
  5951. step="0.01"
  5952. value={editingRoi.h}
  5953. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5954. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5955. />
  5956. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5957. </div>
  5958. </div>
  5959. <p className="text-xs text-bambu-gray">
  5960. {t('printers.roi.instruction')}
  5961. </p>
  5962. </div>
  5963. ) : (
  5964. <p className="text-xs text-bambu-gray">
  5965. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5966. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5967. </p>
  5968. )}
  5969. </div>
  5970. )}
  5971. </div>
  5972. <div className="flex justify-end gap-2 p-4">
  5973. {plateCheckResult.needs_calibration ? (
  5974. <>
  5975. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5976. {t('common.cancel')}
  5977. </Button>
  5978. <Button
  5979. onClick={() => handleCalibratePlate()}
  5980. disabled={isCalibrating}
  5981. >
  5982. {isCalibrating ? (
  5983. <>
  5984. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5985. Calibrating...
  5986. </>
  5987. ) : (
  5988. 'Calibrate Empty Plate'
  5989. )}
  5990. </Button>
  5991. </>
  5992. ) : (
  5993. <>
  5994. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5995. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5996. </Button>
  5997. <Button onClick={() => closePlateCheckModal()}>
  5998. Close
  5999. </Button>
  6000. </>
  6001. )}
  6002. </div>
  6003. </div>
  6004. </div>
  6005. )}
  6006. {/* Power On Confirmation */}
  6007. {showPowerOnConfirm && smartPlug && (
  6008. <ConfirmModal
  6009. title={t('printers.confirm.powerOnTitle')}
  6010. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6011. confirmText={t('printers.confirm.powerOnButton')}
  6012. variant="default"
  6013. onConfirm={() => {
  6014. powerControlMutation.mutate('on');
  6015. setShowPowerOnConfirm(false);
  6016. }}
  6017. onCancel={() => setShowPowerOnConfirm(false)}
  6018. />
  6019. )}
  6020. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6021. disconnects MQTT, which stops progress tracking + completion
  6022. notifications for the in-flight job. Idle / FINISH / FAILED states
  6023. skip this dialog and toggle directly. */}
  6024. {confirmMaintenanceEnter && (
  6025. <ConfirmModal
  6026. title={t('printers.maintenance.confirmMidPrintTitle')}
  6027. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6028. confirmText={t('printers.maintenance.menuEnter')}
  6029. variant="danger"
  6030. onConfirm={() => {
  6031. maintenanceMutation.mutate(false);
  6032. setConfirmMaintenanceEnter(false);
  6033. }}
  6034. onCancel={() => setConfirmMaintenanceEnter(false)}
  6035. />
  6036. )}
  6037. {/* Power Off Confirmation */}
  6038. {showPowerOffConfirm && smartPlug && (
  6039. <ConfirmModal
  6040. title={t('printers.confirm.powerOffTitle')}
  6041. message={
  6042. status?.state === 'RUNNING'
  6043. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6044. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6045. }
  6046. confirmText={t('printers.confirm.powerOffButton')}
  6047. variant="danger"
  6048. onConfirm={() => {
  6049. powerControlMutation.mutate('off');
  6050. setShowPowerOffConfirm(false);
  6051. }}
  6052. onCancel={() => setShowPowerOffConfirm(false)}
  6053. />
  6054. )}
  6055. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6056. {haToggleConfirm && (
  6057. <ConfirmModal
  6058. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6059. message={
  6060. status?.state === 'RUNNING'
  6061. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6062. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6063. }
  6064. confirmText={t('printers.confirm.haToggleButton')}
  6065. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6066. onConfirm={() => {
  6067. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6068. setHaToggleConfirm(null);
  6069. }}
  6070. onCancel={() => setHaToggleConfirm(null)}
  6071. />
  6072. )}
  6073. {/* Stop Print Confirmation */}
  6074. {showStopConfirm && (
  6075. <ConfirmModal
  6076. title={t('printers.confirm.stopTitle')}
  6077. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6078. confirmText={t('printers.confirm.stopButton')}
  6079. variant="danger"
  6080. onConfirm={() => {
  6081. stopPrintMutation.mutate();
  6082. setShowStopConfirm(false);
  6083. }}
  6084. onCancel={() => setShowStopConfirm(false)}
  6085. />
  6086. )}
  6087. {/* Pause Print Confirmation */}
  6088. {showPauseConfirm && (
  6089. <ConfirmModal
  6090. title={t('printers.confirm.pauseTitle')}
  6091. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6092. confirmText={t('printers.confirm.pauseButton')}
  6093. variant="default"
  6094. onConfirm={() => {
  6095. pausePrintMutation.mutate();
  6096. setShowPauseConfirm(false);
  6097. }}
  6098. onCancel={() => setShowPauseConfirm(false)}
  6099. />
  6100. )}
  6101. {/* Resume Print Confirmation */}
  6102. {showResumeConfirm && (
  6103. <ConfirmModal
  6104. title={t('printers.confirm.resumeTitle')}
  6105. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6106. confirmText={t('printers.confirm.resumeButton')}
  6107. variant="default"
  6108. onConfirm={() => {
  6109. resumePrintMutation.mutate();
  6110. setShowResumeConfirm(false);
  6111. }}
  6112. onCancel={() => setShowResumeConfirm(false)}
  6113. />
  6114. )}
  6115. {/* Skip Objects Modal */}
  6116. <SkipObjectsModal
  6117. printerId={printer.id}
  6118. isOpen={showSkipObjectsModal}
  6119. onClose={() => setShowSkipObjectsModal(false)}
  6120. />
  6121. {/* HMS Error Modal */}
  6122. {showHMSModal && (
  6123. <HMSErrorModal
  6124. printerName={printer.name}
  6125. errors={status?.hms_errors || []}
  6126. onClose={() => setShowHMSModal(false)}
  6127. printerId={printer.id}
  6128. hasPermission={hasPermission}
  6129. runoutGuidance={runoutGuidance}
  6130. />
  6131. )}
  6132. {/* AI failure detection modal (#1546) */}
  6133. {showAiModal && (
  6134. <AiDetectionModal
  6135. printerName={printer.name}
  6136. detection={aiDetection}
  6137. lastError={aiLastError}
  6138. onClose={() => setShowAiModal(false)}
  6139. />
  6140. )}
  6141. {/* AMS Filament Backup status / control modal (#1762) */}
  6142. {amsBackupModalOpen && status && (
  6143. <AmsBackupModal
  6144. isOpen={amsBackupModalOpen}
  6145. state={status.ams_filament_backup}
  6146. amsUnits={status.ams}
  6147. amsExtruderMap={status.ams_extruder_map}
  6148. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6149. canToggle={hasPermission('printers:control')}
  6150. pending={setAmsBackupMutation.isPending}
  6151. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6152. onClose={() => setAmsBackupModalOpen(false)}
  6153. />
  6154. )}
  6155. {/* AMS History Modal */}
  6156. {amsHistoryModal && (
  6157. <AMSHistoryModal
  6158. isOpen={!!amsHistoryModal}
  6159. onClose={() => setAmsHistoryModal(null)}
  6160. printerId={printer.id}
  6161. printerName={printer.name}
  6162. amsId={amsHistoryModal.amsId}
  6163. amsLabel={amsHistoryModal.amsLabel}
  6164. initialMode={amsHistoryModal.mode}
  6165. thresholds={amsThresholds}
  6166. />
  6167. )}
  6168. {/* Heater History Modal (nozzle / bed / chamber) */}
  6169. {heaterHistoryModal && (
  6170. <HeaterHistoryModal
  6171. isOpen={!!heaterHistoryModal}
  6172. onClose={() => setHeaterHistoryModal(null)}
  6173. printerId={printer.id}
  6174. printerName={printer.name}
  6175. initialKind={heaterHistoryModal.initialKind}
  6176. availableKinds={heaterHistoryModal.availableKinds}
  6177. />
  6178. )}
  6179. {/* Link Spool Modal */}
  6180. {linkSpoolModal && (
  6181. <LinkSpoolModal
  6182. isOpen={!!linkSpoolModal}
  6183. onClose={() => setLinkSpoolModal(null)}
  6184. tagUid={linkSpoolModal.tagUid}
  6185. trayUuid={linkSpoolModal.trayUuid}
  6186. printerId={linkSpoolModal.printerId}
  6187. amsId={linkSpoolModal.amsId}
  6188. trayId={linkSpoolModal.trayId}
  6189. />
  6190. )}
  6191. {/* Assign Spool Modal */}
  6192. {assignSpoolModal && (
  6193. <AssignSpoolModal
  6194. isOpen={!!assignSpoolModal}
  6195. onClose={() => setAssignSpoolModal(null)}
  6196. printerId={assignSpoolModal.printerId}
  6197. amsId={assignSpoolModal.amsId}
  6198. trayId={assignSpoolModal.trayId}
  6199. trayInfo={assignSpoolModal.trayInfo}
  6200. spoolmanEnabled={!!spoolmanEnabled}
  6201. />
  6202. )}
  6203. {/* Configure AMS Slot Modal */}
  6204. {configureSlotModal && (
  6205. <ConfigureAmsSlotModal
  6206. isOpen={!!configureSlotModal}
  6207. onClose={() => setConfigureSlotModal(null)}
  6208. printerId={printer.id}
  6209. slotInfo={configureSlotModal}
  6210. printerModel={mapModelCode(printer.model) || undefined}
  6211. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6212. onSuccess={() => {
  6213. // Refresh slot presets to show updated profile name
  6214. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6215. // Printer status will update automatically via WebSocket when AMS data changes
  6216. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6217. }}
  6218. />
  6219. )}
  6220. {/* Edit Printer Modal */}
  6221. {showEditModal && (
  6222. <EditPrinterModal
  6223. printer={printer}
  6224. onClose={() => setShowEditModal(false)}
  6225. />
  6226. )}
  6227. {/* Firmware Update Modal */}
  6228. {showFirmwareModal && firmwareInfo && (
  6229. <FirmwareUpdateModal
  6230. printer={printer}
  6231. firmwareInfo={firmwareInfo}
  6232. onClose={() => setShowFirmwareModal(false)}
  6233. />
  6234. )}
  6235. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6236. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6237. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6238. const sliderMin = 35;
  6239. const sliderMax = maxTemp + 10;
  6240. return (
  6241. <>
  6242. {/* Backdrop */}
  6243. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  6244. {/* Popover */}
  6245. <div
  6246. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6247. style={{
  6248. top: dryingPopoverPos.top,
  6249. left: dryingPopoverPos.left,
  6250. // Cap to the space between the popover's top and the bottom
  6251. // viewport margin (8px, matching computePopoverPosition's
  6252. // margin). When the popover is taller than that space — short
  6253. // viewport, landscape phone, zoomed-in — the body scrolls and
  6254. // the footer stays pinned, so the Start button is always
  6255. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6256. // Safari's bottom toolbar overlay doesn't clip the footer
  6257. // (#1669, iPhone 17 Safari).
  6258. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6259. }}
  6260. onClick={e => e.stopPropagation()}
  6261. >
  6262. {/* Header */}
  6263. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6264. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6265. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6266. </div>
  6267. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6268. {/* Body */}
  6269. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6270. {/* Filament type select */}
  6271. <div>
  6272. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6273. <ToolbarDropdown
  6274. value={dryingFilament}
  6275. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6276. onChange={fil => {
  6277. setDryingFilament(fil);
  6278. const preset = dryingPresets[fil];
  6279. if (preset) {
  6280. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6281. setDryingTemp(preset[key]);
  6282. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6283. }
  6284. }}
  6285. fullWidth
  6286. />
  6287. </div>
  6288. {/* Temperature */}
  6289. <div>
  6290. <div className="flex items-center justify-between mb-1">
  6291. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6292. <div className="flex items-center gap-1">
  6293. <input
  6294. type="number"
  6295. min={45}
  6296. max={maxTemp}
  6297. value={dryingTemp}
  6298. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6299. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6300. />
  6301. <span className="text-[10px] text-bambu-gray">°C</span>
  6302. </div>
  6303. </div>
  6304. <input
  6305. type="range"
  6306. min={sliderMin}
  6307. max={sliderMax}
  6308. value={dryingTemp}
  6309. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6310. className="w-full h-1 accent-bambu-green cursor-pointer"
  6311. />
  6312. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6313. <span>45°C</span>
  6314. <span>{maxTemp}°C</span>
  6315. </div>
  6316. </div>
  6317. {/* Duration */}
  6318. <div>
  6319. <div className="flex items-center justify-between mb-1">
  6320. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6321. <div className="flex items-center gap-1">
  6322. <input
  6323. type="number"
  6324. min={1}
  6325. max={24}
  6326. value={dryingDuration}
  6327. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6328. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6329. />
  6330. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6331. </div>
  6332. </div>
  6333. <input
  6334. type="range"
  6335. min={1}
  6336. max={24}
  6337. value={dryingDuration}
  6338. onChange={e => setDryingDuration(Number(e.target.value))}
  6339. className="w-full h-1 accent-bambu-green cursor-pointer"
  6340. />
  6341. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6342. <span>1h</span>
  6343. <span>24h</span>
  6344. </div>
  6345. </div>
  6346. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6347. filament threaded out into the feed tube. The whole AMS
  6348. rotates as one mechanism (all 4 spools turn together), so a
  6349. single loaded slot locks the entire unit. Bambu per-tray
  6350. `state`: 9 = empty, 10 = spool present but not loaded
  6351. (rotation possible), 11 = loaded into tube (rotation impossible).
  6352. Catches both mid-print (active feed) AND idle-with-threaded-
  6353. filament — the H2D's post-print state leaves filament in the
  6354. tube but tray_now resets to 255, which a tray_now-only check
  6355. would silently miss. */}
  6356. {(() => {
  6357. const targetAms = dryingPopoverAmsId !== null
  6358. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6359. : undefined;
  6360. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6361. tray => tray.state === 11,
  6362. );
  6363. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6364. return (
  6365. <button
  6366. type="button"
  6367. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6368. aria-pressed={rotateChecked}
  6369. disabled={trayLoadedInThisAms}
  6370. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6371. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6372. rotateChecked
  6373. ? 'bg-bambu-green border-bambu-green text-white'
  6374. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6375. }`}
  6376. >
  6377. {t('printers.drying.rotateTray')}
  6378. </button>
  6379. );
  6380. })()}
  6381. </div>
  6382. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6383. {/* Footer */}
  6384. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6385. <button
  6386. onClick={() => {
  6387. if (dryingPopoverAmsId !== null) {
  6388. // Clamp rotateTray off when any tray in this AMS is loaded into
  6389. // the tube — the rotate UI is disabled there, but the state may
  6390. // linger as `true` from a previous AMS, or a print may have
  6391. // started while the popover was open. Without this clamp the
  6392. // Start payload would carry rotate_tray=true and firmware would
  6393. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  6394. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  6395. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6396. tray => tray.state === 11,
  6397. );
  6398. startDryingMutation.mutate({
  6399. amsId: dryingPopoverAmsId,
  6400. temp: dryingTemp,
  6401. duration: dryingDuration,
  6402. filament: dryingFilament,
  6403. rotateTray: dryingRotateTray && !trayLoadedInThisAms,
  6404. });
  6405. }
  6406. }}
  6407. disabled={startDryingMutation.isPending}
  6408. data-testid="drying-start-confirm"
  6409. 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"
  6410. >
  6411. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6412. </button>
  6413. </div>
  6414. </div>
  6415. </>
  6416. );
  6417. })()}
  6418. </Card>
  6419. );
  6420. }
  6421. export function AddPrinterModal({
  6422. onClose,
  6423. onAdd,
  6424. existingSerials,
  6425. }: {
  6426. onClose: () => void;
  6427. onAdd: (data: PrinterCreate) => void;
  6428. existingSerials: string[];
  6429. }) {
  6430. const { t } = useTranslation();
  6431. const [form, setForm] = useState<PrinterCreate>({
  6432. name: '',
  6433. serial_number: '',
  6434. ip_address: '',
  6435. access_code: '',
  6436. model: '',
  6437. location: '',
  6438. auto_archive: true,
  6439. });
  6440. // Discovery state
  6441. const [discovering, setDiscovering] = useState(false);
  6442. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6443. const [discoveryError, setDiscoveryError] = useState('');
  6444. const [hasScanned, setHasScanned] = useState(false);
  6445. const [isDocker, setIsDocker] = useState(false);
  6446. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6447. const [subnet, setSubnet] = useState('');
  6448. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6449. // text input so users can scan a subnet Bambuddy isn't directly on
  6450. // (printer behind a router on a different L3 segment — SSDP multicast
  6451. // won't cross that boundary, only an active unicast scan will). #1564
  6452. const [customSubnet, setCustomSubnet] = useState('');
  6453. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6454. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6455. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6456. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6457. // (not block) when checks fail, so the user doesn't add a printer that
  6458. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6459. // failed result awaiting an explicit "save anyway".
  6460. const [checkingSave, setCheckingSave] = useState(false);
  6461. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6462. // Fetch discovery info on mount + restore the last custom CIDR the user
  6463. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6464. // time they open this modal).
  6465. useEffect(() => {
  6466. discoveryApi.getInfo().then(info => {
  6467. setIsDocker(info.is_docker);
  6468. if (info.subnets.length > 0) {
  6469. setDetectedSubnets(info.subnets);
  6470. setSubnet(info.subnets[0]);
  6471. }
  6472. }).catch(() => {
  6473. // Ignore errors, assume not Docker
  6474. });
  6475. try {
  6476. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6477. if (saved) setCustomSubnet(saved);
  6478. } catch {
  6479. // localStorage unavailable (private mode, quota); recall is opportunistic
  6480. }
  6481. }, []);
  6482. // Filter out already-added printers
  6483. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6484. const handleAddSubmit = async (e: React.FormEvent) => {
  6485. e.preventDefault();
  6486. setCheckingSave(true);
  6487. try {
  6488. const result = await api.diagnoseConnection({
  6489. ip_address: form.ip_address.trim(),
  6490. serial_number: form.serial_number.trim() || undefined,
  6491. access_code: form.access_code || undefined,
  6492. });
  6493. if (result.checks.some((c) => c.status === 'fail')) {
  6494. setSaveWarning(result);
  6495. return;
  6496. }
  6497. } catch {
  6498. // Diagnostic infrastructure failed — never block the save on it.
  6499. } finally {
  6500. setCheckingSave(false);
  6501. }
  6502. onAdd(form);
  6503. };
  6504. const startDiscovery = async () => {
  6505. setDiscoveryError('');
  6506. setDiscovered([]);
  6507. setDiscovering(true);
  6508. setHasScanned(false);
  6509. setScanProgress({ scanned: 0, total: 0 });
  6510. // Native installs fall back to subnet scanning when the user picks
  6511. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6512. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6513. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6514. const wantsSubnetScan = isDocker || useCustomSubnet;
  6515. if (wantsSubnetScan && useCustomSubnet) {
  6516. try {
  6517. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6518. } catch {
  6519. // localStorage write best-effort; user just retypes next time
  6520. }
  6521. }
  6522. try {
  6523. if (wantsSubnetScan) {
  6524. await discoveryApi.startSubnetScan(scanCidr);
  6525. // Poll for scan status and results
  6526. const pollInterval = setInterval(async () => {
  6527. try {
  6528. const status = await discoveryApi.getScanStatus();
  6529. setScanProgress({ scanned: status.scanned, total: status.total });
  6530. const printers = await discoveryApi.getDiscoveredPrinters();
  6531. setDiscovered(printers);
  6532. if (!status.running) {
  6533. clearInterval(pollInterval);
  6534. setDiscovering(false);
  6535. setHasScanned(true);
  6536. }
  6537. } catch (e) {
  6538. console.error('Failed to get scan status:', e);
  6539. }
  6540. }, 500);
  6541. } else {
  6542. // Use SSDP discovery for native installs
  6543. await discoveryApi.startDiscovery(10);
  6544. // Poll for discovered printers every second
  6545. const pollInterval = setInterval(async () => {
  6546. try {
  6547. const printers = await discoveryApi.getDiscoveredPrinters();
  6548. setDiscovered(printers);
  6549. } catch (e) {
  6550. console.error('Failed to get discovered printers:', e);
  6551. }
  6552. }, 1000);
  6553. // Stop after 10 seconds
  6554. setTimeout(async () => {
  6555. clearInterval(pollInterval);
  6556. try {
  6557. await discoveryApi.stopDiscovery();
  6558. } catch {
  6559. // Ignore stop errors
  6560. }
  6561. setDiscovering(false);
  6562. setHasScanned(true);
  6563. // Final fetch
  6564. try {
  6565. const printers = await discoveryApi.getDiscoveredPrinters();
  6566. setDiscovered(printers);
  6567. } catch (e) {
  6568. console.error('Failed to get final discovered printers:', e);
  6569. }
  6570. }, 10000);
  6571. }
  6572. } catch (e) {
  6573. console.error('Failed to start discovery:', e);
  6574. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6575. setDiscovering(false);
  6576. setHasScanned(true);
  6577. }
  6578. };
  6579. // Reuse module-level mapModelCode
  6580. const selectPrinter = (printer: DiscoveredPrinter) => {
  6581. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6582. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6583. setForm({
  6584. ...form,
  6585. name: printer.name || '',
  6586. serial_number: serialNumber,
  6587. ip_address: printer.ip_address,
  6588. model: mapModelCode(printer.model),
  6589. });
  6590. // Clear discovery results after selection
  6591. setDiscovered([]);
  6592. };
  6593. // Cleanup discovery on unmount
  6594. useEffect(() => {
  6595. return () => {
  6596. discoveryApi.stopDiscovery().catch(() => {});
  6597. discoveryApi.stopSubnetScan().catch(() => {});
  6598. };
  6599. }, []);
  6600. // Close on Escape key
  6601. useEffect(() => {
  6602. const handleKeyDown = (e: KeyboardEvent) => {
  6603. if (e.key === 'Escape') onClose();
  6604. };
  6605. window.addEventListener('keydown', handleKeyDown);
  6606. return () => window.removeEventListener('keydown', handleKeyDown);
  6607. }, [onClose]);
  6608. return (
  6609. <>
  6610. <div
  6611. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6612. onClick={onClose}
  6613. >
  6614. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6615. <CardContent>
  6616. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6617. {/* Discovery Section */}
  6618. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6619. {/* Subnet picker — always visible. The dropdown lists detected
  6620. interface subnets and a "Custom..." sentinel that reveals
  6621. a CIDR text input for printers on a different L3 segment
  6622. (router, VLAN, etc.). #1564 */}
  6623. <div className="mb-3">
  6624. <label className="block text-sm text-bambu-gray mb-1">
  6625. {t('printers.discovery.subnetToScan')}
  6626. </label>
  6627. {detectedSubnets.length > 0 ? (
  6628. <select
  6629. 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"
  6630. value={useCustomSubnet ? '__custom__' : subnet}
  6631. onChange={(e) => {
  6632. if (e.target.value === '__custom__') {
  6633. setUseCustomSubnet(true);
  6634. } else {
  6635. setUseCustomSubnet(false);
  6636. setSubnet(e.target.value);
  6637. }
  6638. }}
  6639. disabled={discovering}
  6640. >
  6641. {detectedSubnets.map(s => (
  6642. <option key={s} value={s}>{s}</option>
  6643. ))}
  6644. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6645. </select>
  6646. ) : (
  6647. <input
  6648. type="text"
  6649. 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"
  6650. value={subnet}
  6651. onChange={(e) => setSubnet(e.target.value)}
  6652. placeholder="192.168.1.0/24"
  6653. disabled={discovering}
  6654. />
  6655. )}
  6656. {useCustomSubnet && (
  6657. <input
  6658. type="text"
  6659. aria-label={t('printers.discovery.customSubnetLabel')}
  6660. 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"
  6661. value={customSubnet}
  6662. onChange={(e) => setCustomSubnet(e.target.value)}
  6663. placeholder="10.1.1.0/24"
  6664. disabled={discovering}
  6665. />
  6666. )}
  6667. <p className="mt-1 text-xs text-bambu-gray">
  6668. {isDocker
  6669. ? t('printers.discovery.dockerNote')
  6670. : t('printers.discovery.customSubnetNote')}
  6671. </p>
  6672. </div>
  6673. <Button
  6674. type="button"
  6675. variant="secondary"
  6676. onClick={startDiscovery}
  6677. disabled={discovering}
  6678. className="w-full"
  6679. >
  6680. {discovering ? (
  6681. <>
  6682. <Loader2 className="w-4 h-4 animate-spin" />
  6683. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6684. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6685. : t('printers.discovery.scanning')}
  6686. </>
  6687. ) : (
  6688. <>
  6689. <Search className="w-4 h-4" />
  6690. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6691. </>
  6692. )}
  6693. </Button>
  6694. {discoveryError && (
  6695. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  6696. )}
  6697. {newPrinters.length > 0 && (
  6698. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6699. {newPrinters.map((printer) => (
  6700. <div
  6701. key={printer.serial}
  6702. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6703. onClick={() => selectPrinter(printer)}
  6704. >
  6705. <div className="min-w-0 flex-1">
  6706. <p className="font-medium text-white text-sm truncate">
  6707. {printer.name || printer.serial}
  6708. </p>
  6709. <p className="text-xs text-bambu-gray truncate">
  6710. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6711. {printer.serial.startsWith('unknown-') && (
  6712. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6713. )}
  6714. </p>
  6715. </div>
  6716. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6717. </div>
  6718. ))}
  6719. </div>
  6720. )}
  6721. {discovering && (
  6722. <p className="mt-2 text-sm text-bambu-gray text-center">
  6723. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6724. </p>
  6725. )}
  6726. {hasScanned && !discovering && discovered.length === 0 && (
  6727. <p className="mt-2 text-sm text-bambu-gray text-center">
  6728. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6729. </p>
  6730. )}
  6731. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6732. <p className="mt-2 text-sm text-bambu-gray text-center">
  6733. {t('printers.discovery.allConfigured')}
  6734. </p>
  6735. )}
  6736. </div>
  6737. <form onSubmit={handleAddSubmit} className="space-y-4">
  6738. <div>
  6739. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6740. <input
  6741. type="text"
  6742. required
  6743. 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"
  6744. value={form.name}
  6745. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6746. placeholder={t('printers.modal.myPrinter')}
  6747. />
  6748. </div>
  6749. <div>
  6750. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6751. <input
  6752. type="text"
  6753. required
  6754. 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])?)*)"
  6755. 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"
  6756. value={form.ip_address}
  6757. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6758. placeholder="192.168.1.100 or printer.local"
  6759. />
  6760. </div>
  6761. <div>
  6762. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6763. <input
  6764. type="text"
  6765. required
  6766. 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"
  6767. value={form.serial_number}
  6768. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6769. placeholder="01P00A000000000"
  6770. />
  6771. </div>
  6772. <div>
  6773. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6774. <input
  6775. type="password"
  6776. required
  6777. 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"
  6778. value={form.access_code}
  6779. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6780. placeholder={t('printers.modal.fromPrinterSettings')}
  6781. />
  6782. </div>
  6783. <div>
  6784. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6785. <select
  6786. 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"
  6787. value={form.model || ''}
  6788. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6789. >
  6790. <option value="">{t('printers.modal.selectModel')}</option>
  6791. <optgroup label="A1 Series">
  6792. <option value="A1">A1</option>
  6793. <option value="A1 Mini">A1 Mini</option>
  6794. </optgroup>
  6795. <optgroup label="A2 Series">
  6796. <option value="A2L">A2L</option>
  6797. </optgroup>
  6798. <optgroup label="H2 Series">
  6799. <option value="H2C">H2C</option>
  6800. <option value="H2D">H2D</option>
  6801. <option value="H2D Pro">H2D Pro</option>
  6802. <option value="H2S">H2S</option>
  6803. </optgroup>
  6804. <optgroup label="P Series">
  6805. <option value="P1P">P1P</option>
  6806. <option value="P1S">P1S</option>
  6807. <option value="P2S">P2S</option>
  6808. </optgroup>
  6809. <optgroup label="X1 Series">
  6810. <option value="X1">X1</option>
  6811. <option value="X1C">X1 Carbon</option>
  6812. <option value="X1E">X1E</option>
  6813. </optgroup>
  6814. <optgroup label="X2 Series">
  6815. <option value="X2D">X2D</option>
  6816. </optgroup>
  6817. </select>
  6818. </div>
  6819. <div>
  6820. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6821. <input
  6822. type="text"
  6823. 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"
  6824. value={form.location || ''}
  6825. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6826. placeholder={t('printers.modal.locationPlaceholder')}
  6827. />
  6828. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6829. </div>
  6830. <div className="flex items-center gap-2">
  6831. <input
  6832. type="checkbox"
  6833. id="auto_archive"
  6834. checked={form.auto_archive}
  6835. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6836. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6837. />
  6838. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6839. {t('printers.modal.autoArchiveLabel')}
  6840. </label>
  6841. </div>
  6842. <button
  6843. type="button"
  6844. onClick={() => setShowDiagnostic(true)}
  6845. disabled={!form.ip_address.trim()}
  6846. 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"
  6847. >
  6848. <Stethoscope className="w-4 h-4" />
  6849. {t('diagnostic.runButton')}
  6850. </button>
  6851. {saveWarning ? (
  6852. <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">
  6853. <div className="flex items-start gap-2">
  6854. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  6855. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  6856. </div>
  6857. <DiagnosticChecklist result={saveWarning} />
  6858. <div className="flex gap-3">
  6859. <Button
  6860. type="button"
  6861. variant="secondary"
  6862. onClick={() => setSaveWarning(null)}
  6863. className="flex-1"
  6864. >
  6865. {t('printers.addPreflight.back')}
  6866. </Button>
  6867. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6868. {t('printers.addPreflight.saveAnyway')}
  6869. </Button>
  6870. </div>
  6871. </div>
  6872. ) : (
  6873. <div className="flex gap-3 pt-2">
  6874. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6875. {t('common.cancel')}
  6876. </Button>
  6877. <Button type="submit" disabled={checkingSave} className="flex-1">
  6878. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6879. </Button>
  6880. </div>
  6881. )}
  6882. </form>
  6883. </CardContent>
  6884. </Card>
  6885. </div>
  6886. {showDiagnostic && (
  6887. <ConnectionDiagnosticModal
  6888. connection={{
  6889. ip_address: form.ip_address.trim(),
  6890. serial_number: form.serial_number.trim() || undefined,
  6891. access_code: form.access_code || undefined,
  6892. }}
  6893. printerName={form.name || null}
  6894. onClose={() => setShowDiagnostic(false)}
  6895. />
  6896. )}
  6897. </>
  6898. );
  6899. }
  6900. function FirmwareUpdateModal({
  6901. printer,
  6902. firmwareInfo,
  6903. onClose,
  6904. }: {
  6905. printer: Printer;
  6906. firmwareInfo: FirmwareUpdateInfo;
  6907. onClose: () => void;
  6908. }) {
  6909. const { t } = useTranslation();
  6910. const queryClient = useQueryClient();
  6911. const { showToast } = useToast();
  6912. const { hasPermission } = useAuth();
  6913. const canUpdate = hasPermission('firmware:update');
  6914. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6915. const [isUploading, setIsUploading] = useState(false);
  6916. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6917. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6918. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6919. );
  6920. // Prepare check query — runs when a version is selected and user can update
  6921. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6922. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6923. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6924. staleTime: 30000,
  6925. enabled: !!selectedVersion && canUpdate && !isUploading,
  6926. });
  6927. // Start upload mutation
  6928. const uploadMutation = useMutation({
  6929. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6930. onSuccess: () => {
  6931. setIsUploading(true);
  6932. // Start polling for status
  6933. const interval = setInterval(async () => {
  6934. try {
  6935. const status = await firmwareApi.getUploadStatus(printer.id);
  6936. setUploadStatus(status);
  6937. if (status.status === 'complete' || status.status === 'error') {
  6938. clearInterval(interval);
  6939. setPollInterval(null);
  6940. setIsUploading(false);
  6941. if (status.status === 'complete') {
  6942. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6943. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6944. }
  6945. }
  6946. } catch {
  6947. // Ignore errors during polling
  6948. }
  6949. }, 2000);
  6950. setPollInterval(interval);
  6951. },
  6952. onError: (error: Error) => {
  6953. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6954. setIsUploading(false);
  6955. },
  6956. });
  6957. // Cleanup on unmount
  6958. useEffect(() => {
  6959. return () => {
  6960. if (pollInterval) clearInterval(pollInterval);
  6961. };
  6962. }, [pollInterval]);
  6963. const handleStartUpload = () => {
  6964. setUploadStatus(null);
  6965. uploadMutation.mutate();
  6966. };
  6967. return (
  6968. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6969. <Card className="w-full max-w-md mx-4">
  6970. <CardContent>
  6971. <div className="flex items-start gap-3 mb-4">
  6972. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6973. {firmwareInfo.update_available
  6974. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  6975. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6976. </div>
  6977. <div className="flex-1">
  6978. <h3 className="text-lg font-semibold text-white">
  6979. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6980. </h3>
  6981. <p className="text-sm text-bambu-gray mt-1">
  6982. {printer.name}
  6983. </p>
  6984. </div>
  6985. </div>
  6986. {/* Version Info */}
  6987. {(() => {
  6988. const selectedEntry = selectedVersion
  6989. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6990. : null;
  6991. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6992. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6993. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6994. return (
  6995. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6996. <div className="flex justify-between items-center text-sm">
  6997. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6998. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6999. {firmwareInfo.current_version || t('common.unknown')}
  7000. </span>
  7001. </div>
  7002. {showSecondLine && (
  7003. <div className="flex justify-between items-center text-sm mt-1">
  7004. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7005. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7006. </div>
  7007. )}
  7008. {displayNotes && (
  7009. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7010. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7011. {t('printers.firmwareModal.releaseNotes')}
  7012. </summary>
  7013. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7014. {displayNotes}
  7015. </div>
  7016. </details>
  7017. )}
  7018. </div>
  7019. );
  7020. })()}
  7021. {/* Available versions list */}
  7022. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7023. <div className="mb-4">
  7024. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7025. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7026. {firmwareInfo.available_versions.map((v) => {
  7027. const isCurrent = firmwareInfo.current_version === v.version;
  7028. const isSelected = selectedVersion === v.version;
  7029. const cmp = firmwareInfo.current_version
  7030. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7031. : 0;
  7032. const relLabel = isCurrent
  7033. ? t('printers.firmwareModal.currentBadge')
  7034. : cmp > 0
  7035. ? t('printers.firmwareModal.newerBadge')
  7036. : t('printers.firmwareModal.olderBadge');
  7037. const relClass = isCurrent
  7038. ? 'text-bambu-gray'
  7039. : cmp > 0
  7040. ? 'text-orange-700 dark:text-orange-400'
  7041. : 'text-blue-700 dark:text-blue-400';
  7042. return (
  7043. <button
  7044. key={v.version}
  7045. type="button"
  7046. disabled={!v.file_available || !canUpdate || isCurrent}
  7047. onClick={() => setSelectedVersion(v.version)}
  7048. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7049. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7050. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7051. >
  7052. <div className="flex items-center gap-2 min-w-0">
  7053. <span className="font-mono text-white">{v.version}</span>
  7054. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7055. </div>
  7056. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7057. isCurrent
  7058. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7059. : v.file_available
  7060. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7061. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7062. }`}>
  7063. {isCurrent
  7064. ? t('printers.firmwareModal.installed')
  7065. : v.file_available
  7066. ? t('printers.firmwareModal.usable')
  7067. : t('printers.firmwareModal.unavailable')}
  7068. </span>
  7069. </button>
  7070. );
  7071. })}
  7072. </div>
  7073. </div>
  7074. )}
  7075. {/* Status / Progress (only when a version is selected) */}
  7076. {!selectedVersion ? null : isPreparing ? (
  7077. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7078. <Loader2 className="w-4 h-4 animate-spin" />
  7079. {t('printers.firmwareModal.checkingPrereqs')}
  7080. </div>
  7081. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7082. <div className="mb-4">
  7083. {prepareInfo.can_proceed ? (
  7084. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7085. <Box className="w-4 h-4" />
  7086. {t('printers.firmwareModal.sdCardReady')}
  7087. </div>
  7088. ) : (
  7089. <div className="space-y-1">
  7090. {prepareInfo.errors.map((error, i) => (
  7091. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7092. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7093. {error}
  7094. </div>
  7095. ))}
  7096. </div>
  7097. )}
  7098. </div>
  7099. ) : null}
  7100. {/* Upload Progress */}
  7101. {(isUploading || uploadStatus) && uploadStatus && (
  7102. <div className="mb-4">
  7103. <div className="flex items-center justify-between text-sm mb-1">
  7104. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  7105. <span className="text-white">{uploadStatus.progress}%</span>
  7106. </div>
  7107. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  7108. <div
  7109. className={`h-2 rounded-full transition-all ${
  7110. uploadStatus.status === 'error' ? 'bg-status-error' :
  7111. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  7112. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  7113. style={{ width: `${uploadStatus.progress}%` }}
  7114. />
  7115. </div>
  7116. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  7117. {uploadStatus.error && (
  7118. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  7119. )}
  7120. </div>
  7121. )}
  7122. {/* Success Message */}
  7123. {uploadStatus?.status === 'complete' && (
  7124. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  7125. <p className="text-sm text-bambu-green font-medium mb-2">
  7126. {t('printers.firmwareModal.uploadedSuccess')}
  7127. </p>
  7128. <p className="text-xs text-bambu-gray">
  7129. {t('printers.firmwareModal.applyInstructions')}
  7130. </p>
  7131. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  7132. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  7133. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  7134. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  7135. <li>{t('printers.firmwareModal.step4')}</li>
  7136. </ol>
  7137. </div>
  7138. )}
  7139. {/* Buttons */}
  7140. <div className="flex gap-2 justify-end">
  7141. <Button variant="secondary" onClick={onClose}>
  7142. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  7143. </Button>
  7144. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  7145. <Button
  7146. onClick={handleStartUpload}
  7147. disabled={uploadMutation.isPending}
  7148. >
  7149. {uploadMutation.isPending ? (
  7150. <>
  7151. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  7152. {t('printers.firmwareModal.starting')}
  7153. </>
  7154. ) : (
  7155. <>
  7156. <Download className="w-4 h-4 mr-2" />
  7157. {t('printers.firmwareModal.uploadFirmware')}
  7158. </>
  7159. )}
  7160. </Button>
  7161. )}
  7162. </div>
  7163. </CardContent>
  7164. </Card>
  7165. </div>
  7166. );
  7167. }
  7168. function EditPrinterModal({
  7169. printer,
  7170. onClose,
  7171. }: {
  7172. printer: Printer;
  7173. onClose: () => void;
  7174. }) {
  7175. const { t } = useTranslation();
  7176. const queryClient = useQueryClient();
  7177. const { showToast } = useToast();
  7178. const [form, setForm] = useState({
  7179. name: printer.name,
  7180. ip_address: printer.ip_address,
  7181. access_code: '',
  7182. model: printer.model || '',
  7183. location: printer.location || '',
  7184. auto_archive: printer.auto_archive,
  7185. is_active: printer.is_active,
  7186. });
  7187. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7188. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7189. const [checkingSave, setCheckingSave] = useState(false);
  7190. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7191. const updateMutation = useMutation({
  7192. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7193. onSuccess: () => {
  7194. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7195. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7196. onClose();
  7197. },
  7198. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7199. });
  7200. // Close on Escape key
  7201. useEffect(() => {
  7202. const handleKeyDown = (e: KeyboardEvent) => {
  7203. if (e.key === 'Escape') onClose();
  7204. };
  7205. window.addEventListener('keydown', handleKeyDown);
  7206. return () => window.removeEventListener('keydown', handleKeyDown);
  7207. }, [onClose]);
  7208. const doSave = () => {
  7209. const data: Partial<PrinterCreate> = {
  7210. name: form.name,
  7211. ip_address: form.ip_address,
  7212. model: form.model || undefined,
  7213. location: form.location || undefined,
  7214. auto_archive: form.auto_archive,
  7215. is_active: form.is_active,
  7216. };
  7217. // Only include access_code if it was changed
  7218. if (form.access_code) {
  7219. data.access_code = form.access_code;
  7220. }
  7221. updateMutation.mutate(data);
  7222. };
  7223. const handleSubmit = async (e: React.FormEvent) => {
  7224. e.preventDefault();
  7225. setCheckingSave(true);
  7226. try {
  7227. const result = await api.diagnoseConnection({
  7228. ip_address: form.ip_address.trim(),
  7229. serial_number: printer.serial_number,
  7230. access_code: form.access_code || undefined,
  7231. });
  7232. if (result.checks.some((c) => c.status === 'fail')) {
  7233. setSaveWarning(result);
  7234. return;
  7235. }
  7236. } catch {
  7237. // Diagnostic infrastructure failed — never block the save on it.
  7238. } finally {
  7239. setCheckingSave(false);
  7240. }
  7241. doSave();
  7242. };
  7243. return (
  7244. <div
  7245. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7246. onClick={onClose}
  7247. >
  7248. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7249. <CardContent>
  7250. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7251. <form onSubmit={handleSubmit} className="space-y-4">
  7252. <div>
  7253. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7254. <input
  7255. type="text"
  7256. required
  7257. 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"
  7258. value={form.name}
  7259. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7260. placeholder={t('printers.modal.myPrinter')}
  7261. />
  7262. </div>
  7263. <div>
  7264. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7265. <input
  7266. type="text"
  7267. required
  7268. 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])?)*)"
  7269. 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"
  7270. value={form.ip_address}
  7271. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7272. placeholder="192.168.1.100 or printer.local"
  7273. />
  7274. </div>
  7275. <div>
  7276. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7277. <input
  7278. type="text"
  7279. disabled
  7280. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7281. value={printer.serial_number}
  7282. />
  7283. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7284. </div>
  7285. <div>
  7286. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7287. <input
  7288. type="password"
  7289. 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"
  7290. value={form.access_code}
  7291. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7292. placeholder={t('printers.accessCodePlaceholder')}
  7293. />
  7294. </div>
  7295. <div>
  7296. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7297. <select
  7298. 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"
  7299. value={form.model}
  7300. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7301. >
  7302. <option value="">{t('printers.modal.selectModel')}</option>
  7303. <optgroup label="A1 Series">
  7304. <option value="A1">A1</option>
  7305. <option value="A1 Mini">A1 Mini</option>
  7306. </optgroup>
  7307. <optgroup label="A2 Series">
  7308. <option value="A2L">A2L</option>
  7309. </optgroup>
  7310. <optgroup label="H2 Series">
  7311. <option value="H2C">H2C</option>
  7312. <option value="H2D">H2D</option>
  7313. <option value="H2D Pro">H2D Pro</option>
  7314. <option value="H2S">H2S</option>
  7315. </optgroup>
  7316. <optgroup label="P Series">
  7317. <option value="P1P">P1P</option>
  7318. <option value="P1S">P1S</option>
  7319. <option value="P2S">P2S</option>
  7320. </optgroup>
  7321. <optgroup label="X1 Series">
  7322. <option value="X1">X1</option>
  7323. <option value="X1C">X1 Carbon</option>
  7324. <option value="X1E">X1E</option>
  7325. </optgroup>
  7326. <optgroup label="X2 Series">
  7327. <option value="X2D">X2D</option>
  7328. </optgroup>
  7329. </select>
  7330. </div>
  7331. <div>
  7332. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7333. <input
  7334. type="text"
  7335. 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"
  7336. value={form.location}
  7337. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7338. placeholder={t('printers.modal.locationPlaceholder')}
  7339. />
  7340. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7341. </div>
  7342. <div className="flex items-center gap-2">
  7343. <input
  7344. type="checkbox"
  7345. id="edit_auto_archive"
  7346. checked={form.auto_archive}
  7347. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7348. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7349. />
  7350. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7351. {t('printers.modal.autoArchiveLabel')}
  7352. </label>
  7353. </div>
  7354. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7355. is_active because the user-facing concept is "is this printer
  7356. in maintenance" not "is it active". */}
  7357. <div>
  7358. <div className="flex items-center gap-2">
  7359. <input
  7360. type="checkbox"
  7361. id="edit_maintenance_mode"
  7362. checked={!form.is_active}
  7363. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7364. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7365. />
  7366. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7367. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  7368. {t('printers.maintenance.editFieldLabel')}
  7369. </label>
  7370. </div>
  7371. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7372. {t('printers.maintenance.editFieldHelp')}
  7373. </p>
  7374. </div>
  7375. {saveWarning ? (
  7376. <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">
  7377. <div className="flex items-start gap-2">
  7378. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7379. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7380. </div>
  7381. <DiagnosticChecklist result={saveWarning} />
  7382. <div className="flex gap-3">
  7383. <Button
  7384. type="button"
  7385. variant="secondary"
  7386. onClick={() => setSaveWarning(null)}
  7387. className="flex-1"
  7388. >
  7389. {t('printers.addPreflight.back')}
  7390. </Button>
  7391. <Button
  7392. type="button"
  7393. onClick={doSave}
  7394. className="flex-1"
  7395. disabled={updateMutation.isPending}
  7396. >
  7397. {t('printers.addPreflight.saveAnyway')}
  7398. </Button>
  7399. </div>
  7400. </div>
  7401. ) : (
  7402. <div className="flex gap-3 pt-4">
  7403. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7404. {t('common.cancel')}
  7405. </Button>
  7406. <Button
  7407. type="submit"
  7408. className="flex-1"
  7409. disabled={updateMutation.isPending || checkingSave}
  7410. >
  7411. {checkingSave
  7412. ? t('printers.addPreflight.checking')
  7413. : updateMutation.isPending
  7414. ? t('common.saving')
  7415. : t('printers.modal.saveChanges')}
  7416. </Button>
  7417. </div>
  7418. )}
  7419. </form>
  7420. </CardContent>
  7421. </Card>
  7422. </div>
  7423. );
  7424. }
  7425. // Component to check if a printer is offline (for power dropdown)
  7426. function usePrinterOfflineStatus(printerId: number) {
  7427. const { data: status } = useQuery({
  7428. queryKey: ['printerStatus', printerId],
  7429. queryFn: () => api.getPrinterStatus(printerId),
  7430. refetchInterval: 30000,
  7431. });
  7432. return !status?.connected;
  7433. }
  7434. // Power dropdown item for an offline printer
  7435. function PowerDropdownItem({
  7436. printer,
  7437. plug,
  7438. onPowerOn,
  7439. isPowering,
  7440. }: {
  7441. printer: Printer;
  7442. plug: { id: number; name: string };
  7443. onPowerOn: (plugId: number) => void;
  7444. isPowering: boolean;
  7445. }) {
  7446. const isOffline = usePrinterOfflineStatus(printer.id);
  7447. // Fetch plug status
  7448. const { data: plugStatus } = useQuery({
  7449. queryKey: ['smartPlugStatus', plug.id],
  7450. queryFn: () => api.getSmartPlugStatus(plug.id),
  7451. refetchInterval: 10000,
  7452. });
  7453. // Only show if printer is offline
  7454. if (!isOffline) {
  7455. return null;
  7456. }
  7457. return (
  7458. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7459. <div className="flex items-center gap-2 min-w-0">
  7460. <span className="text-sm text-white truncate">{printer.name}</span>
  7461. {plugStatus && (
  7462. <span
  7463. className={`text-xs px-1.5 py-0.5 rounded ${
  7464. plugStatus.state === 'ON'
  7465. ? 'bg-bambu-green/20 text-bambu-green'
  7466. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  7467. }`}
  7468. >
  7469. {plugStatus.state || '?'}
  7470. </span>
  7471. )}
  7472. </div>
  7473. <button
  7474. onClick={() => onPowerOn(plug.id)}
  7475. disabled={isPowering || plugStatus?.state === 'ON'}
  7476. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7477. plugStatus?.state === 'ON'
  7478. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7479. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7480. }`}
  7481. >
  7482. <Power className="w-3 h-3" />
  7483. {isPowering ? '...' : 'On'}
  7484. </button>
  7485. </div>
  7486. );
  7487. }
  7488. export function PrintersPage() {
  7489. const { t } = useTranslation();
  7490. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7491. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7492. const accentButtonClass = {
  7493. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7494. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7495. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7496. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7497. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7498. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7499. }[activeAccent];
  7500. const [showAddModal, setShowAddModal] = useState(false);
  7501. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7502. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7503. });
  7504. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7505. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7506. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7507. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7508. });
  7509. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7510. return localStorage.getItem('printerSortAsc') !== 'false';
  7511. });
  7512. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7513. const [cardSize, setCardSize] = useState<number>(() => {
  7514. const saved = localStorage.getItem('printerCardSize');
  7515. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7516. });
  7517. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  7518. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  7519. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  7520. });
  7521. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  7522. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  7523. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  7524. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  7525. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  7526. });
  7527. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  7528. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  7529. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  7530. });
  7531. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  7532. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  7533. // Defaulting to 'full' because the cards already show this info — users who
  7534. // pick cam-wall view still want to glance the same details without flipping.
  7535. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  7536. const saved = localStorage.getItem('camWallStatusMode');
  7537. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  7538. });
  7539. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7540. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7541. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7542. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7543. requestAnimationFrame(() => {
  7544. requestAnimationFrame(() => {
  7545. const card = document.getElementById(`printer-card-${printerId}`);
  7546. if (!card) return;
  7547. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7548. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7549. window.scrollTo({
  7550. top: Math.max(0, top),
  7551. behavior: 'smooth',
  7552. });
  7553. });
  7554. });
  7555. }, []);
  7556. const openCompactCard = useCallback((printerId: number) => {
  7557. setCompactDrilldownPrinterId(printerId);
  7558. setCardSize(2);
  7559. localStorage.setItem('printerCardSize', '2');
  7560. scrollPrinterIntoView(printerId);
  7561. }, [scrollPrinterIntoView]);
  7562. const returnToCompactCards = useCallback(() => {
  7563. const printerId = compactDrilldownPrinterId;
  7564. setCompactDrilldownPrinterId(null);
  7565. setCardSize(1);
  7566. localStorage.setItem('printerCardSize', '1');
  7567. if (printerId != null) {
  7568. scrollPrinterIntoView(printerId);
  7569. }
  7570. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7571. const [search, setSearch] = useState('');
  7572. const [statusFilter, setStatusFilter] = useState<string>('all');
  7573. const [locationFilter, setLocationFilter] = useState<string>('all');
  7574. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7575. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7576. try {
  7577. const saved = localStorage.getItem('printerCollapsedSections');
  7578. return saved ? JSON.parse(saved) : {};
  7579. } catch { return {}; }
  7580. });
  7581. const queryClient = useQueryClient();
  7582. const { showToast } = useToast();
  7583. const { hasPermission } = useAuth();
  7584. // Embedded camera viewer state - supports multiple simultaneous viewers
  7585. // Persisted to localStorage so cameras reopen after navigation
  7586. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7587. // Initialize from localStorage if camera_view_mode is embedded
  7588. const saved = localStorage.getItem('openEmbeddedCameras');
  7589. if (saved) {
  7590. try {
  7591. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7592. return new Map(cameras.map(c => [c.id, c]));
  7593. } catch {
  7594. return new Map();
  7595. }
  7596. }
  7597. return new Map();
  7598. });
  7599. // Persist open cameras to localStorage when they change
  7600. useEffect(() => {
  7601. const cameras = Array.from(embeddedCameraPrinters.values());
  7602. if (cameras.length > 0) {
  7603. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7604. } else {
  7605. localStorage.removeItem('openEmbeddedCameras');
  7606. }
  7607. }, [embeddedCameraPrinters]);
  7608. const { data: printers, isLoading } = useQuery({
  7609. queryKey: ['printers'],
  7610. queryFn: api.getPrinters,
  7611. });
  7612. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7613. // so users with printers:read but no settings:read still get the values needed
  7614. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7615. const { data: settings } = useQuery({
  7616. queryKey: ['ui-preferences'],
  7617. queryFn: api.getUiPreferences,
  7618. });
  7619. // Parse user-configured temperature/fan presets once, with defensive fallback
  7620. // to built-in defaults on parse failure (validators on the backend already
  7621. // reject malformed writes, so this is just forward-compat).
  7622. const effectiveNozzleTempPresets = useMemo(
  7623. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7624. [settings?.nozzle_temp_presets],
  7625. );
  7626. const effectiveBedTempPresets = useMemo(
  7627. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7628. [settings?.bed_temp_presets],
  7629. );
  7630. const effectiveChamberTempPresets = useMemo(
  7631. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  7632. [settings?.chamber_temp_presets],
  7633. );
  7634. const effectiveFanSpeedPresets = useMemo(
  7635. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7636. [settings?.fan_speed_presets],
  7637. );
  7638. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7639. const effectiveDryingPresets = useMemo(() => {
  7640. if (settings?.drying_presets) {
  7641. try {
  7642. const userPresets = JSON.parse(settings.drying_presets);
  7643. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7644. return { ...DRYING_PRESETS, ...userPresets };
  7645. }
  7646. } catch { /* ignore parse errors, use defaults */ }
  7647. }
  7648. return DRYING_PRESETS;
  7649. }, [settings?.drying_presets]);
  7650. // Close embedded cameras if mode changes to 'window'
  7651. useEffect(() => {
  7652. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7653. setEmbeddedCameraPrinters(new Map());
  7654. }
  7655. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7656. // Fetch all smart plugs to know which printers have them
  7657. const { data: smartPlugs } = useQuery({
  7658. queryKey: ['smart-plugs'],
  7659. queryFn: api.getSmartPlugs,
  7660. });
  7661. // Fetch maintenance overview for all printers to show badges
  7662. const { data: maintenanceOverview } = useQuery({
  7663. queryKey: ['maintenanceOverview'],
  7664. queryFn: api.getMaintenanceOverview,
  7665. staleTime: 60 * 1000, // 1 minute
  7666. });
  7667. // Live AI failure detection state for the card badges (#1546). Matches the
  7668. // 10s refetch of the Failure Detection settings panel.
  7669. const { data: obicoPrinterStatus } = useQuery({
  7670. queryKey: ['obico-printer-status'],
  7671. queryFn: api.getObicoPrinterStatus,
  7672. refetchInterval: 10000,
  7673. });
  7674. // Badge visibility: detection enabled AND this printer in the monitored set
  7675. // (monitored_printers null = all). Live per-print state is passed separately.
  7676. const isAiMonitored = useCallback(
  7677. (printerId: number) =>
  7678. obicoPrinterStatus?.enabled === true &&
  7679. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  7680. [obicoPrinterStatus],
  7681. );
  7682. // Fetch Spoolman status to enable link spool feature
  7683. const { data: spoolmanStatus } = useQuery({
  7684. queryKey: ['spoolman-status'],
  7685. queryFn: api.getSpoolmanStatus,
  7686. staleTime: 60 * 1000, // 1 minute
  7687. });
  7688. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7689. // Fetch Spoolman settings to get sync mode
  7690. const { data: spoolmanSettings } = useQuery({
  7691. queryKey: ['spoolman-settings'],
  7692. queryFn: api.getSpoolmanSettings,
  7693. enabled: !!spoolmanEnabled,
  7694. staleTime: 60 * 1000, // 1 minute
  7695. });
  7696. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7697. // Fetch unlinked spools to know if link button should be enabled
  7698. const { data: unlinkedSpools } = useQuery({
  7699. queryKey: ['unlinked-spools'],
  7700. queryFn: api.getUnlinkedSpools,
  7701. enabled: !!spoolmanEnabled,
  7702. staleTime: 30 * 1000, // 30 seconds
  7703. });
  7704. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7705. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7706. const { data: linkedSpoolsData } = useQuery({
  7707. queryKey: ['linked-spools'],
  7708. queryFn: api.getLinkedSpools,
  7709. enabled: !!spoolmanEnabled,
  7710. staleTime: 30 * 1000, // 30 seconds
  7711. });
  7712. const linkedSpools = linkedSpoolsData?.linked;
  7713. // Fetch spool assignments for inventory feature
  7714. const { data: spoolAssignments } = useQuery({
  7715. queryKey: ['spool-assignments'],
  7716. queryFn: () => api.getAssignments(),
  7717. enabled: hasPermission('inventory:view_assignments'),
  7718. staleTime: 30 * 1000,
  7719. });
  7720. const unassignMutation = useMutation({
  7721. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7722. api.unassignSpool(printerId, amsId, trayId),
  7723. onSuccess: () => {
  7724. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7725. },
  7726. });
  7727. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7728. queryKey: ['spoolman-inventory-spools'],
  7729. queryFn: () => api.getSpoolmanInventorySpools(false),
  7730. enabled: !!spoolmanEnabled,
  7731. staleTime: 30 * 1000,
  7732. });
  7733. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7734. queryKey: ['spoolman-slot-assignments'],
  7735. queryFn: () => api.getSpoolmanSlotAssignments(),
  7736. enabled: !!spoolmanEnabled,
  7737. staleTime: 30 * 1000,
  7738. });
  7739. const unassignSpoolmanMutation = useMutation({
  7740. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7741. onSuccess: () => {
  7742. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7743. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7744. },
  7745. });
  7746. // Helper to find assignment for a specific slot
  7747. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7748. return spoolAssignments?.find(
  7749. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7750. );
  7751. };
  7752. // Create a map of printer_id -> maintenance info for quick lookup
  7753. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7754. (acc, overview) => {
  7755. acc[overview.printer_id] = {
  7756. due_count: overview.due_count,
  7757. warning_count: overview.warning_count,
  7758. total_print_hours: overview.total_print_hours,
  7759. };
  7760. return acc;
  7761. },
  7762. {} as Record<number, PrinterMaintenanceInfo>
  7763. ) || {};
  7764. // Create a map of printer_id -> smart plug
  7765. const smartPlugByPrinter = smartPlugs?.reduce(
  7766. (acc, plug) => {
  7767. if (plug.printer_id) {
  7768. acc[plug.printer_id] = plug;
  7769. }
  7770. return acc;
  7771. },
  7772. {} as Record<number, typeof smartPlugs[0]>
  7773. ) || {};
  7774. const addMutation = useMutation({
  7775. mutationFn: api.createPrinter,
  7776. onSuccess: () => {
  7777. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7778. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7779. setShowAddModal(false);
  7780. },
  7781. onError: (error: Error) => {
  7782. // Localized message when the backend returns a stable error code;
  7783. // the raw message is an English fallback for non-UI clients.
  7784. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7785. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7786. return;
  7787. }
  7788. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7789. },
  7790. });
  7791. const powerOnMutation = useMutation({
  7792. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7793. onSuccess: () => {
  7794. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7795. setPoweringOn(null);
  7796. },
  7797. onError: () => {
  7798. setPoweringOn(null);
  7799. },
  7800. });
  7801. // Bulk selection state
  7802. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7803. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7804. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7805. const [bulkActionPending, setBulkActionPending] = useState(false);
  7806. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7807. const toggleSelect = useCallback((id: number) => {
  7808. setSelectedPrinterIds(prev => {
  7809. const next = new Set(prev);
  7810. if (next.has(id)) next.delete(id);
  7811. else next.add(id);
  7812. return next;
  7813. });
  7814. }, []);
  7815. const clearSelection = useCallback(() => {
  7816. setSelectedPrinterIds(new Set());
  7817. setIsSelectionMode(false);
  7818. }, []);
  7819. // Escape key exits selection mode
  7820. useEffect(() => {
  7821. const handleKeyDown = (e: KeyboardEvent) => {
  7822. if (e.key === 'Escape' && selectionMode) {
  7823. clearSelection();
  7824. }
  7825. };
  7826. window.addEventListener('keydown', handleKeyDown);
  7827. return () => window.removeEventListener('keydown', handleKeyDown);
  7828. }, [selectionMode, clearSelection]);
  7829. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7830. setBulkActionPending(true);
  7831. const ids = Array.from(selectedPrinterIds);
  7832. // Filter to only applicable printers based on cached state
  7833. const applicableIds = ids.filter(id => {
  7834. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7835. if (!status?.connected) return false;
  7836. switch (action) {
  7837. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7838. case 'pause': return status.state === 'RUNNING';
  7839. case 'resume': return status.state === 'PAUSE';
  7840. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7841. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7842. default: return false;
  7843. }
  7844. });
  7845. if (applicableIds.length === 0) {
  7846. showToast(t('printers.bulk.noneApplicable'), 'error');
  7847. setBulkActionPending(false);
  7848. setBulkConfirmAction(null);
  7849. return;
  7850. }
  7851. const apiCall = {
  7852. stop: api.stopPrint,
  7853. pause: api.pausePrint,
  7854. resume: api.resumePrint,
  7855. clearPlate: api.clearPlate,
  7856. clearHMS: api.clearHMSErrors,
  7857. }[action];
  7858. const results = await Promise.allSettled(
  7859. applicableIds.map(id => apiCall(id))
  7860. );
  7861. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7862. const failed = results.filter(r => r.status === 'rejected').length;
  7863. if (failed === 0) {
  7864. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7865. } else {
  7866. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7867. }
  7868. // Invalidate status queries for affected printers
  7869. applicableIds.forEach(id => {
  7870. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7871. });
  7872. setBulkActionPending(false);
  7873. setBulkConfirmAction(null);
  7874. }, [selectedPrinterIds, queryClient, showToast, t]);
  7875. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7876. // Actions that need confirmation
  7877. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7878. setBulkConfirmAction(action);
  7879. } else {
  7880. executeBulkAction(action);
  7881. }
  7882. }, [executeBulkAction]);
  7883. const toggleHideDisconnected = () => {
  7884. const newValue = !hideDisconnected;
  7885. setHideDisconnected(newValue);
  7886. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7887. };
  7888. const handleSortChange = (newSort: SortOption) => {
  7889. setSortBy(newSort);
  7890. localStorage.setItem('printerSortBy', newSort);
  7891. };
  7892. const toggleSortDirection = () => {
  7893. const newAsc = !sortAsc;
  7894. setSortAsc(newAsc);
  7895. localStorage.setItem('printerSortAsc', String(newAsc));
  7896. };
  7897. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7898. const getGridClasses = () => {
  7899. switch (cardSize) {
  7900. 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
  7901. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7902. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7903. case 4: return 'grid-cols-1'; // XL: single column, full width
  7904. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7905. }
  7906. };
  7907. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7908. // Increment version counter whenever a printer status cache entry is updated so
  7909. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7910. useEffect(() => {
  7911. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7912. if (
  7913. event.type === 'updated' &&
  7914. Array.isArray(event.query.queryKey) &&
  7915. event.query.queryKey[0] === 'printerStatus'
  7916. ) {
  7917. setStatusCacheVersion(v => v + 1);
  7918. }
  7919. });
  7920. return unsubscribe;
  7921. }, [queryClient]);
  7922. // Filter printers by search term, status, and location
  7923. const filteredPrinters = useMemo(() => {
  7924. if (!printers) return [];
  7925. let result = printers;
  7926. // Text search
  7927. if (search.trim()) {
  7928. const q = search.trim().toLowerCase();
  7929. result = result.filter(p =>
  7930. p.name.toLowerCase().includes(q) ||
  7931. (p.model || '').toLowerCase().includes(q) ||
  7932. (p.location || '').toLowerCase().includes(q) ||
  7933. (p.serial_number || '').toLowerCase().includes(q)
  7934. );
  7935. }
  7936. // Location filter
  7937. if (locationFilter !== 'all') {
  7938. result = result.filter(p => (p.location || '') === locationFilter);
  7939. }
  7940. // Status filter
  7941. if (statusFilter !== 'all') {
  7942. result = result.filter(p => {
  7943. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7944. if (!status?.connected) return statusFilter === 'offline';
  7945. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7946. switch (statusFilter) {
  7947. case 'printing': return status.state === 'RUNNING';
  7948. case 'paused': return status.state === 'PAUSE';
  7949. case 'finished': return status.state === 'FINISH';
  7950. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7951. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7952. case 'offline': return false; // Connected printers are never offline
  7953. default: return true;
  7954. }
  7955. });
  7956. }
  7957. return result;
  7958. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7959. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7960. // Derive unique locations for the location filter dropdown
  7961. const availableLocations = useMemo(() => {
  7962. if (!printers) return [];
  7963. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7964. }, [printers]);
  7965. // Sort printers based on selected option
  7966. const sortedPrinters = useMemo(() => {
  7967. const sorted = [...filteredPrinters];
  7968. switch (sortBy) {
  7969. case 'name':
  7970. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7971. break;
  7972. case 'model':
  7973. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7974. break;
  7975. case 'location':
  7976. // Sort by location, with ungrouped printers last
  7977. sorted.sort((a, b) => {
  7978. const locA = a.location || '';
  7979. const locB = b.location || '';
  7980. if (!locA && locB) return 1;
  7981. if (locA && !locB) return -1;
  7982. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7983. });
  7984. break;
  7985. case 'status':
  7986. // Sort by status: HMS errors > printing > idle > offline
  7987. sorted.sort((a, b) => {
  7988. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7989. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7990. const getPriority = (s: typeof statusA) => {
  7991. if (!s?.connected) return 3; // offline
  7992. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7993. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7994. if (s.state === 'RUNNING') return 1; // printing
  7995. return 2; // idle
  7996. };
  7997. return getPriority(statusA) - getPriority(statusB);
  7998. });
  7999. break;
  8000. case 'eta':
  8001. sorted.sort((a, b) => {
  8002. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8003. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8004. const tier = (s: typeof statusA) => {
  8005. if (!s?.connected) return 3; // offline last
  8006. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8007. if (s.state === 'RUNNING') return 1; // printing without ETA
  8008. return 2; // idle
  8009. };
  8010. const ta = tier(statusA);
  8011. const tb = tier(statusB);
  8012. if (ta !== tb) return ta - tb;
  8013. if (ta === 0) {
  8014. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8015. if (diff !== 0) return diff;
  8016. }
  8017. return a.name.localeCompare(b.name);
  8018. });
  8019. break;
  8020. }
  8021. // Apply ascending/descending
  8022. if (!sortAsc) {
  8023. sorted.reverse();
  8024. }
  8025. return sorted;
  8026. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8027. const selectAll = useCallback(() => {
  8028. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8029. setIsSelectionMode(true);
  8030. }, [sortedPrinters]);
  8031. const selectByState = useCallback((state: PrinterState) => {
  8032. setSelectedPrinterIds(prev => {
  8033. const next = new Set(prev);
  8034. sortedPrinters.forEach(p => {
  8035. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8036. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8037. });
  8038. return next;
  8039. });
  8040. setIsSelectionMode(true);
  8041. }, [sortedPrinters, queryClient]);
  8042. const selectByLocation = useCallback((location: string) => {
  8043. setSelectedPrinterIds(prev => {
  8044. const next = new Set(prev);
  8045. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  8046. return next;
  8047. });
  8048. setIsSelectionMode(true);
  8049. }, [sortedPrinters]);
  8050. const selectByModel = useCallback((model: string) => {
  8051. setSelectedPrinterIds(prev => {
  8052. const next = new Set(prev);
  8053. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  8054. return next;
  8055. });
  8056. setIsSelectionMode(true);
  8057. }, [sortedPrinters]);
  8058. const toggleSectionCollapse = useCallback((key: string) => {
  8059. setCollapsedSections(prev => {
  8060. const next = { ...prev, [key]: !prev[key] };
  8061. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  8062. return next;
  8063. });
  8064. }, []);
  8065. // Group printers when sorted by location, status, or model
  8066. const groupedPrinters = useMemo(() => {
  8067. if (sortBy === 'name' || sortBy === 'eta') return null;
  8068. const groups: Record<string, typeof sortedPrinters> = {};
  8069. if (sortBy === 'location') {
  8070. sortedPrinters.forEach(printer => {
  8071. const location = printer.location || 'Ungrouped';
  8072. if (!groups[location]) groups[location] = [];
  8073. groups[location].push(printer);
  8074. });
  8075. } else if (sortBy === 'model') {
  8076. sortedPrinters.forEach(printer => {
  8077. const model = printer.model || 'Unknown';
  8078. if (!groups[model]) groups[model] = [];
  8079. groups[model].push(printer);
  8080. });
  8081. } else if (sortBy === 'status') {
  8082. sortedPrinters.forEach(printer => {
  8083. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  8084. const group = classifyPrinterStatus(status);
  8085. if (!groups[group]) groups[group] = [];
  8086. groups[group].push(printer);
  8087. });
  8088. }
  8089. return groups;
  8090. // 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
  8091. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  8092. const toolbarRef = useRef<HTMLDivElement>(null);
  8093. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  8094. const expandedToolbarWidthRef = useRef(0);
  8095. const [compactToolbar, setCompactToolbar] = useState(false);
  8096. const measureToolbar = useCallback(() => {
  8097. const toolbar = toolbarRef.current;
  8098. if (!toolbar) return;
  8099. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  8100. if (measuredControlsWidth) {
  8101. expandedToolbarWidthRef.current = measuredControlsWidth;
  8102. }
  8103. const searchMinimumWidth = 220;
  8104. const gapWidth = 8;
  8105. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  8106. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  8107. }, []);
  8108. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  8109. useLayoutEffect(() => {
  8110. measureToolbar();
  8111. const toolbar = toolbarRef.current;
  8112. if (!toolbar) return;
  8113. if (typeof ResizeObserver === 'undefined') {
  8114. window.addEventListener('resize', measureToolbar);
  8115. return () => window.removeEventListener('resize', measureToolbar);
  8116. }
  8117. const resizeObserver = new ResizeObserver(() => measureToolbar());
  8118. resizeObserver.observe(toolbar);
  8119. window.addEventListener('resize', measureToolbar);
  8120. return () => {
  8121. resizeObserver.disconnect();
  8122. window.removeEventListener('resize', measureToolbar);
  8123. };
  8124. }, [
  8125. measureToolbar,
  8126. printers?.length,
  8127. availableLocations.length,
  8128. hideDisconnected,
  8129. smartPlugCount,
  8130. ]);
  8131. const renderFilterControls = (inMenu = false) => (
  8132. <>
  8133. {/* Status filter */}
  8134. {printers && printers.length > 0 && (
  8135. <ToolbarDropdown
  8136. value={statusFilter}
  8137. onChange={setStatusFilter}
  8138. fullWidth={inMenu}
  8139. options={[
  8140. { value: 'all', label: t('printers.filter.allStatuses') },
  8141. { value: 'printing', label: t('printers.status.printing') },
  8142. { value: 'paused', label: t('printers.status.paused') },
  8143. { value: 'idle', label: t('printers.status.idle') },
  8144. { value: 'finished', label: t('printers.status.finished') },
  8145. { value: 'error', label: t('printers.status.error') },
  8146. { value: 'offline', label: t('printers.status.offline') },
  8147. ]}
  8148. />
  8149. )}
  8150. {/* Location filter — only shown when at least one printer has a location */}
  8151. {printers && printers.length > 0 && availableLocations.length > 0 && (
  8152. <ToolbarDropdown
  8153. value={locationFilter}
  8154. onChange={setLocationFilter}
  8155. fullWidth={inMenu}
  8156. options={[
  8157. { value: 'all', label: t('printers.filter.allLocations') },
  8158. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  8159. ]}
  8160. />
  8161. )}
  8162. <button
  8163. type="button"
  8164. onClick={toggleHideDisconnected}
  8165. aria-pressed={hideDisconnected}
  8166. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  8167. hideDisconnected
  8168. ? 'bg-bambu-green border-bambu-green text-white'
  8169. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8170. }`}
  8171. >
  8172. {t('printers.hideOffline')}
  8173. </button>
  8174. </>
  8175. );
  8176. const renderViewControls = (inMenu = false) => (
  8177. <>
  8178. {/* Sort dropdown */}
  8179. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8180. <ToolbarDropdown<SortOption>
  8181. value={sortBy}
  8182. onChange={handleSortChange}
  8183. fullWidth={inMenu}
  8184. options={[
  8185. { value: 'name', label: t('printers.sort.name') },
  8186. { value: 'status', label: t('printers.sort.status') },
  8187. { value: 'model', label: t('printers.sort.model') },
  8188. { value: 'location', label: t('printers.sort.location') },
  8189. { value: 'eta', label: t('printers.sort.eta') },
  8190. ]}
  8191. />
  8192. <button
  8193. onClick={toggleSortDirection}
  8194. 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"
  8195. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8196. >
  8197. {sortAsc ? (
  8198. <ArrowUp className="w-4 h-4 text-white" />
  8199. ) : (
  8200. <ArrowDown className="w-4 h-4 text-white" />
  8201. )}
  8202. </button>
  8203. </div>
  8204. {/* Page view toggle: Cards / Cam Wall */}
  8205. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8206. <button
  8207. type="button"
  8208. onClick={() => {
  8209. setPageView('cards');
  8210. localStorage.setItem('printerPageView', 'cards');
  8211. }}
  8212. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8213. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8214. }`}
  8215. title={t('printers.pageView.cards')}
  8216. aria-pressed={pageView === 'cards'}
  8217. >
  8218. <LayoutGrid className="w-3.5 h-3.5" />
  8219. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8220. </button>
  8221. <button
  8222. type="button"
  8223. onClick={() => {
  8224. setPageView('camwall');
  8225. localStorage.setItem('printerPageView', 'camwall');
  8226. }}
  8227. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8228. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8229. }`}
  8230. title={t('printers.pageView.camWall')}
  8231. aria-pressed={pageView === 'camwall'}
  8232. disabled={!hasPermission('camera:view')}
  8233. >
  8234. <MonitorPlay className="w-3.5 h-3.5" />
  8235. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8236. </button>
  8237. </div>
  8238. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8239. view, and the page a kiosk token points at. Only offered once the wall
  8240. is the active view, so it doesn't compete with the toggle above. */}
  8241. {pageView === 'camwall' && hasPermission('camera:view') && (
  8242. <RouterLink
  8243. to="/camwall"
  8244. 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' : ''}`}
  8245. title={t('printers.pageView.openCamWallPage')}
  8246. >
  8247. <ExternalLink className="w-3.5 h-3.5" />
  8248. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8249. </RouterLink>
  8250. )}
  8251. {/* Card size selector */}
  8252. <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' : ''}`}>
  8253. {cardSizeLabels.map((label, index) => {
  8254. const size = index + 1;
  8255. const isSelected = cardSize === size;
  8256. return (
  8257. <button
  8258. key={label}
  8259. onClick={() => {
  8260. setCompactDrilldownPrinterId(null);
  8261. setCardSize(size);
  8262. localStorage.setItem('printerCardSize', String(size));
  8263. }}
  8264. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8265. index === 0 ? 'rounded-l-lg' : ''
  8266. } ${
  8267. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8268. } ${
  8269. isSelected
  8270. ? 'bg-bambu-green text-white'
  8271. : 'text-white hover:bg-bambu-dark-tertiary'
  8272. }`}
  8273. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8274. >
  8275. {label}
  8276. </button>
  8277. );
  8278. })}
  8279. </div>
  8280. </>
  8281. );
  8282. const renderActionControls = (inMenu = false) => (
  8283. <>
  8284. {/* Bulk select toggle */}
  8285. <button
  8286. onClick={() => {
  8287. if (selectionMode) clearSelection();
  8288. else setIsSelectionMode(true);
  8289. }}
  8290. 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' : ''} ${
  8291. selectionMode
  8292. ? 'bg-bambu-green border-bambu-green text-white'
  8293. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8294. }`}
  8295. title={t('printers.bulk.select')}
  8296. disabled={!hasPermission('printers:control')}
  8297. >
  8298. <CheckSquare className="w-4 h-4" />
  8299. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8300. </button>
  8301. {/* Power dropdown for offline printers with smart plugs */}
  8302. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8303. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8304. <button
  8305. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8306. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8307. inMenu
  8308. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8309. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8310. }`}
  8311. >
  8312. <span className="flex items-center gap-1.5">
  8313. <Power className="w-4 h-4" />
  8314. {t('printers.powerOn')}
  8315. </span>
  8316. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8317. </button>
  8318. {showPowerDropdown && (
  8319. <>
  8320. {/* Backdrop to close dropdown */}
  8321. <div
  8322. className="fixed inset-0 z-10"
  8323. onClick={() => setShowPowerDropdown(false)}
  8324. />
  8325. <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">
  8326. <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">
  8327. {t('printers.offlinePrintersWithPlugs')}
  8328. </div>
  8329. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  8330. <PowerDropdownItem
  8331. key={printer.id}
  8332. printer={printer}
  8333. plug={smartPlugByPrinter[printer.id]}
  8334. onPowerOn={(plugId) => {
  8335. setPoweringOn(plugId);
  8336. powerOnMutation.mutate(plugId);
  8337. }}
  8338. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  8339. />
  8340. ))}
  8341. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  8342. <div className="px-3 py-2 text-sm text-bambu-gray">
  8343. No printers with smart plugs
  8344. </div>
  8345. )}
  8346. </div>
  8347. </>
  8348. )}
  8349. </div>
  8350. )}
  8351. <Button
  8352. onClick={() => setShowAddModal(true)}
  8353. disabled={!hasPermission('printers:create')}
  8354. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8355. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  8356. >
  8357. <Plus className="w-4 h-4" />
  8358. {t('printers.addPrinter')}
  8359. </Button>
  8360. </>
  8361. );
  8362. return (
  8363. <div className="p-4 md:p-8">
  8364. <div className="space-y-3 mb-6">
  8365. <div>
  8366. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  8367. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  8368. {t('printers.title')}
  8369. </h1>
  8370. <StatusSummaryBar printers={printers} />
  8371. </div>
  8372. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8373. {/* Only show search bar when printers exist */}
  8374. {printers && printers.length > 0 && (
  8375. <div className="relative min-w-0 flex-1">
  8376. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8377. <input
  8378. type="search"
  8379. name="printer-search"
  8380. autoComplete="off"
  8381. data-1p-ignore
  8382. data-lpignore="true"
  8383. value={search}
  8384. onChange={(e) => setSearch(e.target.value)}
  8385. placeholder={t('printers.search')}
  8386. aria-label={t('printers.search')}
  8387. 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"
  8388. />
  8389. {search && (
  8390. <button
  8391. type="button"
  8392. aria-label={t('common.clear')}
  8393. onClick={() => setSearch('')}
  8394. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8395. >
  8396. <X className="w-4 h-4" />
  8397. </button>
  8398. )}
  8399. </div>
  8400. )}
  8401. <div
  8402. ref={expandedToolbarControlsRef}
  8403. aria-hidden={compactToolbar}
  8404. inert={compactToolbar}
  8405. 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`}
  8406. >
  8407. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8408. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8409. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8410. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8411. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8412. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8413. </div>
  8414. {compactToolbar && (
  8415. <div className="ml-auto flex items-center justify-end gap-1">
  8416. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8417. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8418. </ToolbarMenu>
  8419. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8420. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8421. </ToolbarMenu>
  8422. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8423. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8424. </ToolbarMenu>
  8425. </div>
  8426. )}
  8427. </div>
  8428. </div>
  8429. {isLoading ? (
  8430. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8431. ) : printers?.length === 0 ? (
  8432. <Card>
  8433. <CardContent className="text-center py-12">
  8434. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8435. <Button
  8436. onClick={() => setShowAddModal(true)}
  8437. disabled={!hasPermission('printers:create')}
  8438. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8439. >
  8440. <Plus className="w-4 h-4" />
  8441. {t('printers.addPrinter')}
  8442. </Button>
  8443. </CardContent>
  8444. </Card>
  8445. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8446. <Card>
  8447. <CardContent className="text-center py-12">
  8448. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8449. </CardContent>
  8450. </Card>
  8451. ) : pageView === 'camwall' ? (
  8452. <CameraWall
  8453. printers={sortedPrinters}
  8454. maxLive={camWallMaxLive}
  8455. snapshotIntervalSec={camWallSnapshotSec}
  8456. onTileClick={(id, name) => {
  8457. const cameraMode = settings?.camera_view_mode || 'window';
  8458. if (cameraMode === 'embedded') {
  8459. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  8460. } else {
  8461. const saved = localStorage.getItem('cameraWindowState');
  8462. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  8463. const features = [
  8464. `width=${state.width}`,
  8465. `height=${state.height}`,
  8466. state.left !== undefined ? `left=${state.left}` : '',
  8467. state.top !== undefined ? `top=${state.top}` : '',
  8468. 'menubar=no,toolbar=no,location=no,status=no',
  8469. ].filter(Boolean).join(',');
  8470. window.open(`/camera/${id}`, `camera-${id}`, features);
  8471. }
  8472. }}
  8473. statusMode={camWallStatusMode}
  8474. onChangeMaxLive={(next) => {
  8475. setCamWallMaxLive(next);
  8476. localStorage.setItem('camWallMaxLive', String(next));
  8477. }}
  8478. onChangeSnapshotIntervalSec={(next) => {
  8479. setCamWallSnapshotSec(next);
  8480. localStorage.setItem('camWallSnapshotSec', String(next));
  8481. }}
  8482. onChangeStatusMode={(next) => {
  8483. setCamWallStatusMode(next);
  8484. localStorage.setItem('camWallStatusMode', next);
  8485. }}
  8486. />
  8487. ) : groupedPrinters ? (
  8488. /* Grouped view (location, status, or model) */
  8489. <div className="space-y-6">
  8490. {(() => {
  8491. const keys = sortBy === 'status'
  8492. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8493. : Object.keys(groupedPrinters);
  8494. // For status grouping, asc/desc flips the fixed priority order
  8495. // (asc = error→offline, desc = offline→error). This matches the
  8496. // sort-toggle behaviour for other groupings.
  8497. return (sortAsc ? keys : [...keys].reverse());
  8498. })().map((groupKey) => {
  8499. const groupPrinters = groupedPrinters[groupKey];
  8500. const collapseKey = `${sortBy}:${groupKey}`;
  8501. const isOpen = !collapsedSections[collapseKey];
  8502. const dot = sortBy === 'status'
  8503. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8504. : 'bg-bambu-green';
  8505. const label = sortBy === 'status'
  8506. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8507. : groupKey;
  8508. return (
  8509. <Collapsible
  8510. key={groupKey}
  8511. open={isOpen}
  8512. onToggle={() => toggleSectionCollapse(collapseKey)}
  8513. summaryClassName="py-1"
  8514. summary={
  8515. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8516. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8517. {label}
  8518. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8519. {selectionMode && (
  8520. <button
  8521. onClick={(e) => {
  8522. e.stopPropagation();
  8523. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8524. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8525. else if (sortBy === 'model') selectByModel(groupKey);
  8526. }}
  8527. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8528. >
  8529. {t('printers.bulk.selectAll')}
  8530. </button>
  8531. )}
  8532. </h2>
  8533. }
  8534. >
  8535. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8536. {groupPrinters.map((printer) => (
  8537. <PrinterCard
  8538. key={printer.id}
  8539. printer={printer}
  8540. hideIfDisconnected={hideDisconnected}
  8541. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8542. viewMode={viewMode}
  8543. cardSize={cardSize}
  8544. amsThresholds={settings ? {
  8545. humidityGood: Number(settings.ams_humidity_good) || 40,
  8546. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8547. tempGood: Number(settings.ams_temp_good) || 28,
  8548. tempFair: Number(settings.ams_temp_fair) || 35,
  8549. } : undefined}
  8550. spoolmanEnabled={spoolmanEnabled}
  8551. hasUnlinkedSpools={hasUnlinkedSpools}
  8552. linkedSpools={linkedSpools}
  8553. spoolmanUrl={spoolmanStatus?.url}
  8554. spoolmanSyncMode={spoolmanSyncMode}
  8555. onGetAssignment={getAssignment}
  8556. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8557. spoolmanSpools={spoolmanSpools}
  8558. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8559. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8560. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8561. timeFormat={settings?.time_format || 'system'}
  8562. cameraViewMode={settings?.camera_view_mode || 'window'}
  8563. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8564. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8565. dryingPresets={effectiveDryingPresets}
  8566. nozzleTempPresets={effectiveNozzleTempPresets}
  8567. bedTempPresets={effectiveBedTempPresets}
  8568. chamberTempPresets={effectiveChamberTempPresets}
  8569. fanSpeedPresets={effectiveFanSpeedPresets}
  8570. requirePlateClear={settings?.require_plate_clear === true}
  8571. selectionMode={selectionMode}
  8572. isSelected={selectedPrinterIds.has(printer.id)}
  8573. onToggleSelect={toggleSelect}
  8574. onOpenCompactCard={openCompactCard}
  8575. aiDetectionEnabled={isAiMonitored(printer.id)}
  8576. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8577. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8578. />
  8579. ))}
  8580. </div>
  8581. </Collapsible>
  8582. );
  8583. })}
  8584. </div>
  8585. ) : (
  8586. /* Regular grid view */
  8587. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8588. {sortedPrinters.map((printer) => (
  8589. <PrinterCard
  8590. key={printer.id}
  8591. printer={printer}
  8592. hideIfDisconnected={hideDisconnected}
  8593. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8594. viewMode={viewMode}
  8595. cardSize={cardSize}
  8596. spoolmanEnabled={spoolmanEnabled}
  8597. hasUnlinkedSpools={hasUnlinkedSpools}
  8598. linkedSpools={linkedSpools}
  8599. spoolmanUrl={spoolmanStatus?.url}
  8600. spoolmanSyncMode={spoolmanSyncMode}
  8601. onGetAssignment={getAssignment}
  8602. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8603. spoolmanSpools={spoolmanSpools}
  8604. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8605. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8606. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8607. amsThresholds={settings ? {
  8608. humidityGood: Number(settings.ams_humidity_good) || 40,
  8609. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8610. tempGood: Number(settings.ams_temp_good) || 28,
  8611. tempFair: Number(settings.ams_temp_fair) || 35,
  8612. } : undefined}
  8613. timeFormat={settings?.time_format || 'system'}
  8614. cameraViewMode={settings?.camera_view_mode || 'window'}
  8615. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8616. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8617. dryingPresets={effectiveDryingPresets}
  8618. nozzleTempPresets={effectiveNozzleTempPresets}
  8619. bedTempPresets={effectiveBedTempPresets}
  8620. chamberTempPresets={effectiveChamberTempPresets}
  8621. fanSpeedPresets={effectiveFanSpeedPresets}
  8622. requirePlateClear={settings?.require_plate_clear === true}
  8623. selectionMode={selectionMode}
  8624. isSelected={selectedPrinterIds.has(printer.id)}
  8625. onToggleSelect={toggleSelect}
  8626. onOpenCompactCard={openCompactCard}
  8627. aiDetectionEnabled={isAiMonitored(printer.id)}
  8628. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8629. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8630. />
  8631. ))}
  8632. </div>
  8633. )}
  8634. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8635. <button
  8636. type="button"
  8637. onClick={returnToCompactCards}
  8638. 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}`}
  8639. title={t('common.back', 'Back')}
  8640. >
  8641. <ArrowLeft className="w-4 h-4" />
  8642. {t('common.back', 'Back')}
  8643. </button>
  8644. )}
  8645. {showAddModal && (
  8646. <AddPrinterModal
  8647. onClose={() => setShowAddModal(false)}
  8648. onAdd={(data) => addMutation.mutate(data)}
  8649. existingSerials={printers?.map(p => p.serial_number) || []}
  8650. />
  8651. )}
  8652. {/* Bulk selection toolbar */}
  8653. {selectionMode && printers && (
  8654. <BulkPrinterToolbar
  8655. selectedIds={selectedPrinterIds}
  8656. printers={printers}
  8657. onClose={clearSelection}
  8658. onSelectAll={selectAll}
  8659. onSelectByLocation={selectByLocation}
  8660. onSelectByState={selectByState}
  8661. onAction={handleBulkAction}
  8662. actionPending={bulkActionPending}
  8663. />
  8664. )}
  8665. {/* Bulk action confirmation modals */}
  8666. {bulkConfirmAction === 'stop' && (
  8667. <ConfirmModal
  8668. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8669. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8670. confirmText={t('printers.bulk.confirm.stopButton')}
  8671. variant="danger"
  8672. isLoading={bulkActionPending}
  8673. onConfirm={() => executeBulkAction('stop')}
  8674. onCancel={() => setBulkConfirmAction(null)}
  8675. />
  8676. )}
  8677. {bulkConfirmAction === 'pause' && (
  8678. <ConfirmModal
  8679. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8680. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8681. confirmText={t('printers.bulk.confirm.pauseButton')}
  8682. isLoading={bulkActionPending}
  8683. onConfirm={() => executeBulkAction('pause')}
  8684. onCancel={() => setBulkConfirmAction(null)}
  8685. />
  8686. )}
  8687. {bulkConfirmAction === 'clearPlate' && (
  8688. <ConfirmModal
  8689. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8690. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8691. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8692. isLoading={bulkActionPending}
  8693. onConfirm={() => executeBulkAction('clearPlate')}
  8694. onCancel={() => setBulkConfirmAction(null)}
  8695. />
  8696. )}
  8697. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8698. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8699. <EmbeddedCameraViewer
  8700. key={camera.id}
  8701. printerId={camera.id}
  8702. printerName={camera.name}
  8703. viewerIndex={index}
  8704. onClose={() => setEmbeddedCameraPrinters(prev => {
  8705. const next = new Map(prev);
  8706. next.delete(camera.id);
  8707. return next;
  8708. })}
  8709. />
  8710. ))}
  8711. </div>
  8712. );
  8713. }