PrintersPage.tsx 423 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { computePopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. BED_TEMP_DEFAULTS,
  8. CHAMBER_TEMP_DEFAULTS,
  9. FAN_SPEED_DEFAULTS,
  10. NOZZLE_TEMP_DEFAULTS,
  11. buildPresetOptions,
  12. parsePresetTriple,
  13. } from '../utils/temperatureFanPresets';
  14. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  15. // covers header + filament select + temp slider + duration + rotate-tray
  16. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  17. // earlier); under-estimating leaves the popover clipped off the bottom (the
  18. // original bug at #1447).
  19. const DRYING_POPOVER_WIDTH = 240;
  20. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  21. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  22. import { useTranslation } from 'react-i18next';
  23. import { useTheme } from '../contexts/ThemeContext';
  24. import { useAuth } from '../contexts/AuthContext';
  25. import {
  26. Plus,
  27. Link,
  28. Unlink,
  29. Signal,
  30. Clock,
  31. MoreVertical,
  32. Trash2,
  33. RefreshCw,
  34. RotateCw,
  35. Box,
  36. HardDrive,
  37. AlertTriangle,
  38. AlertCircle,
  39. Terminal,
  40. Power,
  41. Zap,
  42. Wrench,
  43. ChevronDown,
  44. Filter,
  45. Pencil,
  46. ArrowLeft,
  47. ArrowRight,
  48. ArrowUp,
  49. ArrowDown,
  50. Layers,
  51. Video,
  52. Search,
  53. Loader2,
  54. Square,
  55. Pause,
  56. Play,
  57. X,
  58. Fan,
  59. Wind,
  60. AirVent,
  61. Download,
  62. ScanSearch,
  63. CheckCircle,
  64. CheckSquare,
  65. XCircle,
  66. User,
  67. Home,
  68. Printer as PrinterIcon,
  69. Info,
  70. Cable,
  71. Flame,
  72. Repeat,
  73. Snowflake,
  74. Gauge,
  75. DoorOpen,
  76. DoorClosed,
  77. Move,
  78. LogIn,
  79. LogOut,
  80. MoreHorizontal,
  81. SlidersHorizontal,
  82. Stethoscope,
  83. LineChart as LineChartIcon,
  84. LayoutGrid,
  85. MonitorPlay,
  86. ExternalLink,
  87. } from 'lucide-react';
  88. // Aliased: lucide-react already exports a `Link` icon into this module.
  89. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  90. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  91. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  92. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  93. import { Card, CardContent } from '../components/Card';
  94. import { Button } from '../components/Button';
  95. import { ConfirmModal } from '../components/ConfirmModal';
  96. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  97. import { FileManagerModal } from '../components/FileManagerModal';
  98. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  99. import { CameraWall } from '../components/CameraWall';
  100. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  101. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  102. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  103. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  104. import { AmsBackupModal } from '../components/AmsBackupModal';
  105. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  106. import type { HeaterSensorKind } from '../api/client';
  107. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  108. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  109. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  110. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  111. import { useToast } from '../contexts/ToastContext';
  112. import { ChamberLight } from '../components/icons/ChamberLight';
  113. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  114. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  115. import { FileUploadModal } from '../components/FileUploadModal';
  116. import { PrintModal } from '../components/PrintModal';
  117. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  118. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
  119. import { getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  120. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  121. import { Collapsible } from '../components/Collapsible';
  122. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  123. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  124. export interface SpoolmanSlotAssignmentRow {
  125. printer_id: number;
  126. ams_id: number;
  127. tray_id: number;
  128. spoolman_spool_id: number;
  129. }
  130. // Color names resolve via getColorName() which reads the backend color_catalog
  131. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  132. // Format K value with 3 decimal places, default to 0.020 if null
  133. function formatKValue(k: number | null | undefined): string {
  134. const value = k ?? 0.020;
  135. return value.toFixed(3);
  136. }
  137. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  138. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  139. const { mode } = useTheme();
  140. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  141. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  142. return (
  143. <span
  144. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  145. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  146. >
  147. {side}
  148. </span>
  149. );
  150. }
  151. // Expand nozzle type codes to material names
  152. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  153. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  154. function nozzleTypeName(type: string, t: (key: string) => string): string {
  155. if (!type) return '';
  156. // Full text names (from main nozzle info)
  157. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  158. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  159. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  160. // 4-char codes (e.g. "HS01"): last 2 digits = material
  161. if (type.length >= 4) {
  162. const material = type.slice(2, 4);
  163. if (material === '00') return t('printers.nozzleStainlessSteel');
  164. if (material === '01') return t('printers.nozzleHardenedSteel');
  165. if (material === '05') return t('printers.nozzleTungstenCarbide');
  166. }
  167. // 2-digit numeric codes
  168. if (type === '00') return t('printers.nozzleStainlessSteel');
  169. if (type === '01') return t('printers.nozzleHardenedSteel');
  170. if (type === '05') return t('printers.nozzleTungstenCarbide');
  171. // 2-char alpha codes: H prefix = hardened steel
  172. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  173. return type;
  174. }
  175. // Parse flow type from nozzle type code
  176. // HH = high flow, HS = standard/normal
  177. function nozzleFlowName(type: string, t: (key: string) => string): string {
  178. if (!type) return '';
  179. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  180. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  181. return '';
  182. }
  183. // Per-slot hover card for nozzle rack
  184. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  185. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  186. slot: import('../api/client').NozzleRackSlot;
  187. index: number;
  188. activeStatus?: boolean;
  189. filamentName?: string;
  190. children: React.ReactNode;
  191. }) {
  192. const { t } = useTranslation();
  193. const [isVisible, setIsVisible] = useState(false);
  194. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  195. const triggerRef = useRef<HTMLDivElement>(null);
  196. const cardRef = useRef<HTMLDivElement>(null);
  197. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  198. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  199. const isMounted = slot.stat === 1;
  200. useEffect(() => {
  201. if (isVisible && triggerRef.current && cardRef.current) {
  202. const triggerRect = triggerRef.current.getBoundingClientRect();
  203. const cardHeight = cardRef.current.offsetHeight;
  204. const headerHeight = 56;
  205. const spaceAbove = triggerRect.top - headerHeight;
  206. const spaceBelow = window.innerHeight - triggerRect.bottom;
  207. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  208. setPosition('bottom');
  209. } else {
  210. setPosition('top');
  211. }
  212. }
  213. }, [isVisible]);
  214. const handleMouseEnter = () => {
  215. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  216. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  217. };
  218. const handleMouseLeave = () => {
  219. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  220. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  221. };
  222. useEffect(() => {
  223. return () => {
  224. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  225. };
  226. }, []);
  227. const filamentCss = parseFilamentColor(slot.filament_color);
  228. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  229. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  230. return (
  231. <div
  232. ref={triggerRef}
  233. className="relative"
  234. onMouseEnter={handleMouseEnter}
  235. onMouseLeave={handleMouseLeave}
  236. >
  237. {children}
  238. {isVisible && (
  239. <div
  240. ref={cardRef}
  241. className={`
  242. absolute left-1/2 -translate-x-1/2 z-50
  243. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  244. animate-in fade-in-0 zoom-in-95 duration-150
  245. `}
  246. style={{ maxWidth: 'calc(100vw - 24px)' }}
  247. >
  248. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  249. {isEmpty ? (
  250. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  251. Slot {index + 1} — Empty
  252. </div>
  253. ) : (
  254. <div className="p-2.5 space-y-1.5">
  255. {/* Diameter */}
  256. <div className="flex items-center justify-between">
  257. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  258. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  259. </div>
  260. {/* Type */}
  261. {typeFull && (
  262. <div className="flex items-center justify-between">
  263. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  264. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  265. </div>
  266. )}
  267. {/* Flow (hide if empty) */}
  268. {flowFull && (
  269. <div className="flex items-center justify-between">
  270. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  271. <span className="text-xs text-white font-semibold">{flowFull}</span>
  272. </div>
  273. )}
  274. {/* Status badge */}
  275. <div className="flex items-center justify-between">
  276. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  277. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  278. activeStatus || isMounted
  279. ? 'bg-green-900/50 text-green-400'
  280. : 'bg-bambu-dark-tertiary text-bambu-gray'
  281. }`}>
  282. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  283. </span>
  284. </div>
  285. {/* Wear (hide if null) */}
  286. {slot.wear != null && (
  287. <div className="flex items-center justify-between">
  288. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  289. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  290. </div>
  291. )}
  292. {/* Max Temp (hide if 0) */}
  293. {slot.max_temp > 0 && (
  294. <div className="flex items-center justify-between">
  295. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  296. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  297. </div>
  298. )}
  299. {/* Serial (hide if empty) */}
  300. {slot.serial_number && (
  301. <div className="flex items-center justify-between">
  302. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  303. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  304. </div>
  305. )}
  306. {/* Filament: material type + color swatch (hide if no color) */}
  307. {(filamentCss || slot.filament_type) && (
  308. <div className="flex items-center justify-between">
  309. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  310. <div className="flex items-center gap-1">
  311. {filamentCss && (
  312. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  313. )}
  314. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  315. </div>
  316. </div>
  317. )}
  318. </div>
  319. )}
  320. </div>
  321. {/* Arrow pointer */}
  322. <div
  323. className={`
  324. absolute left-1/2 -translate-x-1/2 w-0 h-0
  325. border-l-[6px] border-l-transparent
  326. border-r-[6px] border-r-transparent
  327. ${position === 'top'
  328. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  329. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  330. `}
  331. />
  332. </div>
  333. )}
  334. </div>
  335. );
  336. }
  337. // Dual-nozzle hover card showing L and R nozzle details side by side
  338. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  339. leftSlot?: import('../api/client').NozzleRackSlot;
  340. rightSlot?: import('../api/client').NozzleRackSlot;
  341. activeNozzle: 'L' | 'R';
  342. filamentInfo?: Record<string, { name: string; k: number | null }>;
  343. children: React.ReactNode;
  344. }) {
  345. const { t } = useTranslation();
  346. const [isVisible, setIsVisible] = useState(false);
  347. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  348. const triggerRef = useRef<HTMLDivElement>(null);
  349. const cardRef = useRef<HTMLDivElement>(null);
  350. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  351. useEffect(() => {
  352. if (isVisible && triggerRef.current && cardRef.current) {
  353. const triggerRect = triggerRef.current.getBoundingClientRect();
  354. const cardHeight = cardRef.current.offsetHeight;
  355. const headerHeight = 56;
  356. const spaceAbove = triggerRect.top - headerHeight;
  357. const spaceBelow = window.innerHeight - triggerRect.bottom;
  358. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  359. setPosition('bottom');
  360. } else {
  361. setPosition('top');
  362. }
  363. }
  364. }, [isVisible]);
  365. const handleMouseEnter = () => {
  366. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  367. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  368. };
  369. const handleMouseLeave = () => {
  370. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  371. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  372. };
  373. useEffect(() => {
  374. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  375. }, []);
  376. if (!leftSlot && !rightSlot) return <>{children}</>;
  377. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  378. const isActive = activeNozzle === side;
  379. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  380. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  381. const filamentCss = parseFilamentColor(slot.filament_color);
  382. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  383. return (
  384. <div className="flex-1 space-y-1.5">
  385. <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'}`}>
  386. {side === 'L' ? t('common.left') : t('common.right')}
  387. </div>
  388. {slot.nozzle_diameter && (
  389. <div className="flex items-center justify-between">
  390. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  391. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  392. </div>
  393. )}
  394. {typeFull && (
  395. <div className="flex items-center justify-between">
  396. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  397. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  398. </div>
  399. )}
  400. {flowFull && (
  401. <div className="flex items-center justify-between">
  402. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  403. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  404. </div>
  405. )}
  406. <div className="flex items-center justify-between">
  407. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  408. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  409. isActive
  410. ? 'bg-green-900/50 text-green-400'
  411. : 'bg-bambu-dark-tertiary text-bambu-gray'
  412. }`}>
  413. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  414. </span>
  415. </div>
  416. {slot.wear != null && (
  417. <div className="flex items-center justify-between">
  418. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  419. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  420. </div>
  421. )}
  422. {/* Serial and max temp only available on the right (removable) nozzle */}
  423. {side === 'R' && slot.max_temp > 0 && (
  424. <div className="flex items-center justify-between">
  425. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  426. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  427. </div>
  428. )}
  429. {side === 'R' && slot.serial_number && (
  430. <div className="flex items-center justify-between">
  431. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  432. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  433. </div>
  434. )}
  435. {(filamentCss || slot.filament_type || slot.filament_id) && (
  436. <div className="flex items-center justify-between">
  437. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  438. <div className="flex items-center gap-1">
  439. {filamentCss && (
  440. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  441. )}
  442. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  443. {filamentName || slot.filament_type || slot.filament_id || ''}
  444. </span>
  445. </div>
  446. </div>
  447. )}
  448. </div>
  449. );
  450. };
  451. return (
  452. <div
  453. ref={triggerRef}
  454. className="relative flex-1"
  455. onMouseEnter={handleMouseEnter}
  456. onMouseLeave={handleMouseLeave}
  457. >
  458. {children}
  459. {isVisible && (
  460. <div
  461. ref={cardRef}
  462. className={`
  463. absolute left-1/2 -translate-x-1/2 z-50
  464. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  465. animate-in fade-in-0 zoom-in-95 duration-150
  466. `}
  467. style={{ maxWidth: 'calc(100vw - 24px)' }}
  468. >
  469. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  470. <div className="p-2.5 flex gap-3">
  471. {leftSlot && renderColumn(leftSlot, 'L')}
  472. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  473. {rightSlot && renderColumn(rightSlot, 'R')}
  474. </div>
  475. </div>
  476. {/* Arrow pointer */}
  477. <div
  478. className={`
  479. absolute left-1/2 -translate-x-1/2 w-0 h-0
  480. border-l-[6px] border-l-transparent
  481. border-r-[6px] border-r-transparent
  482. ${position === 'top'
  483. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  484. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  485. `}
  486. />
  487. </div>
  488. )}
  489. </div>
  490. );
  491. }
  492. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  493. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  494. const { t } = useTranslation();
  495. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  496. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  497. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  498. // base — computing it from min(present IDs) shifts everything left when slot 16
  499. // is the one currently mounted (#943).
  500. const rackNozzles = slots.filter(s => s.id >= 2);
  501. const RACK_SIZE = 6;
  502. const RACK_BASE_ID = 16;
  503. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  504. { length: RACK_SIZE },
  505. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  506. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  507. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  508. },
  509. );
  510. return (
  511. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  512. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  513. <div className="flex gap-[3px] justify-center">
  514. {rackSlots.map((slot, i) => {
  515. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  516. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  517. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  518. return (
  519. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  520. <div
  521. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  522. isEmpty
  523. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  524. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  525. }`}
  526. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  527. >
  528. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  529. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  530. >
  531. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  532. </span>
  533. </div>
  534. </NozzleSlotHoverCard>
  535. );
  536. })}
  537. </div>
  538. </div>
  539. );
  540. }
  541. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  542. function WaterDropEmpty({ className }: { className?: string }) {
  543. return (
  544. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  545. <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"/>
  546. </svg>
  547. );
  548. }
  549. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  550. function WaterDropHalf({ className }: { className?: string }) {
  551. return (
  552. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  553. <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"/>
  554. <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"/>
  555. </svg>
  556. );
  557. }
  558. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  559. function WaterDropFull({ className }: { className?: string }) {
  560. return (
  561. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  562. <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"/>
  563. <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"/>
  564. </svg>
  565. );
  566. }
  567. // Thermometer SVG - empty outline
  568. function ThermometerEmpty({ className }: { className?: string }) {
  569. return (
  570. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  571. <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"/>
  572. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  573. </svg>
  574. );
  575. }
  576. // Thermometer SVG - half filled (gold - same as humidity fair)
  577. function ThermometerHalf({ className }: { className?: string }) {
  578. return (
  579. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  580. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  581. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  582. <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"/>
  583. </svg>
  584. );
  585. }
  586. // Thermometer SVG - fully filled (red - same as humidity bad)
  587. function ThermometerFull({ className }: { className?: string }) {
  588. return (
  589. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  590. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  591. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  592. <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"/>
  593. </svg>
  594. );
  595. }
  596. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  597. // Added for visual parity with the thermometer icons on the dual-nozzle card
  598. // that previously had no icon at all (#1115, design by @m4rtini2).
  599. function NozzleIcon({ className }: { className?: string }) {
  600. return (
  601. <svg
  602. className={className}
  603. viewBox="0 0 24 24"
  604. fill="none"
  605. xmlns="http://www.w3.org/2000/svg"
  606. stroke="currentColor"
  607. strokeWidth="1.5"
  608. strokeLinecap="round"
  609. strokeLinejoin="round"
  610. >
  611. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  612. <rect x="6" y="11.5" width="12.1" height="3.7" />
  613. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  614. </svg>
  615. );
  616. }
  617. // Heater thermometer icon - filled when heating, outline when off
  618. interface HeaterThermometerProps {
  619. className?: string;
  620. color: string; // The color class (e.g., "text-orange-400")
  621. isHeating: boolean;
  622. }
  623. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  624. // Extract the actual color from Tailwind class for SVG fill
  625. const colorMap: Record<string, string> = {
  626. 'text-orange-400': '#fb923c',
  627. 'text-blue-400': '#60a5fa',
  628. 'text-green-400': '#4ade80',
  629. };
  630. const fillColor = colorMap[color] || '#888';
  631. // Glow style when heating
  632. const glowStyle = isHeating ? {
  633. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  634. } : {};
  635. if (isHeating) {
  636. // Filled thermometer with glow - heater is ON
  637. return (
  638. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  639. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  640. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  641. <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"/>
  642. </svg>
  643. );
  644. }
  645. // Empty thermometer - heater is OFF
  646. return (
  647. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  648. <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"/>
  649. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  650. </svg>
  651. );
  652. }
  653. // AMS Filament Backup tri-state indicator + toggle.
  654. // state=true → ON, click to disable
  655. // state=false → OFF, click opens modal
  656. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  657. interface AmsBackupBadgeProps {
  658. state: boolean | null;
  659. onClick: () => void;
  660. }
  661. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  662. const { t } = useTranslation();
  663. const known = state !== null;
  664. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  665. let title: string;
  666. if (state === true) {
  667. className += known
  668. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  669. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  670. title = t('printers.amsBackup.titleOn');
  671. } else if (state === false) {
  672. className += known
  673. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  674. : 'bg-bambu-dark text-bambu-gray cursor-default';
  675. title = t('printers.amsBackup.titleOff');
  676. } else {
  677. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  678. title = t('printers.amsBackup.titleUnknown');
  679. }
  680. return (
  681. <button
  682. type="button"
  683. disabled={!known}
  684. onClick={() => known && onClick()}
  685. className={className}
  686. title={title}
  687. aria-label={title}
  688. >
  689. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  690. </button>
  691. );
  692. }
  693. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  694. // Reference: https://github.com/theicedmango/bambu-humidity
  695. interface HumidityIndicatorProps {
  696. humidity: number | string;
  697. goodThreshold?: number; // <= this is green
  698. fairThreshold?: number; // <= this is orange, > is red
  699. onClick?: () => void;
  700. compact?: boolean; // Smaller version for grid layout
  701. }
  702. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  703. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  704. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  705. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  706. // Status thresholds (configurable via settings)
  707. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  708. let textColor: string;
  709. let statusText: string;
  710. if (isNaN(humidityValue)) {
  711. textColor = '#C3C2C1';
  712. statusText = 'Unknown';
  713. } else if (humidityValue <= good) {
  714. textColor = '#22a352'; // Green - Good
  715. statusText = 'Good';
  716. } else if (humidityValue <= fair) {
  717. textColor = '#d4a017'; // Gold - Fair
  718. statusText = 'Fair';
  719. } else {
  720. textColor = '#c62828'; // Red - Bad
  721. statusText = 'Bad';
  722. }
  723. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  724. let DropComponent: React.FC<{ className?: string }>;
  725. if (isNaN(humidityValue)) {
  726. DropComponent = WaterDropEmpty;
  727. } else if (humidityValue <= good) {
  728. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  729. } else if (humidityValue <= fair) {
  730. DropComponent = WaterDropHalf; // Fair - half filled
  731. } else {
  732. DropComponent = WaterDropFull; // Bad - full (too humid)
  733. }
  734. return (
  735. <button
  736. type="button"
  737. onClick={onClick}
  738. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  739. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  740. >
  741. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  742. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  743. </button>
  744. );
  745. }
  746. // Temperature indicator with dynamic icon and coloring
  747. interface TemperatureIndicatorProps {
  748. temp: number;
  749. goodThreshold?: number; // <= this is blue
  750. fairThreshold?: number; // <= this is orange, > is red
  751. onClick?: () => void;
  752. compact?: boolean; // Smaller version for grid layout
  753. }
  754. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  755. // Ensure thresholds are numbers
  756. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  757. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  758. let textColor: string;
  759. let statusText: string;
  760. let ThermoComponent: React.FC<{ className?: string }>;
  761. if (temp <= good) {
  762. textColor = '#22a352'; // Green - good (same as humidity)
  763. statusText = 'Good';
  764. ThermoComponent = ThermometerEmpty;
  765. } else if (temp <= fair) {
  766. textColor = '#d4a017'; // Gold - fair (same as humidity)
  767. statusText = 'Fair';
  768. ThermoComponent = ThermometerHalf;
  769. } else {
  770. textColor = '#c62828'; // Red - bad (same as humidity)
  771. statusText = 'Bad';
  772. ThermoComponent = ThermometerFull;
  773. }
  774. return (
  775. <button
  776. type="button"
  777. onClick={onClick}
  778. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  779. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  780. >
  781. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  782. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  783. </button>
  784. );
  785. }
  786. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  787. *
  788. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  789. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  790. * every empty-by-bitmask slot lands here regardless of firmware payload
  791. * shape.
  792. *
  793. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  794. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  795. * the user cleared with "Reset Slot" where a physical spool may still be
  796. * loaded but unassigned.
  797. *
  798. * Returns null when the slot is loaded (tray_type is present).
  799. */
  800. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  801. if (tray?.tray_type) return null;
  802. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  803. // spool the firmware can't identify is physically present (exists === true)
  804. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  805. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  806. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  807. if (tray?.exists === true) return 'reset';
  808. if (tray?.exists === false) return 'physical';
  809. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  810. }
  811. // How long to wait for an AMS to report a live drying cycle after the printer
  812. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  813. // within a couple of seconds; 30s covers the slowest observed push cadence
  814. // without leaving the user waiting on a verdict.
  815. const DRY_START_CONFIRM_MS = 30_000;
  816. function CoverImage({
  817. url,
  818. printName,
  819. className = 'w-20 h-20',
  820. radiusClass = 'rounded-lg',
  821. }: {
  822. url: string | null;
  823. printName?: string;
  824. className?: string;
  825. radiusClass?: string;
  826. }) {
  827. const { t } = useTranslation();
  828. const [loaded, setLoaded] = useState(false);
  829. const [error, setError] = useState(false);
  830. const [showOverlay, setShowOverlay] = useState(false);
  831. // Cache-bust the image URL when the print name changes so the browser
  832. // fetches the new cover instead of serving the stale cached image.
  833. const cacheBustedUrl = useMemo(() => {
  834. if (!url) return null;
  835. const sep = url.includes('?') ? '&' : '?';
  836. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  837. }, [url, printName]);
  838. // Reset loaded/error state when the image URL changes
  839. useEffect(() => {
  840. setLoaded(false);
  841. setError(false);
  842. }, [cacheBustedUrl]);
  843. return (
  844. <>
  845. <div
  846. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  847. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  848. >
  849. {cacheBustedUrl && !error ? (
  850. <>
  851. <img
  852. src={cacheBustedUrl}
  853. alt={t('printers.printPreview')}
  854. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  855. onLoad={() => setLoaded(true)}
  856. onError={() => setError(true)}
  857. />
  858. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  859. </>
  860. ) : (
  861. <Box className="w-8 h-8 text-bambu-gray" />
  862. )}
  863. </div>
  864. {/* Cover Image Overlay */}
  865. {showOverlay && cacheBustedUrl && (
  866. <div
  867. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  868. onClick={() => setShowOverlay(false)}
  869. >
  870. <div className="relative max-w-2xl max-h-full">
  871. <img
  872. src={cacheBustedUrl}
  873. alt={t('printers.printPreview')}
  874. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  875. />
  876. {printName && (
  877. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  878. )}
  879. </div>
  880. </div>
  881. )}
  882. </>
  883. );
  884. }
  885. interface PrinterMaintenanceInfo {
  886. due_count: number;
  887. warning_count: number;
  888. total_print_hours: number;
  889. }
  890. // Status summary bar component - uses queryClient to read cached statuses
  891. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  892. const { t } = useTranslation();
  893. const queryClient = useQueryClient();
  894. // Subscribe to query cache changes to re-render when status updates
  895. // Throttled to prevent rapid re-renders from causing tab crashes
  896. const [cacheTick, setCacheTick] = useState(0);
  897. useEffect(() => {
  898. let pending = false;
  899. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  900. if (!pending) {
  901. pending = true;
  902. requestAnimationFrame(() => {
  903. setCacheTick(t => t + 1);
  904. pending = false;
  905. });
  906. }
  907. });
  908. return () => unsubscribe();
  909. }, [queryClient]);
  910. const { counts, nextFinish } = useMemo(() => {
  911. let printing = 0;
  912. let paused = 0;
  913. let finished = 0;
  914. let idle = 0;
  915. let offline = 0;
  916. let loading = 0;
  917. let error = 0;
  918. let nextPrinterName: string | null = null;
  919. let nextRemainingMin: number | null = null;
  920. let nextProgress: number = 0;
  921. printers?.forEach((printer) => {
  922. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  923. if (status === undefined) {
  924. // Status not yet loaded - don't count as offline yet
  925. loading++;
  926. } else if (!status.connected) {
  927. offline++;
  928. } else {
  929. // Count printers with active HMS errors as problems
  930. const knownHmsCount =
  931. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  932. if (knownHmsCount > 0) {
  933. error++;
  934. }
  935. switch (status.state) {
  936. case 'RUNNING':
  937. printing++;
  938. if (status.remaining_time != null && status.remaining_time > 0) {
  939. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  940. nextRemainingMin = status.remaining_time;
  941. nextPrinterName = printer.name;
  942. nextProgress = status.progress || 0;
  943. }
  944. }
  945. break;
  946. case 'PAUSE':
  947. paused++;
  948. break;
  949. case 'FINISH':
  950. finished++;
  951. break;
  952. case 'FAILED':
  953. // FAILED is the printer's terminal gcode_state after a print stops —
  954. // including user cancellations, where there's no actual fault. Only
  955. // count it as a "problem" when an HMS error is also active; otherwise
  956. // it's just a print that ended unsuccessfully and the plate needs
  957. // clearing (same as FINISH from the operator's perspective).
  958. if (knownHmsCount > 0) {
  959. // Already counted above
  960. } else {
  961. finished++;
  962. }
  963. break;
  964. default:
  965. idle++;
  966. break;
  967. }
  968. }
  969. });
  970. return {
  971. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  972. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  973. };
  974. // eslint-disable-next-line react-hooks/exhaustive-deps
  975. }, [printers, queryClient, cacheTick]);
  976. if (!printers?.length) return null;
  977. const badges: { count: number; dot: string; label: string }[] = [
  978. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  979. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  980. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  981. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  982. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  983. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  984. ];
  985. return (
  986. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  987. {badges.map(({ count, dot, label }) => count > 0 && (
  988. <div key={label} className="flex items-center gap-1.5">
  989. <div className={`w-2 h-2 rounded-full ${dot}`} />
  990. <span className="text-bambu-gray">
  991. <span className="text-white font-medium">{count}</span> {label}
  992. </span>
  993. </div>
  994. ))}
  995. {nextFinish && (
  996. <>
  997. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  998. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  999. <div className="flex items-center gap-2">
  1000. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1001. <span className="text-white font-medium">{nextFinish.name}</span>
  1002. </div>
  1003. <div className="flex items-center gap-2 w-full sm:w-auto">
  1004. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1005. <div
  1006. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1007. style={{ width: `${nextFinish.progress}%` }}
  1008. />
  1009. </div>
  1010. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1011. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1012. </div>
  1013. </div>
  1014. </>
  1015. )}
  1016. </div>
  1017. );
  1018. }
  1019. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1020. type ViewMode = 'expanded' | 'compact';
  1021. type ToolbarDropdownOption<T extends string> = {
  1022. value: T;
  1023. label: string;
  1024. };
  1025. function ToolbarDropdown<T extends string>({
  1026. value,
  1027. options,
  1028. onChange,
  1029. fullWidth = false,
  1030. }: {
  1031. value: T;
  1032. options: ToolbarDropdownOption<T>[];
  1033. onChange: (value: T) => void;
  1034. fullWidth?: boolean;
  1035. }) {
  1036. const [isOpen, setIsOpen] = useState(false);
  1037. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1038. return (
  1039. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1040. <button
  1041. type="button"
  1042. onClick={() => setIsOpen(open => !open)}
  1043. 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'}`}
  1044. >
  1045. <span className="truncate">{selectedOption?.label}</span>
  1046. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1047. </button>
  1048. {isOpen && (
  1049. <>
  1050. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1051. <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">
  1052. {options.map(option => (
  1053. <button
  1054. key={option.value}
  1055. type="button"
  1056. onClick={() => {
  1057. onChange(option.value);
  1058. setIsOpen(false);
  1059. }}
  1060. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1061. option.value === value ? 'text-bambu-green' : 'text-white'
  1062. }`}
  1063. >
  1064. {option.label}
  1065. </button>
  1066. ))}
  1067. </div>
  1068. </>
  1069. )}
  1070. </div>
  1071. );
  1072. }
  1073. function ToolbarMenu({
  1074. label,
  1075. icon,
  1076. children,
  1077. }: {
  1078. label: string;
  1079. icon: React.ReactNode;
  1080. children: React.ReactNode;
  1081. }) {
  1082. const [isOpen, setIsOpen] = useState(false);
  1083. return (
  1084. <div className="relative">
  1085. <button
  1086. type="button"
  1087. onClick={() => setIsOpen(open => !open)}
  1088. 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"
  1089. aria-label={label}
  1090. title={label}
  1091. >
  1092. {icon}
  1093. </button>
  1094. {isOpen && (
  1095. <>
  1096. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1097. <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">
  1098. {children}
  1099. </div>
  1100. </>
  1101. )}
  1102. </div>
  1103. );
  1104. }
  1105. function IndicatorControlPopover({
  1106. title,
  1107. options = [],
  1108. unit,
  1109. customMin,
  1110. customMax,
  1111. customStep = 1,
  1112. widthClass = 'w-[240px]',
  1113. popoverWidth = 240,
  1114. popoverHeight = 280,
  1115. isPending,
  1116. onClose,
  1117. onSubmit,
  1118. children,
  1119. }: {
  1120. title: string;
  1121. options?: Array<{ label: string; value: number }>;
  1122. unit?: string;
  1123. customMin?: number;
  1124. customMax?: number;
  1125. customStep?: number;
  1126. widthClass?: string;
  1127. popoverWidth?: number;
  1128. popoverHeight?: number;
  1129. isPending?: boolean;
  1130. onClose: () => void;
  1131. onSubmit?: (value: number) => void;
  1132. children?: React.ReactNode;
  1133. }) {
  1134. const anchorRef = useRef<HTMLSpanElement>(null);
  1135. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1136. const [customValue, setCustomValue] = useState('');
  1137. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1138. // can position via fixed coords. Portaling to document.body escapes
  1139. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1140. // own contexts and would otherwise cover the popover even at z-[60].
  1141. useLayoutEffect(() => {
  1142. const trigger = anchorRef.current?.parentElement;
  1143. if (!trigger) return;
  1144. const measure = () => {
  1145. const rect = trigger.getBoundingClientRect();
  1146. setCoords(computePopoverPosition({
  1147. triggerRect: rect,
  1148. popoverWidth,
  1149. estimatedHeight: popoverHeight,
  1150. horizontalAlign: 'center',
  1151. }));
  1152. };
  1153. measure();
  1154. window.addEventListener('resize', measure);
  1155. window.addEventListener('scroll', measure, true);
  1156. return () => {
  1157. window.removeEventListener('resize', measure);
  1158. window.removeEventListener('scroll', measure, true);
  1159. };
  1160. }, [popoverWidth, popoverHeight]);
  1161. const showCustomInput = unit !== undefined;
  1162. const submitCustom = () => {
  1163. const value = Number(customValue);
  1164. if (!Number.isFinite(value)) return;
  1165. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1166. onSubmit?.(Math.round(bounded));
  1167. };
  1168. return (
  1169. <>
  1170. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1171. {createPortal(
  1172. <>
  1173. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1174. <div
  1175. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1176. style={{
  1177. top: coords?.top ?? -9999,
  1178. left: coords?.left ?? -9999,
  1179. visibility: coords ? 'visible' : 'hidden',
  1180. }}
  1181. onClick={e => e.stopPropagation()}
  1182. >
  1183. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1184. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1185. {options.length > 0 && (
  1186. <div className="px-3 py-2.5">
  1187. <div className="grid grid-cols-2 gap-1.5">
  1188. {options.map(option => (
  1189. <button
  1190. key={`${option.label}-${option.value}`}
  1191. type="button"
  1192. disabled={isPending}
  1193. onClick={() => onSubmit?.(option.value)}
  1194. 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"
  1195. >
  1196. {option.label}
  1197. </button>
  1198. ))}
  1199. </div>
  1200. </div>
  1201. )}
  1202. {children}
  1203. {showCustomInput && (
  1204. <>
  1205. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1206. <form
  1207. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1208. onSubmit={(e) => {
  1209. e.preventDefault();
  1210. submitCustom();
  1211. }}
  1212. >
  1213. <input
  1214. type="number"
  1215. min={customMin}
  1216. max={customMax}
  1217. step={customStep}
  1218. value={customValue}
  1219. onChange={e => setCustomValue(e.target.value)}
  1220. placeholder="Custom"
  1221. 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"
  1222. />
  1223. <button
  1224. type="submit"
  1225. disabled={isPending || customValue.trim() === ''}
  1226. 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"
  1227. >
  1228. Set
  1229. </button>
  1230. </form>
  1231. </>
  1232. )}
  1233. </div>
  1234. </>,
  1235. document.body
  1236. )}
  1237. </>
  1238. );
  1239. }
  1240. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1241. function NozzleTemperatureControlBox({
  1242. label,
  1243. current,
  1244. target,
  1245. isActive,
  1246. isPending,
  1247. onSubmit,
  1248. options = NOZZLE_TEMPERATURE_OPTIONS,
  1249. }: {
  1250. label: string;
  1251. current?: number;
  1252. target?: number;
  1253. isActive: boolean;
  1254. isPending?: boolean;
  1255. onSubmit: (value: number) => void;
  1256. options?: Array<{ label: string; value: number }>;
  1257. }) {
  1258. const [customValue, setCustomValue] = useState('');
  1259. const submitCustom = () => {
  1260. const value = Number(customValue);
  1261. if (!Number.isFinite(value)) return;
  1262. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1263. };
  1264. return (
  1265. <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'}`}>
  1266. <div className="mb-1.5 flex items-center justify-between gap-2">
  1267. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1268. <span className="text-[10px] text-bambu-gray">
  1269. {Math.round(current ?? 0)}°C
  1270. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1271. </span>
  1272. </div>
  1273. <div className="grid grid-cols-2 gap-1">
  1274. {options.map(option => (
  1275. <button
  1276. key={`${label}-${option.value}`}
  1277. type="button"
  1278. disabled={isPending}
  1279. onClick={() => onSubmit(option.value)}
  1280. 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"
  1281. >
  1282. {option.label}
  1283. </button>
  1284. ))}
  1285. </div>
  1286. <form
  1287. className="mt-1.5 flex gap-1"
  1288. onSubmit={(e) => {
  1289. e.preventDefault();
  1290. submitCustom();
  1291. }}
  1292. >
  1293. <input
  1294. type="number"
  1295. min={0}
  1296. max={320}
  1297. step={1}
  1298. value={customValue}
  1299. onChange={e => setCustomValue(e.target.value)}
  1300. placeholder="Custom"
  1301. 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"
  1302. />
  1303. <button
  1304. type="submit"
  1305. disabled={isPending || customValue.trim() === ''}
  1306. 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"
  1307. >
  1308. Set
  1309. </button>
  1310. </form>
  1311. </div>
  1312. );
  1313. }
  1314. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1315. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1316. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1317. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1318. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1319. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1320. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1321. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1322. };
  1323. /** Classify a printer into one of the UI status buckets. */
  1324. function classifyPrinterStatus(
  1325. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1326. ): PrinterState {
  1327. if (!status?.connected) return 'offline';
  1328. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1329. if (hmsErrors.length > 0) return 'error';
  1330. switch (status.state) {
  1331. case 'RUNNING': return 'printing';
  1332. case 'PAUSE': return 'paused';
  1333. case 'FINISH': return 'finished';
  1334. // FAILED without an active HMS error is the printer's terminal state after
  1335. // any unsuccessful end — including user-cancellations. Treat the same as
  1336. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1337. // HMS code is actually attached (handled by the early-return above).
  1338. case 'FAILED': return 'finished';
  1339. default: return 'idle';
  1340. }
  1341. }
  1342. /**
  1343. * Get human-readable status display text for a printer.
  1344. * Uses stg_cur_name for detailed calibration/preparation stages,
  1345. * otherwise formats the gcode_state nicely.
  1346. */
  1347. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1348. // If we have a specific stage name (calibration, heating, etc.), use it
  1349. if (stg_cur_name) {
  1350. return stg_cur_name;
  1351. }
  1352. // Format the gcode_state nicely
  1353. switch (state) {
  1354. case 'RUNNING':
  1355. return 'Printing';
  1356. case 'PAUSE':
  1357. return 'Paused';
  1358. case 'FINISH':
  1359. return 'Finished';
  1360. case 'FAILED':
  1361. return 'Failed';
  1362. case 'IDLE':
  1363. return 'Idle';
  1364. default:
  1365. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1366. }
  1367. }
  1368. // Bambu models that ship with an enclosure chamber fan (firmware field
  1369. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1370. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1371. // widget is hidden in fanItems instead of rendered greyed-out.
  1372. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1373. 'X1C',
  1374. 'X1',
  1375. 'X1E',
  1376. 'X2D',
  1377. 'P1S',
  1378. 'P2S',
  1379. 'H2D',
  1380. 'H2D Pro',
  1381. 'H2C',
  1382. 'H2S',
  1383. ]);
  1384. // Map SSDP model codes to display names
  1385. function mapModelCode(ssdpModel: string | null): string {
  1386. if (!ssdpModel) return '';
  1387. const modelMap: Record<string, string> = {
  1388. // H2 Series
  1389. 'O1D': 'H2D',
  1390. 'O1E': 'H2D Pro',
  1391. 'O2D': 'H2D Pro',
  1392. 'O1C': 'H2C',
  1393. 'O1C2': 'H2C',
  1394. 'O1S': 'H2S',
  1395. // X1 Series
  1396. 'BL-P001': 'X1C',
  1397. 'BL-P002': 'X1',
  1398. 'BL-P003': 'X1E',
  1399. // X2 Series
  1400. 'N6': 'X2D',
  1401. // A2 Series
  1402. 'N9': 'A2L',
  1403. // P Series
  1404. 'C11': 'P1S',
  1405. 'C12': 'P1P',
  1406. 'C13': 'P2S',
  1407. // A1 Series
  1408. 'N2S': 'A1',
  1409. 'N1': 'A1 Mini',
  1410. // Direct matches
  1411. 'X1C': 'X1C',
  1412. 'X1': 'X1',
  1413. 'X1E': 'X1E',
  1414. 'X2D': 'X2D',
  1415. 'P1S': 'P1S',
  1416. 'P1P': 'P1P',
  1417. 'P2S': 'P2S',
  1418. 'A1': 'A1',
  1419. 'A1 Mini': 'A1 Mini',
  1420. 'A2L': 'A2L',
  1421. 'H2D': 'H2D',
  1422. 'H2D Pro': 'H2D Pro',
  1423. 'H2C': 'H2C',
  1424. 'H2S': 'H2S',
  1425. };
  1426. return modelMap[ssdpModel] || ssdpModel;
  1427. }
  1428. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1429. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1430. // • User-defined friendly name (editable, protected by printers:update)
  1431. // • AMS serial number
  1432. // • AMS firmware version
  1433. export function AmsNameHoverCard({
  1434. ams,
  1435. printerId,
  1436. label,
  1437. amsLabels,
  1438. canEdit,
  1439. onSaved,
  1440. children,
  1441. }: {
  1442. ams: import('../api/client').AMSUnit;
  1443. printerId: number;
  1444. label: string; // auto-generated label, e.g. "AMS-A"
  1445. amsLabels?: Record<number, string>;
  1446. canEdit: boolean;
  1447. onSaved: () => void;
  1448. children: React.ReactNode;
  1449. }) {
  1450. const { t } = useTranslation();
  1451. const [isVisible, setIsVisible] = useState(false);
  1452. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1453. const [editValue, setEditValue] = useState('');
  1454. const [isSaving, setIsSaving] = useState(false);
  1455. const [saveError, setSaveError] = useState<string | null>(null);
  1456. const [isInputFocused, setIsInputFocused] = useState(false);
  1457. const triggerRef = useRef<HTMLDivElement>(null);
  1458. const cardRef = useRef<HTMLDivElement>(null);
  1459. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1460. useEffect(() => {
  1461. if (isVisible) {
  1462. setEditValue(amsLabels?.[ams.id] ?? '');
  1463. setSaveError(null);
  1464. requestAnimationFrame(() => {
  1465. if (triggerRef.current && cardRef.current) {
  1466. const rect = triggerRef.current.getBoundingClientRect();
  1467. const spaceAbove = rect.top - 56;
  1468. const spaceBelow = window.innerHeight - rect.bottom;
  1469. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1470. }
  1471. });
  1472. }
  1473. }, [isVisible, amsLabels, ams.id]);
  1474. const handleMouseEnter = () => {
  1475. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1476. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1477. };
  1478. const handleMouseLeave = () => {
  1479. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1480. if (!isInputFocused) {
  1481. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1482. }
  1483. };
  1484. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1485. const handleSave = async () => {
  1486. if (!canEdit) return;
  1487. setIsSaving(true);
  1488. setSaveError(null);
  1489. try {
  1490. const trimmed = editValue.trim();
  1491. if (trimmed) {
  1492. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1493. } else {
  1494. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1495. }
  1496. onSaved();
  1497. setIsVisible(false);
  1498. } catch (err) {
  1499. setSaveError(err instanceof Error ? err.message : String(err));
  1500. } finally {
  1501. setIsSaving(false);
  1502. }
  1503. };
  1504. const handleClear = async () => {
  1505. if (!canEdit) return;
  1506. setIsSaving(true);
  1507. setSaveError(null);
  1508. try {
  1509. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1510. onSaved();
  1511. setIsVisible(false);
  1512. } catch (err) {
  1513. setSaveError(err instanceof Error ? err.message : String(err));
  1514. } finally {
  1515. setIsSaving(false);
  1516. }
  1517. };
  1518. return (
  1519. <div
  1520. ref={triggerRef}
  1521. className="relative inline-block"
  1522. onMouseEnter={handleMouseEnter}
  1523. onMouseLeave={handleMouseLeave}
  1524. >
  1525. {children}
  1526. {isVisible && (
  1527. <div
  1528. ref={cardRef}
  1529. className={`
  1530. absolute left-0 z-50
  1531. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1532. animate-in fade-in-0 zoom-in-95 duration-150
  1533. `}
  1534. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1535. onMouseEnter={handleMouseEnter}
  1536. onMouseLeave={handleMouseLeave}
  1537. >
  1538. <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">
  1539. {/* AMS auto-label */}
  1540. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1541. {/* Serial number */}
  1542. <div className="flex items-center justify-between gap-2">
  1543. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1544. {t('printers.amsPopup.serialNumber')}
  1545. </span>
  1546. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1547. </div>
  1548. {/* Firmware version */}
  1549. <div className="flex items-center justify-between gap-2">
  1550. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1551. {t('printers.amsPopup.firmwareVersion')}
  1552. </span>
  1553. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1554. </div>
  1555. {/* Friendly name editor */}
  1556. <div className="space-y-1">
  1557. <div className="flex items-center gap-2">
  1558. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1559. {t('printers.amsPopup.friendlyName')}
  1560. </span>
  1561. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1562. </div>
  1563. <input
  1564. type="text"
  1565. value={editValue}
  1566. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1567. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1568. onFocus={() => setIsInputFocused(true)}
  1569. onBlur={() => {
  1570. setIsInputFocused(false);
  1571. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1572. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1573. }}
  1574. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1575. disabled={!canEdit}
  1576. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1577. 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"
  1578. maxLength={100}
  1579. />
  1580. {canEdit && (
  1581. <div className="space-y-1">
  1582. {saveError && (
  1583. <p className="text-[10px] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1584. )}
  1585. <div className="flex gap-1 justify-end">
  1586. <button
  1587. onClick={handleSave}
  1588. disabled={isSaving}
  1589. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1590. >
  1591. {t('printers.amsPopup.save')}
  1592. </button>
  1593. {amsLabels?.[ams.id] && (
  1594. <button
  1595. onClick={handleClear}
  1596. disabled={isSaving}
  1597. 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"
  1598. >
  1599. {t('printers.amsPopup.clear')}
  1600. </button>
  1601. )}
  1602. </div>
  1603. </div>
  1604. )}
  1605. </div>
  1606. </div>
  1607. </div>
  1608. )}
  1609. </div>
  1610. );
  1611. }
  1612. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1613. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1614. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1615. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1616. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1617. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1618. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1619. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1620. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1621. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1622. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1623. };
  1624. function PrinterCard({
  1625. printer,
  1626. hideIfDisconnected,
  1627. maintenanceInfo,
  1628. viewMode = 'expanded',
  1629. cardSize = 2,
  1630. amsThresholds,
  1631. spoolmanEnabled = false,
  1632. linkedSpools,
  1633. spoolmanUrl,
  1634. spoolmanSyncMode,
  1635. onGetAssignment,
  1636. onUnassignSpool,
  1637. spoolmanSpools,
  1638. spoolmanSlotAssignments,
  1639. spoolmanLoading = false,
  1640. onUnassignSpoolmanSpool,
  1641. timeFormat = 'system',
  1642. cameraViewMode = 'window',
  1643. onOpenEmbeddedCamera,
  1644. checkPrinterFirmware = true,
  1645. dryingPresets = DRYING_PRESETS,
  1646. requirePlateClear = false,
  1647. selectionMode = false,
  1648. isSelected = false,
  1649. onToggleSelect,
  1650. onOpenCompactCard,
  1651. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1652. bedTempPresets = BED_TEMP_DEFAULTS,
  1653. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1654. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1655. }: {
  1656. printer: Printer;
  1657. hideIfDisconnected?: boolean;
  1658. maintenanceInfo?: PrinterMaintenanceInfo;
  1659. viewMode?: ViewMode;
  1660. cardSize?: number;
  1661. amsThresholds?: {
  1662. humidityGood: number;
  1663. humidityFair: number;
  1664. tempGood: number;
  1665. tempFair: number;
  1666. };
  1667. spoolmanEnabled?: boolean;
  1668. hasUnlinkedSpools?: boolean;
  1669. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1670. spoolmanUrl?: string | null;
  1671. spoolmanSyncMode?: string | null;
  1672. spoolAssignments?: SpoolAssignment[];
  1673. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1674. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1675. spoolmanSpools?: InventorySpool[];
  1676. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1677. spoolmanLoading?: boolean;
  1678. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1679. timeFormat?: 'system' | '12h' | '24h';
  1680. cameraViewMode?: 'window' | 'embedded';
  1681. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1682. checkPrinterFirmware?: boolean;
  1683. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1684. requirePlateClear?: boolean;
  1685. selectionMode?: boolean;
  1686. isSelected?: boolean;
  1687. onToggleSelect?: (id: number) => void;
  1688. onOpenCompactCard?: (id: number) => void;
  1689. nozzleTempPresets?: readonly [number, number, number];
  1690. bedTempPresets?: readonly [number, number, number];
  1691. chamberTempPresets?: readonly [number, number, number];
  1692. fanSpeedPresets?: readonly [number, number, number];
  1693. }) {
  1694. const { t } = useTranslation();
  1695. const queryClient = useQueryClient();
  1696. const navigate = useNavigate();
  1697. const { showToast } = useToast();
  1698. const { hasPermission } = useAuth();
  1699. const [showMenu, setShowMenu] = useState(false);
  1700. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1701. const [deleteArchives, setDeleteArchives] = useState(true);
  1702. const [showEditModal, setShowEditModal] = useState(false);
  1703. const [showFileManager, setShowFileManager] = useState(false);
  1704. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1705. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1706. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1707. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1708. const [showHMSModal, setShowHMSModal] = useState(false);
  1709. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1710. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1711. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1712. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1713. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1714. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1715. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1716. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1717. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1718. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1719. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1720. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1721. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1722. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1723. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1724. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1725. // AMS drying popover state: which AMS unit has the popover open
  1726. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1727. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1728. const [dryingFilament, setDryingFilament] = useState('PLA');
  1729. const [dryingTemp, setDryingTemp] = useState(50);
  1730. const [dryingDuration, setDryingDuration] = useState(4);
  1731. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1732. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1733. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  1734. // an object rather than a bare id so restarting drying on the SAME unit produces
  1735. // a new identity and rearms the timeout below.
  1736. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  1737. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1738. const [isDropUploading, setIsDropUploading] = useState(false);
  1739. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1740. const dragCounterRef = useRef(0);
  1741. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1742. amsId: number;
  1743. amsLabel: string;
  1744. mode: 'humidity' | 'temperature';
  1745. } | null>(null);
  1746. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1747. initialKind: HeaterSensorKind;
  1748. availableKinds: HeaterSensorKind[];
  1749. } | null>(null);
  1750. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1751. tagUid: string;
  1752. trayUuid: string;
  1753. printerId: number;
  1754. amsId: number;
  1755. trayId: number;
  1756. } | null>(null);
  1757. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1758. printerId: number;
  1759. amsId: number;
  1760. trayId: number;
  1761. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1762. } | null>(null);
  1763. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1764. amsId: number;
  1765. trayId: number;
  1766. trayCount: number;
  1767. trayType?: string;
  1768. trayColor?: string;
  1769. traySubBrands?: string;
  1770. trayInfoIdx?: string;
  1771. extruderId?: number;
  1772. caliIdx?: number | null;
  1773. savedPresetId?: string;
  1774. } | null>(null);
  1775. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1776. const [plateCheckResult, setPlateCheckResult] = useState<{
  1777. is_empty: boolean;
  1778. confidence: number;
  1779. difference_percent: number;
  1780. message: string;
  1781. debug_image_url?: string;
  1782. needs_calibration: boolean;
  1783. light_warning?: boolean;
  1784. reference_count?: number;
  1785. max_references?: number;
  1786. roi?: { x: number; y: number; w: number; h: number };
  1787. } | null>(null);
  1788. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1789. const [isCalibrating, setIsCalibrating] = useState(false);
  1790. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1791. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1792. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1793. const { data: status } = useQuery({
  1794. queryKey: ['printerStatus', printer.id],
  1795. queryFn: () => api.getPrinterStatus(printer.id),
  1796. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1797. });
  1798. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1799. const { data: firmwareInfo } = useQuery({
  1800. queryKey: ['firmwareUpdate', printer.id],
  1801. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1802. staleTime: 5 * 60 * 1000,
  1803. refetchInterval: 5 * 60 * 1000,
  1804. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1805. });
  1806. // Collect unique tray_info_idx values for cloud filament info lookup
  1807. const trayInfoIds = useMemo(() => {
  1808. const ids = new Set<string>();
  1809. if (status?.ams) {
  1810. for (const ams of status.ams) {
  1811. for (const tray of ams.tray || []) {
  1812. if (tray.tray_info_idx) {
  1813. ids.add(tray.tray_info_idx);
  1814. }
  1815. }
  1816. }
  1817. }
  1818. for (const vt of status?.vt_tray ?? []) {
  1819. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1820. }
  1821. if (status?.nozzle_rack) {
  1822. for (const slot of status.nozzle_rack) {
  1823. if (slot.filament_id) {
  1824. ids.add(slot.filament_id);
  1825. }
  1826. }
  1827. }
  1828. return Array.from(ids);
  1829. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1830. // Collect loaded filament types for queue widget filtering
  1831. const loadedFilamentTypes = useMemo(() => {
  1832. const types = new Set<string>();
  1833. if (status?.ams) {
  1834. for (const ams of status.ams) {
  1835. for (const tray of ams.tray || []) {
  1836. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1837. }
  1838. }
  1839. }
  1840. for (const vt of status?.vt_tray ?? []) {
  1841. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1842. }
  1843. return types;
  1844. }, [status?.ams, status?.vt_tray]);
  1845. // Collect loaded filament type+color pairs for queue widget override matching
  1846. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1847. const loadedFilaments = useMemo(() => {
  1848. const filaments = new Set<string>();
  1849. if (status?.ams) {
  1850. for (const ams of status.ams) {
  1851. for (const tray of ams.tray || []) {
  1852. if (tray.tray_type && tray.tray_color) {
  1853. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1854. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1855. }
  1856. }
  1857. }
  1858. }
  1859. for (const vt of status?.vt_tray ?? []) {
  1860. if (vt.tray_type && vt.tray_color) {
  1861. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1862. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1863. }
  1864. }
  1865. return filaments;
  1866. }, [status?.ams, status?.vt_tray]);
  1867. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1868. const { data: filamentInfo } = useQuery({
  1869. queryKey: ['filamentInfo', trayInfoIds],
  1870. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1871. enabled: trayInfoIds.length > 0,
  1872. staleTime: 5 * 60 * 1000, // 5 minutes
  1873. });
  1874. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1875. const { data: slotPresets } = useQuery({
  1876. queryKey: ['slotPresets', printer.id],
  1877. queryFn: () => api.getSlotPresets(printer.id),
  1878. staleTime: 2 * 60 * 1000, // 2 minutes
  1879. });
  1880. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1881. // Only queried when there's a running print backed by an archive; shared
  1882. // React Query cache with the Queue / Archives pages keeps it cheap.
  1883. const activeArchiveId =
  1884. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1885. const { data: activeArchivePlates } = useQuery({
  1886. queryKey: ['archive-plates', activeArchiveId],
  1887. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1888. enabled: activeArchiveId != null,
  1889. staleTime: 5 * 60 * 1000,
  1890. });
  1891. const activePlateLabel = (() => {
  1892. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1893. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1894. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1895. })();
  1896. // Fetch user-defined AMS friendly names from the database
  1897. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1898. queryKey: ['amsLabels', printer.id],
  1899. queryFn: () => api.getAmsLabels(printer.id),
  1900. staleTime: 5 * 60 * 1000, // 5 minutes
  1901. });
  1902. // Cache WiFi signal to prevent it disappearing on updates
  1903. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1904. useEffect(() => {
  1905. if (status?.wifi_signal != null) {
  1906. setCachedWifiSignal(status.wifi_signal);
  1907. }
  1908. }, [status?.wifi_signal]);
  1909. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1910. // Cache connected state to prevent flicker when status briefly becomes undefined
  1911. const cachedConnected = useRef<boolean | undefined>(undefined);
  1912. useEffect(() => {
  1913. if (status?.connected !== undefined) {
  1914. cachedConnected.current = status.connected;
  1915. }
  1916. }, [status?.connected]);
  1917. const isConnected = status?.connected ?? cachedConnected.current;
  1918. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1919. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1920. useEffect(() => {
  1921. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1922. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1923. }
  1924. }, [status?.ams_extruder_map]);
  1925. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1926. ? status.ams_extruder_map
  1927. : cachedAmsExtruderMap.current;
  1928. // Cache AMS data to prevent it disappearing on idle/offline printers
  1929. const cachedAmsData = useRef<AMSUnit[]>([]);
  1930. useEffect(() => {
  1931. if (status?.ams && status.ams.length > 0) {
  1932. cachedAmsData.current = status.ams;
  1933. }
  1934. }, [status?.ams]);
  1935. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1936. // Confirm a drying cycle actually started (#2533). Firmware answers
  1937. // ams_filament_drying with result=success even when it then silently declines,
  1938. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  1939. // reason guard is blind there and the card just sits unchanged. Watch the unit
  1940. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  1941. // means the printer took the command and dropped it.
  1942. useEffect(() => {
  1943. if (!dryStartWatch) return;
  1944. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  1945. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  1946. }, [dryStartWatch, amsData]);
  1947. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  1948. // otherwise rearm the timeout on every frame, so it would never elapse.
  1949. useEffect(() => {
  1950. if (!dryStartWatch) return;
  1951. const timer = setTimeout(() => {
  1952. setDryStartWatch(null);
  1953. showToast(t('printers.drying.toastNotStarted'), 'error');
  1954. }, DRY_START_CONFIRM_MS);
  1955. return () => clearTimeout(timer);
  1956. }, [dryStartWatch, showToast, t]);
  1957. // Cache tray_now to prevent flickering when undefined values come in
  1958. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  1959. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  1960. const cachedTrayNow = useRef<number | undefined>(undefined);
  1961. const currentTrayNow = status?.tray_now;
  1962. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  1963. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  1964. cachedTrayNow.current = currentTrayNow;
  1965. } else if (currentTrayNow === 255) {
  1966. cachedTrayNow.current = undefined;
  1967. }
  1968. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  1969. ? currentTrayNow
  1970. : cachedTrayNow.current;
  1971. // Fetch smart plug for this printer
  1972. const { data: smartPlug } = useQuery({
  1973. queryKey: ['smartPlugByPrinter', printer.id],
  1974. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  1975. });
  1976. // Fetch script plugs for this printer (for multi-device control)
  1977. const { data: scriptPlugs } = useQuery({
  1978. queryKey: ['scriptPlugsByPrinter', printer.id],
  1979. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  1980. });
  1981. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  1982. const { data: plugStatus } = useQuery({
  1983. queryKey: ['smartPlugStatus', smartPlug?.id],
  1984. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  1985. enabled: !!smartPlug,
  1986. refetchInterval: 10000, // 10 seconds for real-time power display
  1987. });
  1988. // Fetch queue count for this printer
  1989. const { data: queueItems } = useQuery({
  1990. queryKey: ['queue', printer.id, 'pending'],
  1991. queryFn: () => api.getQueue(printer.id, 'pending'),
  1992. });
  1993. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  1994. // so the badge only shows on printers that can actually run the queued jobs.
  1995. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  1996. const queueCount = useMemo(() => {
  1997. if (!queueItems?.length) return 0;
  1998. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments).length;
  1999. }, [queueItems, loadedFilamentTypes, loadedFilaments]);
  2000. // Fetch currently printing queue item to show who started it (Issue #206)
  2001. const { data: printingQueueItems } = useQuery({
  2002. queryKey: ['queue', printer.id, 'printing'],
  2003. queryFn: () => api.getQueue(printer.id, 'printing'),
  2004. enabled: status?.state === 'RUNNING',
  2005. });
  2006. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2007. const { data: reprintUser } = useQuery({
  2008. queryKey: ['currentPrintUser', printer.id],
  2009. queryFn: () => api.getCurrentPrintUser(printer.id),
  2010. enabled: status?.state === 'RUNNING',
  2011. });
  2012. // Combine both sources: queue item user takes precedence, then reprint user
  2013. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2014. // Fetch last completed print for this printer
  2015. const { data: lastPrints } = useQuery({
  2016. queryKey: ['archives', printer.id, 'last'],
  2017. queryFn: () => api.getArchives(printer.id, 1, 0),
  2018. enabled: status?.connected && status?.state !== 'RUNNING',
  2019. });
  2020. const lastPrint = lastPrints?.[0];
  2021. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2022. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2023. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2024. const activePrintName = status?.current_print && isPrintingOrPaused
  2025. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2026. : null;
  2027. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2028. useEffect(() => {
  2029. if (activePrintName) {
  2030. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2031. } else if (!needsPlateClear) {
  2032. setRetainedPrintJob(null);
  2033. }
  2034. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2035. const plateStatus = (() => {
  2036. if (!requirePlateClear || !status?.connected) return null;
  2037. if (isPrintingOrPaused) {
  2038. return {
  2039. label: t('printers.plateStatus.inUse'),
  2040. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2041. };
  2042. }
  2043. if (status.awaiting_plate_clear) {
  2044. return {
  2045. label: t('printers.plateStatus.notCleared'),
  2046. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2047. };
  2048. }
  2049. return {
  2050. label: t('printers.plateStatus.cleared'),
  2051. className: 'bg-status-ok/20 text-status-ok',
  2052. };
  2053. })();
  2054. const plateStatusPill = plateStatus ? (
  2055. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2056. {plateStatus.label}
  2057. </span>
  2058. ) : null;
  2059. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2060. const shouldHide = hideIfDisconnected && isConnected === false;
  2061. const deleteMutation = useMutation({
  2062. mutationFn: (options: { deleteArchives: boolean }) =>
  2063. api.deletePrinter(printer.id, options.deleteArchives),
  2064. onSuccess: () => {
  2065. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2066. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2067. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2068. },
  2069. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2070. });
  2071. const connectMutation = useMutation({
  2072. mutationFn: () => api.connectPrinter(printer.id),
  2073. onSuccess: () => {
  2074. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2075. },
  2076. });
  2077. const forceRefreshMutation = useMutation({
  2078. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2079. onSuccess: () => {
  2080. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2081. showToast(t('printers.forceRefreshSuccess'), 'success');
  2082. },
  2083. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2084. });
  2085. const unlinkSpoolMutation = useMutation({
  2086. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2087. onSuccess: (result) => {
  2088. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2089. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2090. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2091. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2092. },
  2093. onError: (error: Error) => {
  2094. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2095. },
  2096. });
  2097. // AMS drying mutations
  2098. const startDryingMutation = useMutation({
  2099. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2100. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2101. onSuccess: (_data, { amsId }) => {
  2102. setDryingPopoverAmsId(null);
  2103. setDryStartWatch({ amsId });
  2104. // "Command sent", not "drying started" — at this point the printer has only
  2105. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2106. // the cycle is genuinely live; the watcher below covers the case where it
  2107. // never appears.
  2108. showToast(t('printers.drying.toastCommandSent'), 'success');
  2109. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2110. },
  2111. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2112. });
  2113. const stopDryingMutation = useMutation({
  2114. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2115. onSuccess: () => {
  2116. setDryStartWatch(null);
  2117. showToast(t('printers.drying.toastStopped'), 'success');
  2118. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2119. },
  2120. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2121. });
  2122. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2123. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2124. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2125. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2126. // showing the old backup state until the user reopens it.
  2127. const setAmsBackupMutation = useMutation({
  2128. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2129. onSuccess: (_data, enabled) => {
  2130. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2131. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2132. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2133. },
  2134. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2135. });
  2136. // Smart plug control mutations
  2137. const powerControlMutation = useMutation({
  2138. mutationFn: (action: 'on' | 'off') =>
  2139. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2140. onSuccess: () => {
  2141. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2142. },
  2143. });
  2144. const toggleAutoOffMutation = useMutation({
  2145. mutationFn: (enabled: boolean) =>
  2146. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2147. onSuccess: () => {
  2148. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2149. // Also invalidate the smart-plugs list to keep Settings page in sync
  2150. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2151. },
  2152. });
  2153. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2154. const runScriptMutation = useMutation({
  2155. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2156. onSuccess: () => {
  2157. showToast(t('printers.toast.scriptTriggered'));
  2158. },
  2159. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2160. });
  2161. // Print control mutations
  2162. const stopPrintMutation = useMutation({
  2163. mutationFn: () => api.stopPrint(printer.id),
  2164. onSuccess: () => {
  2165. showToast(t('printers.toast.printStopped'));
  2166. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2167. },
  2168. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2169. });
  2170. const pausePrintMutation = useMutation({
  2171. mutationFn: () => api.pausePrint(printer.id),
  2172. onSuccess: () => {
  2173. showToast(t('printers.toast.printPaused'));
  2174. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2175. },
  2176. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2177. });
  2178. const resumePrintMutation = useMutation({
  2179. mutationFn: () => api.resumePrint(printer.id),
  2180. onSuccess: () => {
  2181. showToast(t('printers.toast.printResumed'));
  2182. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2183. },
  2184. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2185. });
  2186. const clearPlateMutation = useMutation({
  2187. mutationFn: () => api.clearPlate(printer.id),
  2188. onSuccess: () => {
  2189. showToast(t('queue.clearPlateSuccess'));
  2190. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2191. old ? { ...old, awaiting_plate_clear: false } : old
  2192. );
  2193. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2194. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2195. },
  2196. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2197. });
  2198. const nozzleTemperatureMutation = useMutation({
  2199. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2200. api.setNozzleTemperature(printer.id, target, nozzle),
  2201. onSuccess: (result) => {
  2202. setStatusControlMenu(null);
  2203. showToast(result.message);
  2204. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2205. },
  2206. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2207. });
  2208. const bedTemperatureMutation = useMutation({
  2209. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2210. onSuccess: (result) => {
  2211. setStatusControlMenu(null);
  2212. showToast(result.message);
  2213. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2214. },
  2215. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2216. });
  2217. const chamberTemperatureMutation = useMutation({
  2218. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2219. onSuccess: (result) => {
  2220. setStatusControlMenu(null);
  2221. showToast(result.message);
  2222. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2223. },
  2224. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2225. });
  2226. const fanSpeedMutation = useMutation({
  2227. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'chamber'; speed: number }) =>
  2228. api.setFanSpeed(printer.id, fan, speed),
  2229. onMutate: async ({ fan, speed }) => {
  2230. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2231. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2232. const fanField = {
  2233. part: 'cooling_fan_speed',
  2234. aux: 'big_fan1_speed',
  2235. chamber: 'big_fan2_speed',
  2236. }[fan];
  2237. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2238. old ? { ...old, [fanField]: speed } : old
  2239. );
  2240. return { previousStatus };
  2241. },
  2242. onSuccess: (result) => {
  2243. setStatusControlMenu(null);
  2244. showToast(result.message);
  2245. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2246. },
  2247. onError: (error: Error, _variables, context) => {
  2248. if (context?.previousStatus) {
  2249. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2250. }
  2251. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2252. },
  2253. });
  2254. const selectExtruderMutation = useMutation({
  2255. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2256. onMutate: async (extruder) => {
  2257. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2258. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2259. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2260. old ? { ...old, active_extruder: extruder } : old
  2261. );
  2262. return { previousStatus };
  2263. },
  2264. onSuccess: (result) => {
  2265. setStatusControlMenu(null);
  2266. showToast(result.message);
  2267. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2268. },
  2269. onError: (error: Error, _extruder, context) => {
  2270. if (context?.previousStatus) {
  2271. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2272. }
  2273. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2274. },
  2275. });
  2276. // Chamber light mutation with optimistic update
  2277. const chamberLightMutation = useMutation({
  2278. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2279. onMutate: async (on) => {
  2280. // Cancel any outgoing refetches
  2281. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2282. // Snapshot the previous value
  2283. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2284. // Optimistically update
  2285. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2286. ...old,
  2287. chamber_light: on,
  2288. }));
  2289. return { previousStatus };
  2290. },
  2291. onSuccess: (_, on) => {
  2292. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2293. },
  2294. onError: (error: Error, _, context) => {
  2295. // Rollback on error
  2296. if (context?.previousStatus) {
  2297. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2298. }
  2299. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2300. },
  2301. });
  2302. // Print speed mutation with optimistic update
  2303. const printSpeedMutation = useMutation({
  2304. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2305. onMutate: async (mode) => {
  2306. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2307. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2308. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2309. ...old,
  2310. speed_level: mode,
  2311. }));
  2312. return { previousStatus };
  2313. },
  2314. onError: (error: Error, _, context) => {
  2315. if (context?.previousStatus) {
  2316. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2317. }
  2318. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2319. },
  2320. });
  2321. const airductMutation = useMutation({
  2322. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2323. onMutate: async (mode) => {
  2324. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2325. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2326. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2327. ...old,
  2328. airduct_mode: mode === 'cooling' ? 0 : 1,
  2329. }));
  2330. return { previousStatus };
  2331. },
  2332. onError: (error: Error, _, context) => {
  2333. if (context?.previousStatus) {
  2334. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2335. }
  2336. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2337. },
  2338. });
  2339. const bedJogMutation = useMutation({
  2340. mutationFn: ({ distance }: { distance: number }) =>
  2341. api.bedJog(printer.id, distance),
  2342. onError: (error: Error) =>
  2343. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2344. });
  2345. const xyJogMutation = useMutation({
  2346. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2347. api.xyJog(printer.id, x, y),
  2348. onError: (error: Error) =>
  2349. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2350. });
  2351. const extruderJogMutation = useMutation({
  2352. mutationFn: (distance: number) =>
  2353. api.extruderJog(printer.id, distance),
  2354. onError: (error: Error) =>
  2355. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2356. });
  2357. const homeAxesMutation = useMutation({
  2358. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2359. onSuccess: () => {
  2360. showToast(t('printers.bedJog.homingStarted'));
  2361. },
  2362. onError: (error: Error) =>
  2363. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2364. });
  2365. // Plate detection setting mutation
  2366. const plateDetectionMutation = useMutation({
  2367. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2368. onSuccess: () => {
  2369. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2370. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2371. },
  2372. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2373. });
  2374. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2375. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2376. // metrics, and the print picker — so flipping this flag puts the printer
  2377. // out of service across every consumer in one place. Used from the
  2378. // overflow menu and EditPrinterModal.
  2379. const maintenanceMutation = useMutation({
  2380. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2381. onSuccess: (_data, isActive) => {
  2382. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2383. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2384. showToast(
  2385. isActive
  2386. ? t('printers.maintenance.toastExited', { name: printer.name })
  2387. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2388. 'success',
  2389. );
  2390. },
  2391. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2392. });
  2393. // Confirm before entering maintenance on a printing printer (entering mode
  2394. // disconnects MQTT, which stops progress tracking + completion notifications
  2395. // for the in-flight job).
  2396. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2397. const handleEnterMaintenance = () => {
  2398. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2399. setConfirmMaintenanceEnter(true);
  2400. } else {
  2401. maintenanceMutation.mutate(false);
  2402. }
  2403. };
  2404. // Query for printable objects (for skip functionality)
  2405. // Fetch when printing with 2+ objects OR when modal is open
  2406. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2407. const { data: objectsData } = useQuery({
  2408. queryKey: ['printableObjects', printer.id],
  2409. queryFn: () => api.getPrintableObjects(printer.id),
  2410. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2411. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2412. });
  2413. // State for tracking which AMS slot is being refreshed
  2414. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2415. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2416. const seenBusyStateRef = useRef<boolean>(false);
  2417. // Fallback timeout ref
  2418. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2419. // Minimum display time passed
  2420. const minTimePassedRef = useRef<boolean>(false);
  2421. // AMS slot refresh mutation
  2422. const refreshAmsSlotMutation = useMutation({
  2423. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2424. api.refreshAmsSlot(printer.id, amsId, slotId),
  2425. onMutate: ({ amsId, slotId }) => {
  2426. // Clear any existing timeout
  2427. if (refreshTimeoutRef.current) {
  2428. clearTimeout(refreshTimeoutRef.current);
  2429. }
  2430. // Reset state
  2431. seenBusyStateRef.current = false;
  2432. minTimePassedRef.current = false;
  2433. setRefreshingSlot({ amsId, slotId });
  2434. // Minimum display time (2 seconds)
  2435. setTimeout(() => {
  2436. minTimePassedRef.current = true;
  2437. }, 2000);
  2438. // Fallback timeout (30 seconds max)
  2439. refreshTimeoutRef.current = setTimeout(() => {
  2440. setRefreshingSlot(null);
  2441. }, 30000);
  2442. },
  2443. onSuccess: (data) => {
  2444. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2445. },
  2446. onError: (error: Error) => {
  2447. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2448. if (refreshTimeoutRef.current) {
  2449. clearTimeout(refreshTimeoutRef.current);
  2450. }
  2451. setRefreshingSlot(null);
  2452. },
  2453. });
  2454. // AMS load/unload mutations (#891)
  2455. const loadAmsTrayMutation = useMutation({
  2456. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2457. onSuccess: (data) => {
  2458. showToast(data.message || t('printers.toast.loadInitiated'));
  2459. },
  2460. onError: (error: Error) => {
  2461. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2462. },
  2463. });
  2464. const unloadAmsMutation = useMutation({
  2465. mutationFn: () => api.unloadAms(printer.id),
  2466. onSuccess: (data) => {
  2467. showToast(data.message || t('printers.toast.unloadInitiated'));
  2468. },
  2469. onError: (error: Error) => {
  2470. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2471. },
  2472. });
  2473. // Plate references state
  2474. const [plateReferences, setPlateReferences] = useState<{
  2475. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2476. max_references: number;
  2477. } | null>(null);
  2478. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2479. // Fetch plate references
  2480. const fetchPlateReferences = async () => {
  2481. try {
  2482. const data = await api.getPlateReferences(printer.id);
  2483. setPlateReferences(data);
  2484. } catch {
  2485. // Ignore errors - references will show as empty
  2486. }
  2487. };
  2488. // Toggle plate detection enabled/disabled
  2489. const handleTogglePlateDetection = () => {
  2490. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2491. };
  2492. // Open plate detection management modal (for calibration/references)
  2493. const handleOpenPlateManagement = async () => {
  2494. setIsCheckingPlate(true);
  2495. setPlateCheckResult(null);
  2496. // Auto-turn on light if it's off
  2497. const lightWasOff = status?.chamber_light === false;
  2498. setPlateCheckLightWasOff(lightWasOff);
  2499. if (lightWasOff) {
  2500. await api.setChamberLight(printer.id, true);
  2501. // Wait for light to physically turn on and camera to adjust exposure
  2502. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2503. await new Promise(resolve => setTimeout(resolve, 2500));
  2504. }
  2505. try {
  2506. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2507. setPlateCheckResult(result);
  2508. fetchPlateReferences();
  2509. } catch (error) {
  2510. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2511. // Restore light if check failed
  2512. if (lightWasOff) {
  2513. await api.setChamberLight(printer.id, false);
  2514. setPlateCheckLightWasOff(false);
  2515. }
  2516. } finally {
  2517. setIsCheckingPlate(false);
  2518. }
  2519. };
  2520. // Close plate check modal and restore light state
  2521. const closePlateCheckModal = useCallback(async () => {
  2522. setPlateCheckResult(null);
  2523. // Restore light to original state if we turned it on
  2524. if (plateCheckLightWasOff) {
  2525. await api.setChamberLight(printer.id, false);
  2526. setPlateCheckLightWasOff(false);
  2527. }
  2528. }, [plateCheckLightWasOff, printer.id]);
  2529. // Calibrate plate detection handler
  2530. const handleCalibratePlate = async (label?: string) => {
  2531. setIsCalibrating(true);
  2532. try {
  2533. const result = await api.calibratePlateDetection(printer.id, { label });
  2534. if (result.success) {
  2535. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2536. // Refresh references and re-check
  2537. fetchPlateReferences();
  2538. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2539. setPlateCheckResult(checkResult);
  2540. } else {
  2541. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2542. }
  2543. } catch (error) {
  2544. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2545. } finally {
  2546. setIsCalibrating(false);
  2547. }
  2548. };
  2549. // Update reference label
  2550. const handleUpdateRefLabel = async (index: number, label: string) => {
  2551. try {
  2552. await api.updatePlateReferenceLabel(printer.id, index, label);
  2553. setEditingRefLabel(null);
  2554. fetchPlateReferences();
  2555. } catch (error) {
  2556. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2557. }
  2558. };
  2559. // Delete reference
  2560. const handleDeleteRef = async (index: number) => {
  2561. try {
  2562. await api.deletePlateReference(printer.id, index);
  2563. showToast(t('printers.toast.referenceDeleted'), 'success');
  2564. fetchPlateReferences();
  2565. // Re-check to update counts
  2566. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2567. setPlateCheckResult(checkResult);
  2568. } catch (error) {
  2569. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2570. }
  2571. };
  2572. // Save ROI settings
  2573. const handleSaveRoi = async () => {
  2574. if (!editingRoi) return;
  2575. setIsSavingRoi(true);
  2576. try {
  2577. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2578. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2579. setEditingRoi(null);
  2580. // Re-check to see new ROI in action
  2581. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2582. setPlateCheckResult(checkResult);
  2583. } catch (error) {
  2584. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2585. } finally {
  2586. setIsSavingRoi(false);
  2587. }
  2588. };
  2589. // Close plate check modal on Escape key
  2590. useEffect(() => {
  2591. const handleEscape = (e: KeyboardEvent) => {
  2592. if (e.key === 'Escape' && plateCheckResult) {
  2593. closePlateCheckModal();
  2594. }
  2595. };
  2596. window.addEventListener('keydown', handleEscape);
  2597. return () => window.removeEventListener('keydown', handleEscape);
  2598. }, [plateCheckResult, closePlateCheckModal]);
  2599. // Watch ams_status_main to detect when RFID read completes
  2600. // ams_status_main: 0=idle, 2=rfid_identifying
  2601. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2602. useEffect(() => {
  2603. if (!refreshingSlot) return;
  2604. const amsStatus = status?.ams_status_main ?? 0;
  2605. // Track when we see non-idle state (printer is working)
  2606. if (amsStatus !== 0) {
  2607. seenBusyStateRef.current = true;
  2608. // Cancel any deferred clear since we're back to busy
  2609. if (deferredClearRef.current) {
  2610. clearTimeout(deferredClearRef.current);
  2611. deferredClearRef.current = null;
  2612. }
  2613. }
  2614. // When we've seen busy and now idle, clear (with min time check)
  2615. if (seenBusyStateRef.current && amsStatus === 0) {
  2616. if (minTimePassedRef.current) {
  2617. // Min time passed - clear now
  2618. if (refreshTimeoutRef.current) {
  2619. clearTimeout(refreshTimeoutRef.current);
  2620. }
  2621. setRefreshingSlot(null);
  2622. } else {
  2623. // Schedule clear after min time (2 seconds from start)
  2624. if (!deferredClearRef.current) {
  2625. deferredClearRef.current = setTimeout(() => {
  2626. if (refreshTimeoutRef.current) {
  2627. clearTimeout(refreshTimeoutRef.current);
  2628. }
  2629. setRefreshingSlot(null);
  2630. }, 2000);
  2631. }
  2632. }
  2633. }
  2634. return () => {
  2635. if (deferredClearRef.current) {
  2636. clearTimeout(deferredClearRef.current);
  2637. }
  2638. };
  2639. }, [status?.ams_status_main, refreshingSlot]);
  2640. useEffect(() => {
  2641. if (!showMenu) return;
  2642. const handleClickOutside = (event: MouseEvent) => {
  2643. const target = event.target as Node;
  2644. if (!printerActionsMenuRef.current?.contains(target)) {
  2645. setShowMenu(false);
  2646. }
  2647. };
  2648. document.addEventListener('mousedown', handleClickOutside);
  2649. return () => document.removeEventListener('mousedown', handleClickOutside);
  2650. }, [showMenu]);
  2651. if (shouldHide) {
  2652. return null;
  2653. }
  2654. // Size-based styling helpers
  2655. const getImageSize = () => {
  2656. switch (cardSize) {
  2657. case 1: return 'w-10 h-10';
  2658. case 2: return 'w-14 h-14';
  2659. case 3: return 'w-16 h-16';
  2660. case 4: return 'w-20 h-20';
  2661. default: return 'w-14 h-14';
  2662. }
  2663. };
  2664. const getTitleSize = () => {
  2665. switch (cardSize) {
  2666. case 1: return 'text-base truncate';
  2667. case 2: return 'text-lg';
  2668. case 3: return 'text-xl';
  2669. case 4: return 'text-2xl';
  2670. default: return 'text-lg';
  2671. }
  2672. };
  2673. const getSpacing = () => {
  2674. switch (cardSize) {
  2675. case 1: return 'mb-2';
  2676. case 2: return 'mb-4';
  2677. case 3: return 'mb-5';
  2678. case 4: return 'mb-6';
  2679. default: return 'mb-4';
  2680. }
  2681. };
  2682. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2683. const handleCardDragEnter = (e: React.DragEvent) => {
  2684. e.preventDefault();
  2685. dragCounterRef.current++;
  2686. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2687. };
  2688. const handleCardDragOver = (e: React.DragEvent) => {
  2689. e.preventDefault();
  2690. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2691. };
  2692. const handleCardDragLeave = (e: React.DragEvent) => {
  2693. e.preventDefault();
  2694. dragCounterRef.current--;
  2695. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2696. };
  2697. const handleCardDrop = async (e: React.DragEvent) => {
  2698. e.preventDefault();
  2699. dragCounterRef.current = 0;
  2700. setIsDraggingFile(false);
  2701. if (!canDrop) return;
  2702. const droppedFiles = Array.from(e.dataTransfer.files);
  2703. const file = droppedFiles[0];
  2704. if (!file) return;
  2705. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2706. const lower = file.name.toLowerCase();
  2707. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2708. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2709. return;
  2710. }
  2711. setIsDropUploading(true);
  2712. try {
  2713. const result = await api.uploadLibraryFile(file, null);
  2714. // Check printer compatibility if sliced_for_model is available in metadata
  2715. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2716. const printerModel = mapModelCode(printer.model);
  2717. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2718. await api.deleteLibraryFile(result.id).catch(() => {});
  2719. showToast(
  2720. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2721. 'error'
  2722. );
  2723. return;
  2724. }
  2725. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2726. } catch {
  2727. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2728. } finally {
  2729. setIsDropUploading(false);
  2730. }
  2731. };
  2732. const handleCardClick = (e: React.MouseEvent) => {
  2733. if (viewMode !== 'compact' || selectionMode) return;
  2734. const target = e.target as HTMLElement;
  2735. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2736. onOpenCompactCard?.(printer.id);
  2737. };
  2738. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2739. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2740. const renderAmsSlotActions = ({
  2741. amsId,
  2742. slotId,
  2743. loadTrayId,
  2744. isRefreshing,
  2745. includeRfid = true,
  2746. }: {
  2747. amsId: number;
  2748. slotId: number;
  2749. loadTrayId: number;
  2750. isRefreshing?: boolean;
  2751. includeRfid?: boolean;
  2752. }) => {
  2753. const printerBusy = status?.state === 'RUNNING';
  2754. return (
  2755. <>
  2756. {includeRfid && (
  2757. <button
  2758. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2759. hasPermission('printers:ams_rfid')
  2760. ? 'text-white hover:bg-bambu-dark-tertiary'
  2761. : 'text-bambu-gray/50 cursor-not-allowed'
  2762. }`}
  2763. onClick={(e) => {
  2764. e.stopPropagation();
  2765. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2766. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2767. }}
  2768. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2769. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2770. >
  2771. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2772. {t('printers.rfid.reread')}
  2773. </button>
  2774. )}
  2775. <button
  2776. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2777. hasPermission('printers:control')
  2778. ? 'text-white hover:bg-bambu-dark-tertiary'
  2779. : 'text-bambu-gray/50 cursor-not-allowed'
  2780. }`}
  2781. onClick={(e) => {
  2782. e.stopPropagation();
  2783. if (printerBusy || !hasPermission('printers:control')) return;
  2784. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2785. }}
  2786. disabled={printerBusy || !hasPermission('printers:control')}
  2787. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2788. >
  2789. <LogIn className="w-3 h-3" />
  2790. {t('printers.ams.load')}
  2791. </button>
  2792. <button
  2793. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2794. hasPermission('printers:control')
  2795. ? 'text-white hover:bg-bambu-dark-tertiary'
  2796. : 'text-bambu-gray/50 cursor-not-allowed'
  2797. }`}
  2798. onClick={(e) => {
  2799. e.stopPropagation();
  2800. if (printerBusy || !hasPermission('printers:control')) return;
  2801. unloadAmsMutation.mutate();
  2802. }}
  2803. disabled={printerBusy || !hasPermission('printers:control')}
  2804. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2805. >
  2806. <LogOut className="w-3 h-3" />
  2807. {t('printers.ams.unload')}
  2808. </button>
  2809. </>
  2810. );
  2811. };
  2812. const printerActionsMenu = (
  2813. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2814. <Button
  2815. variant="secondary"
  2816. size="sm"
  2817. onClick={() => setShowMenu(!showMenu)}
  2818. title={t('common.more', 'More')}
  2819. className={footerIconButtonClass}
  2820. >
  2821. <MoreVertical className="w-4 h-4" />
  2822. </Button>
  2823. {showMenu && (
  2824. <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">
  2825. <button
  2826. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2827. hasPermission('printers:update')
  2828. ? 'hover:bg-bambu-dark-tertiary'
  2829. : 'opacity-50 cursor-not-allowed'
  2830. }`}
  2831. onClick={() => {
  2832. if (!hasPermission('printers:update')) return;
  2833. setShowEditModal(true);
  2834. setShowMenu(false);
  2835. }}
  2836. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2837. >
  2838. <Pencil className="w-4 h-4" />
  2839. {t('common.edit')}
  2840. </button>
  2841. <button
  2842. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2843. onClick={() => {
  2844. setShowPrinterInfo(true);
  2845. setShowMenu(false);
  2846. }}
  2847. >
  2848. <Info className="w-4 h-4" />
  2849. {t('printers.printerInformation')}
  2850. </button>
  2851. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2852. <button
  2853. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2854. hasPermission('printers:update')
  2855. ? 'hover:bg-bambu-dark-tertiary'
  2856. : 'opacity-50 cursor-not-allowed'
  2857. }`}
  2858. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2859. onClick={() => {
  2860. if (!hasPermission('printers:update')) return;
  2861. setShowMenu(false);
  2862. if (printer.is_active !== false) {
  2863. handleEnterMaintenance();
  2864. } else {
  2865. maintenanceMutation.mutate(true);
  2866. }
  2867. }}
  2868. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2869. >
  2870. <Wrench className="w-4 h-4" />
  2871. {printer.is_active !== false
  2872. ? t('printers.maintenance.menuEnter')
  2873. : t('printers.maintenance.menuExit')}
  2874. </button>
  2875. <button
  2876. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2877. onClick={() => {
  2878. connectMutation.mutate();
  2879. setShowMenu(false);
  2880. }}
  2881. >
  2882. <RefreshCw className="w-4 h-4" />
  2883. {t('printers.reconnect')}
  2884. </button>
  2885. <button
  2886. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2887. disabled={forceRefreshMutation.isPending}
  2888. onClick={() => {
  2889. forceRefreshMutation.mutate();
  2890. setShowMenu(false);
  2891. }}
  2892. >
  2893. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2894. {t('printers.forceRefresh')}
  2895. </button>
  2896. <button
  2897. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2898. onClick={() => {
  2899. setShowMQTTDebug(true);
  2900. setShowMenu(false);
  2901. }}
  2902. >
  2903. <Terminal className="w-4 h-4" />
  2904. {t('printers.mqttDebug')}
  2905. </button>
  2906. <button
  2907. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2908. onClick={() => {
  2909. setShowDiagnostic(true);
  2910. setShowMenu(false);
  2911. }}
  2912. >
  2913. <Stethoscope className="w-4 h-4" />
  2914. {t('diagnostic.runButton')}
  2915. </button>
  2916. <button
  2917. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2918. hasPermission('printers:delete')
  2919. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  2920. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  2921. }`}
  2922. onClick={() => {
  2923. if (!hasPermission('printers:delete')) return;
  2924. setShowDeleteConfirm(true);
  2925. setShowMenu(false);
  2926. }}
  2927. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2928. >
  2929. <Trash2 className="w-4 h-4" />
  2930. {t('common.delete')}
  2931. </button>
  2932. </div>
  2933. )}
  2934. </div>
  2935. );
  2936. return (
  2937. <Card
  2938. id={`printer-card-${printer.id}`}
  2939. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  2940. onClick={handleCardClick}
  2941. onDragEnter={handleCardDragEnter}
  2942. onDragOver={handleCardDragOver}
  2943. onDragLeave={handleCardDragLeave}
  2944. onDrop={handleCardDrop}
  2945. >
  2946. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  2947. {selectionMode && (
  2948. <div
  2949. className="absolute inset-0 z-20 flex items-start p-2"
  2950. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  2951. >
  2952. {isSelected ? (
  2953. <CheckSquare className="w-5 h-5 text-bambu-green" />
  2954. ) : (
  2955. <Square className="w-5 h-5 text-bambu-gray" />
  2956. )}
  2957. </div>
  2958. )}
  2959. {/* Drop zone overlay */}
  2960. {(isDraggingFile || isDropUploading) && (
  2961. <div
  2962. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  2963. isDropUploading
  2964. ? 'bg-bambu-green/10 border-bambu-green/50'
  2965. : canDrop
  2966. ? 'bg-bambu-green/10 border-bambu-green'
  2967. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  2968. }`}
  2969. >
  2970. <div className="text-center">
  2971. {isDropUploading ? (
  2972. <>
  2973. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  2974. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  2975. </>
  2976. ) : canDrop ? (
  2977. <>
  2978. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  2979. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  2980. </>
  2981. ) : (
  2982. <>
  2983. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  2984. <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  2985. </>
  2986. )}
  2987. </div>
  2988. </div>
  2989. )}
  2990. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  2991. {/* Header */}
  2992. <div className={getSpacing()}>
  2993. {/* Top row: Image, Name, Menu */}
  2994. <div className="flex items-start justify-between gap-2">
  2995. <div className="flex items-center gap-3 min-w-0 flex-1">
  2996. {/* Printer Model Image */}
  2997. <img
  2998. src={getPrinterImage(printer.model)}
  2999. alt={printer.model || t('common.printer')}
  3000. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3001. />
  3002. <div className="min-w-0 flex-1">
  3003. <div className="flex items-center justify-between gap-2">
  3004. <div className="flex min-w-0 items-center gap-2">
  3005. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3006. {/* Connection indicator dot for compact mode */}
  3007. {viewMode === 'compact' && (() => {
  3008. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3009. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3010. const hasWarning = hmsErrors.length > 0;
  3011. const pipColor = !status?.connected
  3012. ? 'bg-status-error'
  3013. : hasSevere
  3014. ? 'bg-status-error'
  3015. : hasWarning
  3016. ? 'bg-status-warning'
  3017. : 'bg-status-ok';
  3018. const pipTitle = !status?.connected
  3019. ? t('printers.connection.offline')
  3020. : hasWarning
  3021. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3022. : t('printers.connection.connected');
  3023. return (
  3024. <div
  3025. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  3026. title={pipTitle}
  3027. />
  3028. );
  3029. })()}
  3030. </div>
  3031. {viewMode === 'compact' && showClearPlateButton && (
  3032. <button
  3033. type="button"
  3034. onClick={() => clearPlateMutation.mutate()}
  3035. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3036. aria-label={t('printers.plateStatus.markCleared')}
  3037. 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"
  3038. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3039. >
  3040. {clearPlateMutation.isPending ? (
  3041. <Loader2 className="w-3 h-3 animate-spin" />
  3042. ) : (
  3043. <PlateClearedIcon className="w-3 h-3" />
  3044. )}
  3045. </button>
  3046. )}
  3047. </div>
  3048. <p className="text-sm text-bambu-gray">
  3049. {printer.model || 'Unknown Model'}
  3050. {/* Nozzle Info - only in expanded */}
  3051. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3052. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3053. • {status.nozzles[0].nozzle_diameter}mm
  3054. </span>
  3055. )}
  3056. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3057. <span className="ml-2 text-bambu-gray">
  3058. <Clock className="w-3 h-3 inline-block mr-1" />
  3059. {Math.round(maintenanceInfo.total_print_hours)}h
  3060. </span>
  3061. )}
  3062. </p>
  3063. </div>
  3064. </div>
  3065. </div>
  3066. {/* Badges row - only in expanded mode */}
  3067. {viewMode === 'expanded' && (
  3068. <div className="mt-2">
  3069. <div className="flex flex-wrap items-center gap-2">
  3070. {/* Connection status badge (or Maintenance pill when out of service).
  3071. Defensive: only swap when is_active is EXPLICITLY false. An
  3072. undefined / missing field defaults to "active" so the regular
  3073. pill renders — matches the backend default and prevents test
  3074. fixtures (or stale clients) from accidentally tripping the
  3075. maintenance UI. */}
  3076. {printer.is_active === false ? (
  3077. <span
  3078. 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"
  3079. title={t('printers.maintenance.subtitle')}
  3080. >
  3081. <Wrench className="w-3 h-3" />
  3082. {t('printers.maintenance.pillLabel')}
  3083. </span>
  3084. ) : (
  3085. <span
  3086. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3087. status?.connected
  3088. ? 'bg-status-ok/20 text-status-ok'
  3089. : 'bg-status-error/20 text-status-error'
  3090. }`}
  3091. >
  3092. {status?.connected ? (
  3093. <Link className="w-3 h-3" />
  3094. ) : (
  3095. <Unlink className="w-3 h-3" />
  3096. )}
  3097. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3098. </span>
  3099. )}
  3100. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3101. {printer.is_active !== false && !status?.connected && (
  3102. <button
  3103. onClick={() => setShowDiagnostic(true)}
  3104. 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"
  3105. title={t('diagnostic.runButton')}
  3106. >
  3107. <Stethoscope className="w-3 h-3" />
  3108. {t('diagnostic.runButton')}
  3109. </button>
  3110. )}
  3111. {/* Network connection indicator */}
  3112. {status?.connected && status?.wired_network && (
  3113. <span
  3114. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3115. title={t('printers.connection.ethernet', 'Ethernet')}
  3116. >
  3117. <Cable className="w-3 h-3" />
  3118. {t('printers.connection.ethernet', 'Ethernet')}
  3119. </span>
  3120. )}
  3121. {/* WiFi signal indicator */}
  3122. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3123. <span
  3124. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3125. wifiSignal >= -50
  3126. ? 'bg-status-ok/20 text-status-ok'
  3127. : wifiSignal >= -60
  3128. ? 'bg-status-ok/20 text-status-ok'
  3129. : wifiSignal >= -70
  3130. ? 'bg-status-warning/20 text-status-warning'
  3131. : wifiSignal >= -80
  3132. ? 'bg-orange-500/20 text-orange-600'
  3133. : 'bg-status-error/20 text-status-error'
  3134. }`}
  3135. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3136. >
  3137. <Signal className="w-3 h-3" />
  3138. {wifiSignal}dBm
  3139. </span>
  3140. )}
  3141. {/* HMS Status Indicator */}
  3142. {status?.connected && (() => {
  3143. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3144. return (
  3145. <button
  3146. onClick={() => setShowHMSModal(true)}
  3147. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3148. knownErrors.length > 0
  3149. ? knownErrors.some(e => e.severity <= 2)
  3150. ? 'bg-status-error/20 text-status-error'
  3151. : 'bg-status-warning/20 text-status-warning'
  3152. : 'bg-status-ok/20 text-status-ok'
  3153. }`}
  3154. title={t('printers.clickToViewHmsErrors')}
  3155. >
  3156. <AlertTriangle className="w-3 h-3" />
  3157. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3158. </button>
  3159. );
  3160. })()}
  3161. {/* Maintenance Status Indicator */}
  3162. {maintenanceInfo && (
  3163. <button
  3164. onClick={() => navigate('/maintenance')}
  3165. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3166. maintenanceInfo.due_count > 0
  3167. ? 'bg-status-error/20 text-status-error'
  3168. : maintenanceInfo.warning_count > 0
  3169. ? 'bg-status-warning/20 text-status-warning'
  3170. : 'bg-status-ok/20 text-status-ok'
  3171. }`}
  3172. title={
  3173. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3174. ? `${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`
  3175. : t('printers.maintenanceUpToDate')
  3176. }
  3177. >
  3178. <Wrench className="w-3 h-3" />
  3179. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3180. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3181. : 'OK'}
  3182. </button>
  3183. )}
  3184. {/* Queue Count Badge */}
  3185. {queueCount > 0 && (
  3186. <button
  3187. onClick={() => navigate('/queue')}
  3188. 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"
  3189. title={t('printers.queue.inQueue', { count: queueCount })}
  3190. >
  3191. <Layers className="w-3 h-3" />
  3192. {queueCount}
  3193. </button>
  3194. )}
  3195. {/* Firmware Version Badge */}
  3196. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3197. <button
  3198. onClick={() => setShowFirmwareModal(true)}
  3199. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3200. firmwareInfo.update_available
  3201. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3202. : 'bg-status-ok/20 text-status-ok'
  3203. }`}
  3204. title={
  3205. firmwareInfo.update_available
  3206. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3207. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3208. }
  3209. >
  3210. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3211. {firmwareInfo.current_version}
  3212. </button>
  3213. ) : status?.firmware_version ? (
  3214. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3215. {status.firmware_version}
  3216. </span>
  3217. ) : null}
  3218. {/* Enclosure Door Badge — models with an actual door sensor.
  3219. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3220. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3221. <span
  3222. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3223. status.door_open
  3224. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3225. : 'bg-status-ok/20 text-status-ok'
  3226. }`}
  3227. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3228. >
  3229. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3230. </span>
  3231. )}
  3232. </div>
  3233. </div>
  3234. )}
  3235. </div>
  3236. {/* Delete Confirmation */}
  3237. {showDeleteConfirm && (
  3238. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3239. <Card className="w-full max-w-md mx-4">
  3240. <CardContent>
  3241. <div className="flex items-start gap-3 mb-4">
  3242. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3243. <AlertTriangle className="w-5 h-5 text-red-600 dark:text-red-400" />
  3244. </div>
  3245. <div>
  3246. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3247. <p className="text-sm text-bambu-gray mt-1">
  3248. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3249. </p>
  3250. </div>
  3251. </div>
  3252. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3253. <label className="flex items-start gap-3 cursor-pointer">
  3254. <input
  3255. type="checkbox"
  3256. checked={deleteArchives}
  3257. onChange={(e) => setDeleteArchives(e.target.checked)}
  3258. 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"
  3259. />
  3260. <div>
  3261. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3262. <p className="text-xs text-bambu-gray mt-0.5">
  3263. {deleteArchives
  3264. ? t('printers.confirm.deleteArchivesNote')
  3265. : t('printers.confirm.keepArchivesNote')}
  3266. </p>
  3267. </div>
  3268. </label>
  3269. </div>
  3270. <div className="flex justify-end gap-2">
  3271. <Button
  3272. variant="secondary"
  3273. onClick={() => {
  3274. setShowDeleteConfirm(false);
  3275. setDeleteArchives(true);
  3276. }}
  3277. >
  3278. {t('common.cancel')}
  3279. </Button>
  3280. <Button
  3281. variant="danger"
  3282. onClick={() => {
  3283. deleteMutation.mutate({ deleteArchives });
  3284. setShowDeleteConfirm(false);
  3285. setDeleteArchives(true);
  3286. }}
  3287. >
  3288. Delete
  3289. </Button>
  3290. </div>
  3291. </CardContent>
  3292. </Card>
  3293. </div>
  3294. )}
  3295. {/* Status — see the equivalent defensive `=== false` check on the
  3296. header pill above for why this is not `!printer.is_active`. */}
  3297. {printer.is_active === false ? (
  3298. // Maintenance mode (#1476) — replaces the cover/progress container
  3299. // so the card keeps the same height. Renders for both compact and
  3300. // expanded view modes so the printer stays visible but plainly
  3301. // out-of-service.
  3302. <>
  3303. {viewMode === 'compact' ? (
  3304. <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">
  3305. <Wrench className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  3306. <span className="text-[11px] text-amber-700 dark:text-amber-400 font-medium truncate">
  3307. {t('printers.maintenance.pillLabel')}
  3308. </span>
  3309. </div>
  3310. ) : (
  3311. <>
  3312. <div className="flex items-center gap-2 mb-2">
  3313. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3314. {t('printers.status.title', 'Status')}
  3315. </span>
  3316. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3317. </div>
  3318. <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">
  3319. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3320. <div className="flex-1 min-w-0">
  3321. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3322. {t('printers.maintenance.title')}
  3323. </p>
  3324. <p className="text-xs text-bambu-gray mt-0.5">
  3325. {t('printers.maintenance.subtitle')}
  3326. </p>
  3327. </div>
  3328. <Button
  3329. variant="secondary"
  3330. size="sm"
  3331. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3332. onClick={() => maintenanceMutation.mutate(true)}
  3333. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3334. >
  3335. {t('printers.maintenance.exitButton')}
  3336. </Button>
  3337. </div>
  3338. </>
  3339. )}
  3340. </>
  3341. ) : status?.connected && (
  3342. <>
  3343. {/* Compact: Simple status bar */}
  3344. {viewMode === 'compact' ? (
  3345. (() => {
  3346. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3347. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3348. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3349. ? Math.max(0, Math.min(100, status.progress || 0))
  3350. : showClearPlateButton
  3351. ? 100
  3352. : hasProblem
  3353. ? 100
  3354. : 0;
  3355. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3356. const compactProgressClass = hasProblem
  3357. ? 'bg-status-error'
  3358. : status.state === 'PAUSE'
  3359. ? 'bg-status-warning'
  3360. : 'bg-bambu-green';
  3361. return (
  3362. <div className="relative mt-2 flex items-center gap-2">
  3363. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3364. <div
  3365. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3366. style={{ width: `${compactProgress}%` }}
  3367. />
  3368. </div>
  3369. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3370. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3371. </span>
  3372. </div>
  3373. );
  3374. })()
  3375. ) : (
  3376. /* Expanded: Full status section */
  3377. <>
  3378. <div className="flex items-center gap-2 mb-2">
  3379. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3380. {t('printers.status.title', 'Status')}
  3381. </span>
  3382. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3383. </div>
  3384. {/* Current Print or Idle Placeholder */}
  3385. {(() => {
  3386. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3387. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3388. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3389. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3390. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3391. return (
  3392. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3393. <button
  3394. onClick={() => setShowSkipObjectsModal(true)}
  3395. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3396. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3397. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3398. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3399. : 'text-bambu-gray/30 cursor-not-allowed'
  3400. }`}
  3401. title={
  3402. !hasPermission('printers:control')
  3403. ? t('printers.permission.noControl')
  3404. : !isActivePrint
  3405. ? t('printers.skipObjects.onlyWhilePrinting')
  3406. : (status.printable_objects_count ?? 0) >= 2
  3407. ? t('printers.skipObjects.tooltip')
  3408. : t('printers.skipObjects.requiresMultiple')
  3409. }
  3410. >
  3411. <SkipObjectsIcon className="w-4 h-4" />
  3412. {objectsData && objectsData.skipped_count > 0 && (
  3413. <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">
  3414. {objectsData.skipped_count}
  3415. </span>
  3416. )}
  3417. </button>
  3418. <div className="flex items-stretch gap-2">
  3419. <CoverImage
  3420. url={coverUrl}
  3421. printName={printName || undefined}
  3422. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3423. />
  3424. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3425. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3426. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3427. {plateStatusPill}
  3428. </div>
  3429. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3430. {printName || t('printers.noActiveJob', 'No active job')}
  3431. </p>
  3432. <div className="flex h-3 items-center gap-2 text-sm">
  3433. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3434. <div
  3435. 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`}
  3436. style={{ width: `${progress}%` }}
  3437. />
  3438. </div>
  3439. <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>
  3440. </div>
  3441. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3442. {isActivePrint ? (
  3443. <>
  3444. {status.remaining_time != null && status.remaining_time > 0 && (
  3445. <>
  3446. <span className="flex items-center gap-1">
  3447. <Clock className="w-3 h-3" />
  3448. {formatDuration(status.remaining_time * 60)}
  3449. </span>
  3450. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3451. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3452. </span>
  3453. </>
  3454. )}
  3455. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3456. <span className="flex items-center gap-1">
  3457. <Layers className="w-3 h-3" />
  3458. {status.layer_num}/{status.total_layers}
  3459. </span>
  3460. )}
  3461. {currentPrintUser && (
  3462. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3463. <User className="w-3 h-3" />
  3464. {currentPrintUser}
  3465. </span>
  3466. )}
  3467. </>
  3468. ) : lastPrint ? (
  3469. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3470. Last: {lastPrint.print_name || lastPrint.filename}
  3471. {lastPrint.completed_at && (
  3472. <span className="ml-1 text-bambu-gray/60">
  3473. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3474. </span>
  3475. )}
  3476. </p>
  3477. ) : (
  3478. <span>{t('printers.readyToPrint')}</span>
  3479. )}
  3480. </div>
  3481. </div>
  3482. </div>
  3483. <PrinterQueueWidget
  3484. printerId={printer.id}
  3485. printerModel={printer.model}
  3486. loadedFilamentTypes={loadedFilamentTypes}
  3487. loadedFilaments={loadedFilaments}
  3488. variant="panelExtension"
  3489. />
  3490. </div>
  3491. );
  3492. })()}
  3493. </>
  3494. )}
  3495. {/* Temperatures */}
  3496. {status.temperatures && viewMode === 'expanded' && (() => {
  3497. // Use actual heater states from MQTT stream
  3498. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3499. const bedHeating = status.temperatures.bed_heating || false;
  3500. const chamberHeating = status.temperatures.chamber_heating || false;
  3501. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3502. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3503. const kinds: HeaterSensorKind[] = ['nozzle'];
  3504. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3505. kinds.push('bed');
  3506. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3507. return kinds;
  3508. })();
  3509. // active_extruder: 0=right, 1=left
  3510. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3511. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3512. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3513. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3514. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3515. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3516. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3517. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3518. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3519. 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 ${
  3520. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3521. }`;
  3522. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3523. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3524. // the widget there is at best dead UI and at worst suggests a
  3525. // control that does nothing. Mirrors the enclosure-door badge
  3526. // gate above.
  3527. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3528. const fanItems = [
  3529. {
  3530. key: 'part',
  3531. label: t('printers.fans.partCooling'),
  3532. value: status.cooling_fan_speed ?? 0,
  3533. Icon: Fan,
  3534. activeClass: 'text-cyan-600 dark:text-cyan-400',
  3535. },
  3536. {
  3537. key: 'aux',
  3538. label: t('printers.fans.auxiliary'),
  3539. value: status.big_fan1_speed ?? 0,
  3540. Icon: Wind,
  3541. activeClass: 'text-blue-600 dark:text-blue-400',
  3542. },
  3543. ...(hasChamberFan
  3544. ? [
  3545. {
  3546. key: 'chamber',
  3547. label: t('printers.fans.chamber'),
  3548. value: status.big_fan2_speed ?? 0,
  3549. Icon: AirVent,
  3550. activeClass: 'text-green-600 dark:text-green-400',
  3551. },
  3552. ]
  3553. : []),
  3554. ];
  3555. return (
  3556. <>
  3557. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3558. {/* Nozzle temp - combined for dual nozzle */}
  3559. <div
  3560. className={statusControlClass}
  3561. title={statusControlTitle}
  3562. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3563. >
  3564. <button
  3565. type="button"
  3566. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3567. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3568. onClick={(e) => {
  3569. e.stopPropagation();
  3570. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3571. }}
  3572. >
  3573. <LineChartIcon className="w-2.5 h-2.5" />
  3574. </button>
  3575. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3576. {status.temperatures.nozzle_2 !== undefined ? (
  3577. <>
  3578. <p className="text-[9px] text-bambu-gray">L / R</p>
  3579. <p className="text-[11px] text-white">
  3580. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3581. </p>
  3582. </>
  3583. ) : singleNozzleSlot ? (
  3584. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3585. <div className="cursor-default">
  3586. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3587. <p className="text-[11px] text-white">
  3588. {Math.round(status.temperatures.nozzle || 0)}°C
  3589. </p>
  3590. </div>
  3591. </NozzleSlotHoverCard>
  3592. ) : (
  3593. <>
  3594. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3595. <p className="text-[11px] text-white">
  3596. {Math.round(status.temperatures.nozzle || 0)}°C
  3597. </p>
  3598. </>
  3599. )}
  3600. {statusControlMenu === 'nozzle-temp' && (
  3601. isDualNozzle ? (
  3602. <IndicatorControlPopover
  3603. title="Set Nozzle Temperatures"
  3604. widthClass="w-[300px]"
  3605. popoverWidth={300}
  3606. popoverHeight={260}
  3607. isPending={nozzleTemperatureMutation.isPending}
  3608. onClose={() => setStatusControlMenu(null)}
  3609. >
  3610. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3611. <NozzleTemperatureControlBox
  3612. label="Left Temp"
  3613. current={status.temperatures.nozzle}
  3614. target={status.temperatures.nozzle_target}
  3615. isActive={activeNozzle === 'L'}
  3616. isPending={nozzleTemperatureMutation.isPending}
  3617. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3618. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3619. />
  3620. <NozzleTemperatureControlBox
  3621. label="Right Temp"
  3622. current={status.temperatures.nozzle_2}
  3623. target={status.temperatures.nozzle_2_target}
  3624. isActive={activeNozzle === 'R'}
  3625. isPending={nozzleTemperatureMutation.isPending}
  3626. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3627. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3628. />
  3629. </div>
  3630. </IndicatorControlPopover>
  3631. ) : (
  3632. <IndicatorControlPopover
  3633. title="Set Nozzle Temperature"
  3634. unit="°C"
  3635. customMin={0}
  3636. customMax={320}
  3637. isPending={nozzleTemperatureMutation.isPending}
  3638. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3639. onClose={() => setStatusControlMenu(null)}
  3640. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3641. />
  3642. )
  3643. )}
  3644. </div>
  3645. <div
  3646. className={statusControlClass}
  3647. title={statusControlTitle}
  3648. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3649. >
  3650. <button
  3651. type="button"
  3652. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3653. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3654. onClick={(e) => {
  3655. e.stopPropagation();
  3656. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3657. }}
  3658. >
  3659. <LineChartIcon className="w-2.5 h-2.5" />
  3660. </button>
  3661. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3662. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3663. <p className="text-[11px] text-white">
  3664. {Math.round(status.temperatures.bed || 0)}°C
  3665. </p>
  3666. {statusControlMenu === 'bed-temp' && (
  3667. <IndicatorControlPopover
  3668. title="Set Bed Temperature"
  3669. unit="°C"
  3670. customMin={0}
  3671. customMax={140}
  3672. isPending={bedTemperatureMutation.isPending}
  3673. options={buildPresetOptions(bedTempPresets, 'C')}
  3674. onClose={() => setStatusControlMenu(null)}
  3675. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3676. />
  3677. )}
  3678. </div>
  3679. {status.temperatures.chamber !== undefined && (() => {
  3680. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3681. // but can't act on M141, so we keep the card read-only there.
  3682. const hasChamberHeater = status.supports_chamber_heater === true;
  3683. return (
  3684. <div
  3685. className={hasChamberHeater
  3686. ? statusControlClass
  3687. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3688. title={hasChamberHeater ? statusControlTitle : undefined}
  3689. onClick={hasChamberHeater
  3690. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3691. : undefined}
  3692. >
  3693. <button
  3694. type="button"
  3695. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3696. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3697. onClick={(e) => {
  3698. e.stopPropagation();
  3699. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3700. }}
  3701. >
  3702. <LineChartIcon className="w-2.5 h-2.5" />
  3703. </button>
  3704. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3705. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3706. <p className="text-[11px] text-white">
  3707. {Math.round(status.temperatures.chamber || 0)}°C
  3708. </p>
  3709. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3710. <IndicatorControlPopover
  3711. title="Set Chamber Temperature"
  3712. unit="°C"
  3713. customMin={0}
  3714. customMax={60}
  3715. isPending={chamberTemperatureMutation.isPending}
  3716. options={buildPresetOptions(chamberTempPresets, 'C')}
  3717. onClose={() => setStatusControlMenu(null)}
  3718. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3719. />
  3720. )}
  3721. </div>
  3722. );
  3723. })()}
  3724. {/* Active nozzle indicator for dual-nozzle printers */}
  3725. {isDualNozzle && (
  3726. <DualNozzleHoverCard
  3727. leftSlot={leftNozzleSlot}
  3728. rightSlot={rightNozzleSlot}
  3729. activeNozzle={activeNozzle}
  3730. filamentInfo={filamentInfo}
  3731. >
  3732. <div
  3733. 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 ${
  3734. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3735. }`}
  3736. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3737. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3738. >
  3739. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-600 dark:text-amber-400" />
  3740. <div className="flex items-center gap-2">
  3741. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3742. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3743. </span>
  3744. <span className="text-[9px] text-bambu-gray/40">·</span>
  3745. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3746. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3747. </span>
  3748. </div>
  3749. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3750. {statusControlMenu === 'nozzle-select' && (
  3751. <IndicatorControlPopover
  3752. title="Set Nozzle Selection"
  3753. widthClass="w-[300px]"
  3754. popoverWidth={300}
  3755. popoverHeight={140}
  3756. isPending={selectExtruderMutation.isPending}
  3757. options={[
  3758. { label: 'Left', value: 1 },
  3759. { label: 'Right', value: 0 },
  3760. ]}
  3761. onClose={() => setStatusControlMenu(null)}
  3762. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3763. />
  3764. )}
  3765. </div>
  3766. </DualNozzleHoverCard>
  3767. )}
  3768. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3769. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3770. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3771. )}
  3772. </div>
  3773. <div className="mt-2 flex items-center gap-1.5">
  3774. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3775. const active = value > 0;
  3776. return (
  3777. <div
  3778. key={key}
  3779. 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 ${
  3780. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3781. }`}
  3782. title={canUseStatusControls ? label : statusControlTitle}
  3783. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3784. >
  3785. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3786. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3787. {value}%
  3788. </span>
  3789. {statusControlMenu === `fan-${key}` && (
  3790. <IndicatorControlPopover
  3791. title={`Set ${label} Speed`}
  3792. unit="%"
  3793. customMin={0}
  3794. customMax={100}
  3795. isPending={fanSpeedMutation.isPending}
  3796. options={buildPresetOptions(fanSpeedPresets, '%')}
  3797. onClose={() => setStatusControlMenu(null)}
  3798. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'chamber', speed })}
  3799. />
  3800. )}
  3801. </div>
  3802. );
  3803. })}
  3804. </div>
  3805. </>
  3806. );
  3807. })()}
  3808. {viewMode === 'expanded' && showClearPlateButton && (
  3809. <button
  3810. type="button"
  3811. onClick={() => clearPlateMutation.mutate()}
  3812. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3813. 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"
  3814. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3815. >
  3816. {clearPlateMutation.isPending ? (
  3817. <Loader2 className="w-3 h-3 animate-spin" />
  3818. ) : (
  3819. <PlateClearedIcon className="w-4 h-4" />
  3820. )}
  3821. {t('printers.plateStatus.markCleared')}
  3822. </button>
  3823. )}
  3824. {/* Controls */}
  3825. {viewMode === 'expanded' && (() => {
  3826. // Determine print state for control buttons
  3827. const isRunning = status.state === 'RUNNING';
  3828. const isPaused = status.state === 'PAUSE';
  3829. const isPrinting = isRunning || isPaused;
  3830. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  3831. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  3832. 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';
  3833. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  3834. return (
  3835. <div className="mt-3">
  3836. {/* Section Header */}
  3837. <div className="flex items-center gap-2 mb-2">
  3838. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3839. {t('printers.controls')}
  3840. </span>
  3841. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3842. </div>
  3843. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  3844. {/* Left: Secondary controls */}
  3845. <div className="flex flex-wrap items-center gap-2 min-w-0">
  3846. <button
  3847. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  3848. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  3849. className={`${iconControlClass} ${
  3850. status.chamber_light
  3851. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  3852. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  3853. }`}
  3854. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  3855. >
  3856. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  3857. </button>
  3858. {/* Airduct Mode (P2S / X2D / H2*) */}
  3859. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  3860. const isHeating = status.airduct_mode === 1;
  3861. const Icon = isHeating ? Flame : Snowflake;
  3862. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  3863. 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';
  3864. return (
  3865. <div className="relative">
  3866. <button
  3867. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  3868. disabled={!hasPermission('printers:control')}
  3869. className={`${iconControlClass} ${bg}`}
  3870. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  3871. >
  3872. <Icon className={`w-4 h-4 ${color}`} />
  3873. </button>
  3874. {showAirductMenu === printer.id && (
  3875. <>
  3876. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  3877. <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]">
  3878. {([
  3879. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  3880. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  3881. ] as const).map(({ mode, label, modeId }) => (
  3882. <button
  3883. key={mode}
  3884. onClick={() => {
  3885. airductMutation.mutate(mode);
  3886. setShowAirductMenu(null);
  3887. }}
  3888. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  3889. status.airduct_mode === modeId
  3890. ? 'text-bambu-green bg-bambu-green/10'
  3891. : 'text-white hover:bg-bambu-dark-tertiary'
  3892. }`}
  3893. >
  3894. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  3895. {label}
  3896. </button>
  3897. ))}
  3898. </div>
  3899. </>
  3900. )}
  3901. </div>
  3902. );
  3903. })()}
  3904. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  3905. {(() => {
  3906. const canControl = hasPermission('printers:control');
  3907. const disabled = isPrinting || !canControl;
  3908. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  3909. 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';
  3910. const requestZJog = (direction: 1 | -1) => {
  3911. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  3912. // The jog never disables the soft endstops (#2579), so it's always
  3913. // safe: the firmware clamps the move at the travel limit, or refuses
  3914. // it if the printer isn't homed. No not-homed bypass to gate.
  3915. bedJogMutation.mutate({ distance: signed });
  3916. };
  3917. const requestXyJog = (x: number, y: number) => {
  3918. xyJogMutation.mutate({ x, y });
  3919. };
  3920. const requestExtruderJog = (distance: number) => {
  3921. extruderJogMutation.mutate(distance);
  3922. };
  3923. return (
  3924. <div className="relative">
  3925. <button
  3926. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  3927. disabled={disabled}
  3928. className={`${iconControlClass} ${
  3929. disabled
  3930. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  3931. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  3932. }`}
  3933. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  3934. >
  3935. <Move className="w-4 h-4" />
  3936. </button>
  3937. {showBedJogMenu === printer.id && (
  3938. <>
  3939. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  3940. <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">
  3941. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  3942. {t('printers.bedJog.title')}
  3943. </div>
  3944. <div className="h-px bg-bambu-dark-tertiary" />
  3945. {/* #2579: Bambu firmware does not enforce soft endstops on
  3946. G-code sent over MQTT, so manual moves can drive past the
  3947. travel limits and cause a collision. Not fixable from our
  3948. side — warn prominently. */}
  3949. <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">
  3950. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  3951. <span>{t('printers.bedJog.limitWarning')}</span>
  3952. </div>
  3953. <div className="h-px bg-bambu-dark-tertiary" />
  3954. <div className="flex justify-center px-3 py-2.5">
  3955. <div className="flex items-center justify-center gap-3">
  3956. <div className="grid grid-cols-3 gap-1">
  3957. <div />
  3958. <button
  3959. onClick={() => requestXyJog(0, bedJogStep)}
  3960. disabled={xyJogMutation.isPending}
  3961. className={jogButtonClass}
  3962. aria-label="Move Y forward"
  3963. >
  3964. <ArrowUp className="w-4 h-4" />
  3965. </button>
  3966. <div />
  3967. <button
  3968. onClick={() => requestXyJog(-bedJogStep, 0)}
  3969. disabled={xyJogMutation.isPending}
  3970. className={jogButtonClass}
  3971. aria-label="Move X left"
  3972. >
  3973. <ArrowLeft className="w-4 h-4" />
  3974. </button>
  3975. <button
  3976. onClick={() => {
  3977. setShowBedJogMenu(null);
  3978. homeAxesMutation.mutate('all');
  3979. }}
  3980. disabled={homeAxesMutation.isPending}
  3981. className={jogButtonClass}
  3982. aria-label={t('printers.bedJog.homeZ')}
  3983. >
  3984. <Home className="w-4 h-4" />
  3985. </button>
  3986. <button
  3987. onClick={() => requestXyJog(bedJogStep, 0)}
  3988. disabled={xyJogMutation.isPending}
  3989. className={jogButtonClass}
  3990. aria-label="Move X right"
  3991. >
  3992. <ArrowRight className="w-4 h-4" />
  3993. </button>
  3994. <div />
  3995. <button
  3996. onClick={() => requestXyJog(0, -bedJogStep)}
  3997. disabled={xyJogMutation.isPending}
  3998. className={jogButtonClass}
  3999. aria-label="Move Y back"
  4000. >
  4001. <ArrowDown className="w-4 h-4" />
  4002. </button>
  4003. <div />
  4004. </div>
  4005. <div className="flex flex-col items-center gap-1">
  4006. <button
  4007. onClick={() => requestZJog(-1)}
  4008. disabled={bedJogMutation.isPending}
  4009. className={jogButtonClass}
  4010. aria-label={t('printers.bedJog.up')}
  4011. >
  4012. <ArrowUp className="w-4 h-4" />
  4013. </button>
  4014. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4015. <Layers className="w-4 h-4" />
  4016. </div>
  4017. <button
  4018. onClick={() => requestZJog(1)}
  4019. disabled={bedJogMutation.isPending}
  4020. className={jogButtonClass}
  4021. aria-label={t('printers.bedJog.down')}
  4022. >
  4023. <ArrowDown className="w-4 h-4" />
  4024. </button>
  4025. </div>
  4026. <div className="flex flex-col items-center gap-1">
  4027. <button
  4028. onClick={() => requestExtruderJog(-bedJogStep)}
  4029. disabled={extruderJogMutation.isPending}
  4030. className={jogButtonClass}
  4031. aria-label="Retract filament"
  4032. >
  4033. <ArrowUp className="w-4 h-4" />
  4034. </button>
  4035. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4036. <span className="text-sm font-semibold leading-none">E</span>
  4037. </div>
  4038. <button
  4039. onClick={() => requestExtruderJog(bedJogStep)}
  4040. disabled={extruderJogMutation.isPending}
  4041. className={jogButtonClass}
  4042. aria-label="Extrude filament"
  4043. >
  4044. <ArrowDown className="w-4 h-4" />
  4045. </button>
  4046. </div>
  4047. </div>
  4048. </div>
  4049. <div className="h-px bg-bambu-dark-tertiary" />
  4050. <div className="px-3 pt-2.5 pb-3">
  4051. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4052. {t('printers.bedJog.step')}
  4053. </div>
  4054. <div className="flex gap-1">
  4055. {[1, 10, 50].map((step) => (
  4056. <button
  4057. key={step}
  4058. onClick={() => setBedJogStep(step)}
  4059. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4060. bedJogStep === step
  4061. ? 'bg-bambu-green/20 text-bambu-green'
  4062. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4063. }`}
  4064. >
  4065. {step}
  4066. </button>
  4067. ))}
  4068. </div>
  4069. </div>
  4070. </div>
  4071. </>
  4072. )}
  4073. </div>
  4074. );
  4075. })()}
  4076. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4077. <button
  4078. onClick={handleTogglePlateDetection}
  4079. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4080. className={`${iconControlClass} rounded-r-none ${
  4081. printer.plate_detection_enabled
  4082. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4083. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4084. }`}
  4085. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4086. >
  4087. {plateDetectionMutation.isPending ? (
  4088. <Loader2 className="w-4 h-4 animate-spin" />
  4089. ) : (
  4090. <ScanSearch className="w-4 h-4" />
  4091. )}
  4092. </button>
  4093. <button
  4094. onClick={handleOpenPlateManagement}
  4095. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4096. 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 ${
  4097. printer.plate_detection_enabled
  4098. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4099. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4100. }`}
  4101. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4102. >
  4103. {isCheckingPlate ? (
  4104. <Loader2 className="w-4 h-4 animate-spin" />
  4105. ) : (
  4106. <ChevronDown className="w-4 h-4" />
  4107. )}
  4108. </button>
  4109. </div>
  4110. {/* Print Speed */}
  4111. {(() => (
  4112. <div className="relative">
  4113. <button
  4114. data-testid="speed-control"
  4115. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4116. disabled={!isPrinting || !hasPermission('printers:control')}
  4117. className={`${iconControlClass} ${
  4118. isPrinting
  4119. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4120. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4121. }`}
  4122. title={isPrinting ? t('printers.speed.title') : undefined}
  4123. >
  4124. <Gauge className="w-4 h-4" />
  4125. </button>
  4126. {showSpeedMenu === printer.id && (
  4127. <>
  4128. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4129. <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]">
  4130. {([
  4131. { mode: 1, label: t('printers.speed.silent') },
  4132. { mode: 2, label: t('printers.speed.standard') },
  4133. { mode: 3, label: t('printers.speed.sport') },
  4134. { mode: 4, label: t('printers.speed.ludicrous') },
  4135. ] as const).map(({ mode, label }) => (
  4136. <button
  4137. key={mode}
  4138. onClick={() => {
  4139. printSpeedMutation.mutate(mode);
  4140. setShowSpeedMenu(null);
  4141. }}
  4142. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4143. status.speed_level === mode
  4144. ? 'text-bambu-green bg-bambu-green/10'
  4145. : 'text-white hover:bg-bambu-dark-tertiary'
  4146. }`}
  4147. >
  4148. {label}
  4149. </button>
  4150. ))}
  4151. </div>
  4152. </>
  4153. )}
  4154. </div>
  4155. ))()}
  4156. </div>
  4157. {/* Right: Print Control Buttons */}
  4158. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4159. {/* Pause/Resume button */}
  4160. {(() => {
  4161. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4162. return (
  4163. <button
  4164. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4165. disabled={pauseUnavailable}
  4166. className={`
  4167. ${printControlClass}
  4168. ${pauseUnavailable
  4169. ? unavailablePrintActionClass
  4170. : isPaused
  4171. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4172. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4173. }
  4174. `}
  4175. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4176. >
  4177. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4178. {isPaused ? t('printers.resume') : t('printers.pause')}
  4179. </button>
  4180. );
  4181. })()}
  4182. {/* Stop button */}
  4183. {(() => {
  4184. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4185. return (
  4186. <button
  4187. onClick={() => setShowStopConfirm(true)}
  4188. disabled={stopUnavailable}
  4189. className={`
  4190. ${printControlClass}
  4191. ${stopUnavailable
  4192. ? unavailablePrintActionClass
  4193. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4194. }
  4195. `}
  4196. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4197. >
  4198. <Square className="w-3 h-3" />
  4199. {t('printers.stop')}
  4200. </button>
  4201. );
  4202. })()}
  4203. </div>
  4204. </div>
  4205. </div>
  4206. );
  4207. })()}
  4208. {/* AMS Units - 2-Column Grid Layout */}
  4209. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4210. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4211. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4212. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4213. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4214. const filamentSlotClass = 'min-w-14';
  4215. // #1762 (comment 2): while a print is running/paused, overlay a small
  4216. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4217. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4218. // staged to a printer with mismatched filament: the wrong-slot pill
  4219. // is visible the instant printing starts.
  4220. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4221. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4222. ? status.ams_mapping
  4223. : [];
  4224. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4225. const boundedSlotCount = Math.max(1, slotCount);
  4226. const gapCount = Math.max(0, boundedSlotCount - 1);
  4227. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4228. return {
  4229. flex: `1 1 ${minWidth}`,
  4230. minWidth,
  4231. };
  4232. };
  4233. return (
  4234. <div className="mt-3">
  4235. {/* Section Header */}
  4236. <div className="flex items-center gap-2 mb-2">
  4237. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4238. {t('printers.filaments')}
  4239. </span>
  4240. <AmsBackupBadge
  4241. state={status.ams_filament_backup}
  4242. onClick={() => setAmsBackupModalOpen(true)}
  4243. />
  4244. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4245. </div>
  4246. {/* AMS Content */}
  4247. <div className="flex flex-wrap gap-2">
  4248. {/* Regular AMS units */}
  4249. {regularAms.map((ams) => {
  4250. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4251. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4252. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4253. const isLeftNozzle = extruderId === 1;
  4254. const isRightNozzle = extruderId === 0;
  4255. return (
  4256. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4257. {/* Header: Label + Stats (no icon) */}
  4258. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4259. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4260. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4261. <AmsNameHoverCard
  4262. ams={ams}
  4263. printerId={printer.id}
  4264. label={getAmsLabel(ams.id, ams.tray.length)}
  4265. amsLabels={amsLabels}
  4266. canEdit={hasPermission('printers:update')}
  4267. onSaved={refetchAmsLabels}
  4268. >
  4269. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4270. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4271. </span>
  4272. </AmsNameHoverCard>
  4273. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4274. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4275. )}
  4276. </div>
  4277. {(ams.humidity != null || ams.temp != null) && (
  4278. <div className="flex shrink-0 items-center gap-1.5">
  4279. {ams.humidity != null && (
  4280. <HumidityIndicator
  4281. humidity={ams.humidity}
  4282. goodThreshold={amsThresholds?.humidityGood}
  4283. fairThreshold={amsThresholds?.humidityFair}
  4284. onClick={() => setAmsHistoryModal({
  4285. amsId: ams.id,
  4286. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4287. mode: 'humidity',
  4288. })}
  4289. compact
  4290. />
  4291. )}
  4292. {ams.temp != null && (
  4293. <div className="mr-1">
  4294. <TemperatureIndicator
  4295. temp={ams.temp}
  4296. goodThreshold={amsThresholds?.tempGood}
  4297. fairThreshold={amsThresholds?.tempFair}
  4298. onClick={() => setAmsHistoryModal({
  4299. amsId: ams.id,
  4300. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4301. mode: 'temperature',
  4302. })}
  4303. compact
  4304. />
  4305. </div>
  4306. )}
  4307. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4308. Screen-only models (P1 series) keep the control but can't
  4309. be commanded: it stays disabled and says why (#2533). */}
  4310. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4311. <button
  4312. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4313. onClick={(e) => {
  4314. if (ams.dry_time > 0) {
  4315. stopDryingMutation.mutate(ams.id);
  4316. } else if (dryingPopoverAmsId === ams.id) {
  4317. setDryingPopoverAmsId(null);
  4318. } else {
  4319. const firstTray = ams.tray.find(t => t.tray_type);
  4320. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4321. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4322. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4323. setDryingFilament(filType);
  4324. setDryingTemp(preset[moduleType] || preset.n3f);
  4325. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4326. setDryingRotateTray(false);
  4327. setDryingPopoverModuleType(ams.module_type);
  4328. setDryingPopoverAmsId(ams.id);
  4329. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4330. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4331. }
  4332. }}
  4333. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4334. ams.dry_time > 0
  4335. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4336. : status.drying_screen_only || ams.dry_sf_reason?.length
  4337. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4338. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4339. }`}
  4340. 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')}
  4341. >
  4342. <Flame className="w-3 h-3" />
  4343. </button>
  4344. )}
  4345. </div>
  4346. )}
  4347. </div>
  4348. {/* Drying status bar */}
  4349. {ams.dry_time > 0 && (
  4350. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  4351. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4352. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4353. {ams.dry_filament && ams.dry_target_temp != null && (
  4354. <span className="text-amber-700/80 dark:text-amber-300/70">
  4355. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4356. </span>
  4357. )}
  4358. <span className="text-amber-700/80 dark:text-amber-300/70">
  4359. {t('printers.drying.timeRemaining', {
  4360. time: ams.dry_time >= 60
  4361. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4362. : `${ams.dry_time}m`
  4363. })}
  4364. </span>
  4365. {/* A cycle on a screen-only model was started at the printer
  4366. and can only be stopped there (#2533). */}
  4367. {!status.drying_screen_only && (
  4368. <button
  4369. onClick={() => stopDryingMutation.mutate(ams.id)}
  4370. disabled={stopDryingMutation.isPending}
  4371. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  4372. title={t('printers.drying.stop')}
  4373. >
  4374. <X className="w-3 h-3" />
  4375. </button>
  4376. )}
  4377. </div>
  4378. )}
  4379. {/* Slots grid: 4 columns - always render 4 slots */}
  4380. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4381. {[0, 1, 2, 3].map((slotIdx) => {
  4382. // Find tray data for this slot (may be undefined if data incomplete)
  4383. // Use array index if available, as tray.id may not always be set
  4384. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4385. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4386. const isEmpty = !tray?.tray_type;
  4387. const emptyKind = getEmptySlotKind(tray);
  4388. // Check if this is the currently loaded tray
  4389. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4390. const globalTrayId = ams.id * 4 + slotIdx;
  4391. const isActive = effectiveTrayNow === globalTrayId;
  4392. // Get cloud preset info if available
  4393. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4394. // Get saved slot preset mapping (for user-configured slots)
  4395. const slotPreset = slotPresets?.[globalTrayId];
  4396. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4397. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4398. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4399. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4400. // Slot-assigned-only spool fill (no tag link required)
  4401. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4402. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4403. : undefined;
  4404. const slotSpoolForFill = slotAssignmentForFill
  4405. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4406. : undefined;
  4407. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4408. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4409. : null;
  4410. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4411. const inventoryFill = (() => {
  4412. const sp = inventoryAssignment?.spool;
  4413. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4414. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4415. }
  4416. return null;
  4417. })();
  4418. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4419. // (inventory weight_used may be stale or over-counted — #676)
  4420. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4421. ? null : inventoryFill;
  4422. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4423. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4424. : resolvedInventoryFill !== null ? 'inventory' as const
  4425. : hasFillLevel ? 'ams' as const
  4426. : undefined;
  4427. // Build filament data for hover card
  4428. const filamentData = tray?.tray_type ? {
  4429. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4430. // Spoolman spool name wins over cloud lookup so a slot bound to
  4431. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4432. // Design PLA") instead of whatever the printer's filament_id
  4433. // resolves to in the cloud catalog (often "Generic PLA" for
  4434. // P-prefix local presets). Spoolman's filament.name is just the
  4435. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4436. // the hover card shows "Devil Design PLA Basic" rather than the
  4437. // vendor-less form. Strip the "@<printer>..." suffix that
  4438. // BambuStudio appends to user-preset names.
  4439. 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,
  4440. colorName: getColorName(tray.tray_color || ''),
  4441. colorHex: tray.tray_color || null,
  4442. kFactor: formatKValue(tray.k),
  4443. fillLevel: effectiveFill,
  4444. trayUuid: tray.tray_uuid || null,
  4445. tagUid: tray.tag_uid || null,
  4446. fillSource,
  4447. } : null;
  4448. // Check if this specific slot is being refreshed
  4449. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4450. refreshingSlot?.slotId === slotIdx;
  4451. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4452. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4453. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4454. ? `P${activePrintSlotIdx + 1}`
  4455. : null;
  4456. // Slot visual content (goes inside hover card)
  4457. const slotVisual = (
  4458. <div
  4459. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4460. >
  4461. {activePrintSlotLabel && (
  4462. <span
  4463. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4464. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4465. 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"
  4466. >
  4467. {activePrintSlotLabel}
  4468. </span>
  4469. )}
  4470. {/* Filament color circle with 1-based slot number centered inside */}
  4471. <FilamentSlotCircle
  4472. trayColor={tray?.tray_color}
  4473. trayType={tray?.tray_type}
  4474. isEmpty={isEmpty}
  4475. emptyKind={emptyKind}
  4476. slotNumber={slotIdx + 1}
  4477. />
  4478. <div className="text-[9px] text-white font-bold truncate">
  4479. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4480. </div>
  4481. {/* Fill bar */}
  4482. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4483. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4484. <div
  4485. className="h-full rounded-full transition-all"
  4486. style={{
  4487. width: `${effectiveFill}%`,
  4488. backgroundColor: getFillBarColor(effectiveFill),
  4489. }}
  4490. />
  4491. )}
  4492. </div>
  4493. </div>
  4494. );
  4495. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4496. return (
  4497. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4498. {/* Loading overlay during RFID re-read */}
  4499. {isRefreshing && (
  4500. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4501. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4502. </div>
  4503. )}
  4504. {/* Hover card wraps only the visual content */}
  4505. {filamentData ? (
  4506. <FilamentHoverCard
  4507. data={filamentData}
  4508. actions={renderAmsSlotActions({
  4509. amsId: ams.id,
  4510. slotId: slotIdx,
  4511. loadTrayId: ams.id * 4 + slotIdx,
  4512. isRefreshing,
  4513. })}
  4514. spoolman={{
  4515. enabled: spoolmanEnabled,
  4516. // #1457: slot assignment is the user's most explicit action — it must
  4517. // outrank the tag-link, which can be stale when a non-RFID slot's
  4518. // fallback tag is still attached to a previous spool in Spoolman.
  4519. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4520. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4521. spoolmanUrl,
  4522. syncMode: spoolmanSyncMode,
  4523. // Suppress Link button when slot is already occupied by ANY assignment
  4524. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4525. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4526. // still appearing on slots with a local Devil Design PLA assigned.
  4527. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4528. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4529. setLinkSpoolModal({
  4530. tagUid: filamentData.tagUid || linkTag,
  4531. trayUuid: filamentData.trayUuid || '',
  4532. printerId: printer.id,
  4533. amsId: ams.id,
  4534. trayId: slotIdx,
  4535. });
  4536. } : undefined,
  4537. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4538. }}
  4539. inventory={(() => {
  4540. if (spoolmanEnabled) {
  4541. if (spoolmanLoading) return undefined;
  4542. const slotAssignment = slotAssignmentForFill;
  4543. const spoolmanSpool = slotSpoolForFill;
  4544. return {
  4545. assignedSpool: spoolmanSpool ? {
  4546. id: spoolmanSpool.id,
  4547. material: spoolmanSpool.material,
  4548. brand: spoolmanSpool.brand ?? null,
  4549. color_name: spoolmanSpool.color_name ?? null,
  4550. remainingWeightGrams: spoolmanSpool.label_weight
  4551. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4552. : undefined,
  4553. } : null,
  4554. onAssignSpool: () => setAssignSpoolModal({
  4555. printerId: printer.id,
  4556. amsId: ams.id,
  4557. trayId: slotIdx,
  4558. trayInfo: {
  4559. type: tray?.tray_type || filamentData.profile,
  4560. material: tray?.tray_type ?? undefined,
  4561. profile: filamentData.profile,
  4562. color: filamentData.colorHex || '',
  4563. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4564. },
  4565. }),
  4566. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4567. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4568. };
  4569. }
  4570. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4571. return {
  4572. assignedSpool: assignment?.spool ? {
  4573. id: assignment.spool.id,
  4574. material: assignment.spool.material,
  4575. brand: assignment.spool.brand,
  4576. color_name: assignment.spool.color_name,
  4577. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4578. } : null,
  4579. onAssignSpool: () => setAssignSpoolModal({
  4580. printerId: printer.id,
  4581. amsId: ams.id,
  4582. trayId: slotIdx,
  4583. trayInfo: {
  4584. type: tray?.tray_type || filamentData.profile,
  4585. material: tray?.tray_type ?? undefined,
  4586. profile: filamentData.profile,
  4587. color: filamentData.colorHex || '',
  4588. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4589. },
  4590. }),
  4591. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4592. isAssigned: !!assignment || isBambuLabSpool(tray),
  4593. };
  4594. })()}
  4595. configureSlot={{
  4596. enabled: hasPermission('printers:control'),
  4597. onConfigure: () => setConfigureSlotModal({
  4598. amsId: ams.id,
  4599. trayId: slotIdx,
  4600. trayCount: ams.tray.length,
  4601. trayType: tray?.tray_type || undefined,
  4602. trayColor: tray?.tray_color || undefined,
  4603. traySubBrands: tray?.tray_sub_brands || undefined,
  4604. trayInfoIdx: tray?.tray_info_idx || undefined,
  4605. extruderId: mappedExtruderId,
  4606. caliIdx: tray?.cali_idx,
  4607. savedPresetId: slotPreset?.preset_id,
  4608. }),
  4609. }}
  4610. >
  4611. {slotVisual}
  4612. </FilamentHoverCard>
  4613. ) : (
  4614. <EmptySlotHoverCard
  4615. kind={emptyKind ?? undefined}
  4616. actions={renderAmsSlotActions({
  4617. amsId: ams.id,
  4618. slotId: slotIdx,
  4619. loadTrayId: ams.id * 4 + slotIdx,
  4620. isRefreshing,
  4621. })}
  4622. configureSlot={{
  4623. enabled: hasPermission('printers:control'),
  4624. onConfigure: () => setConfigureSlotModal({
  4625. amsId: ams.id,
  4626. trayId: slotIdx,
  4627. trayCount: ams.tray.length,
  4628. extruderId: mappedExtruderId,
  4629. }),
  4630. }}
  4631. onAssignSpool={() => setAssignSpoolModal({
  4632. printerId: printer.id,
  4633. amsId: ams.id,
  4634. trayId: slotIdx,
  4635. trayInfo: {
  4636. type: '',
  4637. material: undefined,
  4638. profile: '',
  4639. color: '',
  4640. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4641. },
  4642. })}
  4643. >
  4644. {slotVisual}
  4645. </EmptySlotHoverCard>
  4646. )}
  4647. </div>
  4648. );
  4649. })}
  4650. </div>
  4651. </div>
  4652. );
  4653. })}
  4654. {/* HT AMS units */}
  4655. {htAms.map((ams) => {
  4656. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4657. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4658. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4659. const isLeftNozzle = extruderId === 1;
  4660. const isRightNozzle = extruderId === 0;
  4661. const tray = ams.tray[0];
  4662. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4663. const isEmpty = !tray?.tray_type;
  4664. const emptyKind = getEmptySlotKind(tray);
  4665. // Check if this is the currently loaded tray
  4666. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4667. const isActive = effectiveTrayNow === globalTrayId;
  4668. // Get cloud preset info if available
  4669. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4670. // Get saved slot preset mapping (for user-configured slots)
  4671. const slotPreset = slotPresets?.[globalTrayId];
  4672. const htSlotId = tray?.id ?? 0;
  4673. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4674. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4675. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4676. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4677. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4678. const htInventoryFill = (() => {
  4679. const sp = htInventoryAssignment?.spool;
  4680. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4681. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4682. }
  4683. return null;
  4684. })();
  4685. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4686. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4687. ? null : htInventoryFill;
  4688. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4689. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4690. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4691. : undefined;
  4692. const htSlotSpoolForFill = htSlotAssignmentForFill
  4693. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4694. : undefined;
  4695. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4696. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4697. : null;
  4698. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4699. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4700. : htResolvedInventoryFill !== null ? 'inventory' as const
  4701. : hasFillLevel ? 'ams' as const
  4702. : undefined;
  4703. // Build filament data for hover card
  4704. const filamentData = tray?.tray_type ? {
  4705. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4706. 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,
  4707. colorName: getColorName(tray.tray_color || ''),
  4708. colorHex: tray.tray_color || null,
  4709. kFactor: formatKValue(tray.k),
  4710. fillLevel: htEffectiveFill,
  4711. trayUuid: tray.tray_uuid || null,
  4712. tagUid: tray.tag_uid || null,
  4713. fillSource: htFillSource,
  4714. } : null;
  4715. // Check if this specific slot is being refreshed
  4716. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4717. refreshingSlot?.slotId === htSlotId;
  4718. // #1762 (comment 2): active print-slot index for this HT slot.
  4719. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4720. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4721. ? `P${htActivePrintSlotIdx + 1}`
  4722. : null;
  4723. // Slot visual content (goes inside hover card)
  4724. const slotVisual = (
  4725. <div
  4726. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  4727. >
  4728. {htActivePrintSlotLabel && (
  4729. <span
  4730. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4731. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4732. 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"
  4733. >
  4734. {htActivePrintSlotLabel}
  4735. </span>
  4736. )}
  4737. {/* Filament color circle with 1-based slot number centered inside */}
  4738. <FilamentSlotCircle
  4739. trayColor={tray?.tray_color}
  4740. trayType={tray?.tray_type}
  4741. isEmpty={isEmpty}
  4742. emptyKind={emptyKind}
  4743. slotNumber={1}
  4744. />
  4745. <div className="text-[9px] text-white font-bold truncate">
  4746. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4747. </div>
  4748. {/* Fill bar */}
  4749. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4750. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4751. <div
  4752. className="h-full rounded-full transition-all"
  4753. style={{
  4754. width: `${htEffectiveFill}%`,
  4755. backgroundColor: getFillBarColor(htEffectiveFill),
  4756. }}
  4757. />
  4758. )}
  4759. </div>
  4760. </div>
  4761. );
  4762. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4763. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4764. // Without this override, the L view squishes HT into a sliver next to the
  4765. // 4-slot AMS neighbors.
  4766. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4767. return (
  4768. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4769. {/* Row 1: Label + Nozzle + Drying */}
  4770. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4771. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4772. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4773. <AmsNameHoverCard
  4774. ams={ams}
  4775. printerId={printer.id}
  4776. label={getAmsLabel(ams.id, ams.tray.length)}
  4777. amsLabels={amsLabels}
  4778. canEdit={hasPermission('printers:update')}
  4779. onSaved={refetchAmsLabels}
  4780. >
  4781. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4782. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4783. </span>
  4784. </AmsNameHoverCard>
  4785. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4786. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4787. )}
  4788. </div>
  4789. {/* Drying button for HT AMS */}
  4790. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4791. <div className="relative ml-auto">
  4792. <button
  4793. disabled={status.drying_screen_only}
  4794. onClick={(e) => {
  4795. if (ams.dry_time > 0) {
  4796. stopDryingMutation.mutate(ams.id);
  4797. } else if (dryingPopoverAmsId === ams.id) {
  4798. setDryingPopoverAmsId(null);
  4799. } else {
  4800. const firstTray = ams.tray.find(t => t.tray_type);
  4801. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4802. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4803. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4804. setDryingFilament(filType);
  4805. setDryingTemp(preset[moduleType] || preset.n3f);
  4806. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4807. setDryingRotateTray(false);
  4808. setDryingPopoverModuleType(ams.module_type);
  4809. setDryingPopoverAmsId(ams.id);
  4810. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4811. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4812. }
  4813. }}
  4814. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4815. ams.dry_time > 0
  4816. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4817. : status.drying_screen_only
  4818. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4819. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4820. }`}
  4821. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  4822. >
  4823. <Flame className="w-3 h-3" />
  4824. </button>
  4825. </div>
  4826. )}
  4827. </div>
  4828. {/* HT AMS drying status bar */}
  4829. {ams.dry_time > 0 && (
  4830. <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]">
  4831. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4832. {ams.dry_filament && ams.dry_target_temp != null && (
  4833. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  4834. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4835. </span>
  4836. )}
  4837. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  4838. {ams.dry_time >= 60
  4839. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4840. : `${ams.dry_time}m`}
  4841. </span>
  4842. {!status.drying_screen_only && (
  4843. <button
  4844. onClick={() => stopDryingMutation.mutate(ams.id)}
  4845. disabled={stopDryingMutation.isPending}
  4846. 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"
  4847. title={t('printers.drying.stop')}
  4848. >
  4849. <X className="w-3 h-3" />
  4850. </button>
  4851. )}
  4852. </div>
  4853. )}
  4854. {/* Row 2: Slot (left) + Stats (right stacked) */}
  4855. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  4856. {/* Slot wrapper with loading overlay */}
  4857. <div className="relative group min-w-14 flex-1">
  4858. {/* Loading overlay during RFID re-read */}
  4859. {isHtRefreshing && (
  4860. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4861. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4862. </div>
  4863. )}
  4864. {/* Hover card wraps only the visual content */}
  4865. {filamentData ? (
  4866. <FilamentHoverCard
  4867. data={filamentData}
  4868. actions={renderAmsSlotActions({
  4869. amsId: ams.id,
  4870. slotId: htSlotId,
  4871. loadTrayId: ams.id * 4 + htSlotId,
  4872. isRefreshing: isHtRefreshing,
  4873. })}
  4874. spoolman={{
  4875. enabled: spoolmanEnabled,
  4876. // #1457: slot assignment outranks tag-link (see top-level slot block).
  4877. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  4878. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  4879. spoolmanUrl,
  4880. syncMode: spoolmanSyncMode,
  4881. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  4882. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  4883. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  4884. setLinkSpoolModal({
  4885. tagUid: filamentData.tagUid || linkTag,
  4886. trayUuid: filamentData.trayUuid || '',
  4887. printerId: printer.id,
  4888. amsId: ams.id,
  4889. trayId: htSlotId,
  4890. });
  4891. } : undefined,
  4892. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  4893. }}
  4894. inventory={(() => {
  4895. if (spoolmanEnabled) {
  4896. if (spoolmanLoading) return undefined;
  4897. const slotAssignment = htSlotAssignmentForFill;
  4898. const spoolmanSpool = htSlotSpoolForFill;
  4899. return {
  4900. assignedSpool: spoolmanSpool ? {
  4901. id: spoolmanSpool.id,
  4902. material: spoolmanSpool.material,
  4903. brand: spoolmanSpool.brand ?? null,
  4904. color_name: spoolmanSpool.color_name ?? null,
  4905. remainingWeightGrams: spoolmanSpool.label_weight
  4906. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4907. : undefined,
  4908. } : null,
  4909. onAssignSpool: () => setAssignSpoolModal({
  4910. printerId: printer.id,
  4911. amsId: ams.id,
  4912. trayId: htSlotId,
  4913. trayInfo: {
  4914. type: tray?.tray_type || filamentData.profile,
  4915. material: tray?.tray_type ?? undefined,
  4916. profile: filamentData.profile,
  4917. color: filamentData.colorHex || '',
  4918. location: getAmsLabel(ams.id, ams.tray.length),
  4919. },
  4920. }),
  4921. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4922. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4923. };
  4924. }
  4925. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4926. return {
  4927. assignedSpool: assignment?.spool ? {
  4928. id: assignment.spool.id,
  4929. material: assignment.spool.material,
  4930. brand: assignment.spool.brand,
  4931. color_name: assignment.spool.color_name,
  4932. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4933. } : null,
  4934. onAssignSpool: () => setAssignSpoolModal({
  4935. printerId: printer.id,
  4936. amsId: ams.id,
  4937. trayId: htSlotId,
  4938. trayInfo: {
  4939. type: tray?.tray_type || filamentData.profile,
  4940. material: tray?.tray_type ?? undefined,
  4941. profile: filamentData.profile,
  4942. color: filamentData.colorHex || '',
  4943. location: getAmsLabel(ams.id, ams.tray.length),
  4944. },
  4945. }),
  4946. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  4947. isAssigned: !!assignment || isBambuLabSpool(tray),
  4948. };
  4949. })()}
  4950. configureSlot={{
  4951. enabled: hasPermission('printers:control'),
  4952. onConfigure: () => setConfigureSlotModal({
  4953. amsId: ams.id,
  4954. trayId: htSlotId,
  4955. trayCount: ams.tray.length,
  4956. trayType: tray?.tray_type || undefined,
  4957. trayColor: tray?.tray_color || undefined,
  4958. traySubBrands: tray?.tray_sub_brands || undefined,
  4959. trayInfoIdx: tray?.tray_info_idx || undefined,
  4960. extruderId: mappedExtruderId,
  4961. caliIdx: tray?.cali_idx,
  4962. savedPresetId: slotPreset?.preset_id,
  4963. }),
  4964. }}
  4965. >
  4966. {slotVisual}
  4967. </FilamentHoverCard>
  4968. ) : (
  4969. <EmptySlotHoverCard
  4970. kind={emptyKind ?? undefined}
  4971. actions={renderAmsSlotActions({
  4972. amsId: ams.id,
  4973. slotId: htSlotId,
  4974. loadTrayId: ams.id * 4 + htSlotId,
  4975. isRefreshing: isHtRefreshing,
  4976. })}
  4977. configureSlot={{
  4978. enabled: hasPermission('printers:control'),
  4979. onConfigure: () => setConfigureSlotModal({
  4980. amsId: ams.id,
  4981. trayId: htSlotId,
  4982. trayCount: ams.tray.length,
  4983. extruderId: mappedExtruderId,
  4984. }),
  4985. }}
  4986. onAssignSpool={() => setAssignSpoolModal({
  4987. printerId: printer.id,
  4988. amsId: ams.id,
  4989. trayId: htSlotId,
  4990. trayInfo: {
  4991. type: '',
  4992. material: undefined,
  4993. profile: '',
  4994. color: '',
  4995. location: getAmsLabel(ams.id, ams.tray.length),
  4996. },
  4997. })}
  4998. >
  4999. {slotVisual}
  5000. </EmptySlotHoverCard>
  5001. )}
  5002. </div>
  5003. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5004. {(ams.humidity != null || ams.temp != null) && (
  5005. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5006. {ams.temp != null && (
  5007. <TemperatureIndicator
  5008. temp={ams.temp}
  5009. goodThreshold={amsThresholds?.tempGood}
  5010. fairThreshold={amsThresholds?.tempFair}
  5011. onClick={() => setAmsHistoryModal({
  5012. amsId: ams.id,
  5013. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5014. mode: 'temperature',
  5015. })}
  5016. compact
  5017. />
  5018. )}
  5019. {ams.humidity != null && (
  5020. <HumidityIndicator
  5021. humidity={ams.humidity}
  5022. goodThreshold={amsThresholds?.humidityGood}
  5023. fairThreshold={amsThresholds?.humidityFair}
  5024. onClick={() => setAmsHistoryModal({
  5025. amsId: ams.id,
  5026. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5027. mode: 'humidity',
  5028. })}
  5029. compact
  5030. />
  5031. )}
  5032. </div>
  5033. )}
  5034. </div>
  5035. </div>
  5036. );
  5037. })}
  5038. {/* External spool(s) - grouped in one card like regular AMS */}
  5039. {status.vt_tray.length > 0 && (
  5040. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5041. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5042. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  5043. </div>
  5044. <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`}>
  5045. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5046. const extTrayId = extTray.id ?? 254;
  5047. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5048. // generically — use active_extruder to determine L vs R:
  5049. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5050. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5051. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5052. (extTrayId === 255 && status.active_extruder === 0)
  5053. : effectiveTrayNow === extTrayId;
  5054. const slotTrayId = extTrayId - 254; // 0 or 1
  5055. const extLabel = isDualNozzle
  5056. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5057. : '';
  5058. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5059. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5060. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5061. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5062. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5063. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5064. const extInventoryFill = (() => {
  5065. const sp = extInventoryAssignment?.spool;
  5066. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5067. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5068. }
  5069. return null;
  5070. })();
  5071. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5072. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5073. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5074. ? null : extInventoryFill;
  5075. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5076. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5077. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5078. : undefined;
  5079. const extSlotSpoolForFill = extSlotAssignmentForFill
  5080. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5081. : undefined;
  5082. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5083. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5084. : null;
  5085. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5086. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5087. : extResolvedInventoryFill !== null ? 'inventory' as const
  5088. : extHasFillLevel ? 'ams' as const
  5089. : undefined;
  5090. const extFilamentData = {
  5091. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5092. 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',
  5093. colorName: getColorName(extTray.tray_color || ''),
  5094. colorHex: extTray.tray_color || null,
  5095. kFactor: formatKValue(extTray.k),
  5096. fillLevel: extEffectiveFill,
  5097. trayUuid: extTray.tray_uuid || null,
  5098. tagUid: extTray.tag_uid || null,
  5099. fillSource: extFillSource,
  5100. };
  5101. const isEmpty = !extTray.tray_type;
  5102. const emptyKind = getEmptySlotKind(extTray);
  5103. const extSlotContent = (
  5104. <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' : ''}`}>
  5105. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5106. the separate Ext-L/Ext-R caption that made the row taller than
  5107. regular AMS slots), 1-based slot number on single-nozzle. */}
  5108. <FilamentSlotCircle
  5109. trayColor={extTray.tray_color}
  5110. trayType={extTray.tray_type}
  5111. isEmpty={isEmpty}
  5112. emptyKind={emptyKind}
  5113. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5114. />
  5115. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5116. {extTray.tray_type || t('ams.slotEmpty')}
  5117. </div>
  5118. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5119. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5120. <div
  5121. className="h-full rounded-full transition-all"
  5122. style={{
  5123. width: `${extEffectiveFill}%`,
  5124. backgroundColor: getFillBarColor(extEffectiveFill),
  5125. }}
  5126. />
  5127. )}
  5128. </div>
  5129. </div>
  5130. );
  5131. return (
  5132. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5133. {!isEmpty ? (
  5134. <FilamentHoverCard
  5135. data={extFilamentData}
  5136. actions={renderAmsSlotActions({
  5137. amsId: 255,
  5138. slotId: slotTrayId,
  5139. loadTrayId: extTrayId,
  5140. includeRfid: false,
  5141. })}
  5142. spoolman={{
  5143. enabled: spoolmanEnabled,
  5144. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5145. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5146. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5147. spoolmanUrl,
  5148. syncMode: spoolmanSyncMode,
  5149. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5150. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5151. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5152. setLinkSpoolModal({
  5153. tagUid: extFilamentData.tagUid || linkTag,
  5154. trayUuid: extFilamentData.trayUuid || '',
  5155. printerId: printer.id,
  5156. amsId: 255,
  5157. trayId: slotTrayId,
  5158. });
  5159. } : undefined,
  5160. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5161. }}
  5162. inventory={(() => {
  5163. if (spoolmanEnabled) {
  5164. if (spoolmanLoading) return undefined;
  5165. const slotAssignment = extSlotAssignmentForFill;
  5166. const spoolmanSpool = extSlotSpoolForFill;
  5167. return {
  5168. assignedSpool: spoolmanSpool ? {
  5169. id: spoolmanSpool.id,
  5170. material: spoolmanSpool.material,
  5171. brand: spoolmanSpool.brand ?? null,
  5172. color_name: spoolmanSpool.color_name ?? null,
  5173. remainingWeightGrams: spoolmanSpool.label_weight
  5174. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5175. : undefined,
  5176. } : null,
  5177. onAssignSpool: () => setAssignSpoolModal({
  5178. printerId: printer.id,
  5179. amsId: 255,
  5180. trayId: slotTrayId,
  5181. trayInfo: {
  5182. type: extTray.tray_type || extFilamentData.profile,
  5183. material: extTray.tray_type ?? undefined,
  5184. profile: extFilamentData.profile,
  5185. color: extFilamentData.colorHex || '',
  5186. location: extLabel || t('printers.external'),
  5187. },
  5188. }),
  5189. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5190. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5191. };
  5192. }
  5193. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5194. return {
  5195. assignedSpool: assignment?.spool ? {
  5196. id: assignment.spool.id,
  5197. material: assignment.spool.material,
  5198. brand: assignment.spool.brand,
  5199. color_name: assignment.spool.color_name,
  5200. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5201. } : null,
  5202. onAssignSpool: () => setAssignSpoolModal({
  5203. printerId: printer.id,
  5204. amsId: 255,
  5205. trayId: slotTrayId,
  5206. trayInfo: {
  5207. type: extTray.tray_type || extFilamentData.profile,
  5208. material: extTray.tray_type ?? undefined,
  5209. profile: extFilamentData.profile,
  5210. color: extFilamentData.colorHex || '',
  5211. location: extLabel || t('printers.external'),
  5212. },
  5213. }),
  5214. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5215. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5216. };
  5217. })()}
  5218. configureSlot={{
  5219. enabled: hasPermission('printers:control'),
  5220. onConfigure: () => setConfigureSlotModal({
  5221. amsId: 255,
  5222. trayId: slotTrayId,
  5223. trayCount: 1,
  5224. trayType: extTray.tray_type || undefined,
  5225. trayColor: extTray.tray_color || undefined,
  5226. traySubBrands: extTray.tray_sub_brands || undefined,
  5227. trayInfoIdx: extTray.tray_info_idx || undefined,
  5228. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5229. caliIdx: extTray.cali_idx,
  5230. savedPresetId: extSlotPreset?.preset_id,
  5231. }),
  5232. }}
  5233. >
  5234. {extSlotContent}
  5235. </FilamentHoverCard>
  5236. ) : (
  5237. <EmptySlotHoverCard
  5238. kind={emptyKind ?? undefined}
  5239. actions={renderAmsSlotActions({
  5240. amsId: 255,
  5241. slotId: slotTrayId,
  5242. loadTrayId: extTrayId,
  5243. includeRfid: false,
  5244. })}
  5245. configureSlot={{
  5246. enabled: hasPermission('printers:control'),
  5247. onConfigure: () => setConfigureSlotModal({
  5248. amsId: 255,
  5249. trayId: slotTrayId,
  5250. trayCount: 1,
  5251. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5252. }),
  5253. }}
  5254. onAssignSpool={() => setAssignSpoolModal({
  5255. printerId: printer.id,
  5256. amsId: 255,
  5257. trayId: slotTrayId,
  5258. trayInfo: {
  5259. type: '',
  5260. material: undefined,
  5261. profile: '',
  5262. color: '',
  5263. location: `External Slot ${slotTrayId + 1}`,
  5264. },
  5265. })}
  5266. >
  5267. {extSlotContent}
  5268. </EmptySlotHoverCard>
  5269. )}
  5270. </div>
  5271. );
  5272. })}
  5273. </div>
  5274. </div>
  5275. )}
  5276. </div>
  5277. </div>
  5278. );
  5279. })()}
  5280. </>
  5281. )}
  5282. {/* Bottom block (power row + action bar). Wrapped together so the
  5283. power row hugs the action bar at the card bottom instead of
  5284. floating up when there's less filament content above. */}
  5285. {viewMode === 'expanded' && (
  5286. <div className="mt-auto">
  5287. {smartPlug && (
  5288. <div className="pt-3">
  5289. <div className="flex items-center gap-2 mb-2">
  5290. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5291. {t('printers.power', 'Power')}
  5292. </span>
  5293. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5294. </div>
  5295. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5296. {/* Plug name + current power */}
  5297. <div className="flex items-center gap-2 min-w-0 pl-1">
  5298. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5299. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5300. <span
  5301. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5302. title={t('smartPlugs.power')}
  5303. >
  5304. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5305. </span>
  5306. </div>
  5307. {/* Spacer */}
  5308. <div className="flex-1" />
  5309. <div className="flex items-center gap-2">
  5310. {/* Auto-off */}
  5311. <button
  5312. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5313. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5314. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5315. 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 ${
  5316. !hasPermission('smart_plugs:control')
  5317. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5318. : smartPlug.auto_off || smartPlug.auto_off_executed
  5319. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5320. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5321. }`}
  5322. >
  5323. <Clock className="w-4 h-4" />
  5324. </button>
  5325. <button
  5326. onClick={() => {
  5327. if (plugStatus?.state === 'ON') {
  5328. setShowPowerOffConfirm(true);
  5329. } else {
  5330. setShowPowerOnConfirm(true);
  5331. }
  5332. }}
  5333. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5334. 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 ${
  5335. !hasPermission('smart_plugs:control')
  5336. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5337. : plugStatus?.state === 'ON'
  5338. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5339. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5340. }`}
  5341. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5342. >
  5343. <Zap className="w-4 h-4" />
  5344. </button>
  5345. </div>
  5346. </div>
  5347. {/* HA entity buttons row */}
  5348. {scriptPlugs && scriptPlugs.length > 0 && (
  5349. <div className="flex items-center gap-2 mt-2">
  5350. <Home className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
  5351. <span className="text-xs text-bambu-gray">HA:</span>
  5352. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5353. <div className="flex flex-wrap gap-1">
  5354. {scriptPlugs.map(script => {
  5355. const isScript = script.ha_entity_id?.startsWith('script.');
  5356. return (
  5357. <button
  5358. key={script.id}
  5359. onClick={() => {
  5360. if (isScript) {
  5361. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5362. } else {
  5363. setHaToggleConfirm(script);
  5364. }
  5365. }}
  5366. disabled={runScriptMutation.isPending}
  5367. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5368. 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"
  5369. >
  5370. <Play className="w-2.5 h-2.5" />
  5371. {script.name}
  5372. </button>
  5373. );
  5374. })}
  5375. </div>
  5376. </div>
  5377. )}
  5378. </div>
  5379. )}
  5380. {/* Connection Info & Actions */}
  5381. <div className="pt-4">
  5382. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5383. <div className="flex items-center justify-between gap-2">
  5384. {printerActionsMenu}
  5385. <div className="flex items-center justify-end gap-2 flex-wrap">
  5386. {/* Camera Button */}
  5387. <Button
  5388. variant="secondary"
  5389. size="sm"
  5390. onClick={() => {
  5391. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5392. onOpenEmbeddedCamera(printer.id, printer.name);
  5393. } else {
  5394. // Use saved window state or defaults
  5395. const saved = localStorage.getItem('cameraWindowState');
  5396. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5397. const features = [
  5398. `width=${state.width}`,
  5399. `height=${state.height}`,
  5400. state.left !== undefined ? `left=${state.left}` : '',
  5401. state.top !== undefined ? `top=${state.top}` : '',
  5402. // No `noopener`: same-origin popup needs opener so the browser
  5403. // copies sessionStorage (auth token) into the new window.
  5404. 'menubar=no,toolbar=no,location=no,status=no',
  5405. ].filter(Boolean).join(',');
  5406. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5407. }
  5408. }}
  5409. disabled={!status?.connected || !hasPermission('camera:view')}
  5410. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5411. className={footerIconButtonClass}
  5412. >
  5413. <Video className="w-4 h-4" />
  5414. </Button>
  5415. <Button
  5416. variant="secondary"
  5417. size="sm"
  5418. onClick={() => setShowFileManager(true)}
  5419. disabled={!isConnected || !hasPermission('printers:files')}
  5420. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5421. className={footerIconButtonClass}
  5422. >
  5423. <HardDrive className="w-4 h-4" />
  5424. </Button>
  5425. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5426. <Button
  5427. size="sm"
  5428. onClick={() => setShowUploadForPrint(true)}
  5429. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  5430. title={
  5431. !hasPermission('library:upload')
  5432. ? t('fileManager.noPermissionUpload')
  5433. : !hasPermission('queue:create')
  5434. ? t('fileManager.noPermissionAddToQueue')
  5435. : t('common.print')
  5436. }
  5437. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5438. >
  5439. <PrinterIcon className="w-4 h-4" />
  5440. {t('common.print')}
  5441. </Button>
  5442. )}
  5443. </div>
  5444. </div>
  5445. </div>
  5446. </div>
  5447. )}
  5448. </CardContent>
  5449. {/* File Manager Modal */}
  5450. {showFileManager && (
  5451. <FileManagerModal
  5452. printerId={printer.id}
  5453. printerName={printer.name}
  5454. onClose={() => setShowFileManager(false)}
  5455. />
  5456. )}
  5457. {/* Upload for Print Modal */}
  5458. {showUploadForPrint && (
  5459. <FileUploadModal
  5460. folderId={null}
  5461. onClose={() => setShowUploadForPrint(false)}
  5462. onUploadComplete={() => {}}
  5463. autoUpload
  5464. accept=".gcode,.3mf"
  5465. validateFile={(file) => {
  5466. const lower = file.name.toLowerCase();
  5467. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5468. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5469. }
  5470. }}
  5471. onFileUploaded={(uploadedFile) => {
  5472. // Check printer compatibility if sliced_for_model is available in metadata
  5473. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5474. const printerModel = mapModelCode(printer.model);
  5475. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5476. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5477. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5478. }
  5479. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5480. }}
  5481. />
  5482. )}
  5483. {/* Print Modal (after upload) */}
  5484. {printAfterUpload && (
  5485. <PrintModal
  5486. mode="create"
  5487. libraryFileId={printAfterUpload.id}
  5488. archiveName={printAfterUpload.filename}
  5489. initialSelectedPrinterIds={[printer.id]}
  5490. onClose={() => setPrintAfterUpload(null)}
  5491. onSuccess={() => setPrintAfterUpload(null)}
  5492. cleanupLibraryAfterDispatch
  5493. />
  5494. )}
  5495. {/* MQTT Debug Modal */}
  5496. {showMQTTDebug && (
  5497. <MQTTDebugModal
  5498. printerId={printer.id}
  5499. printerName={printer.name}
  5500. onClose={() => setShowMQTTDebug(false)}
  5501. />
  5502. )}
  5503. {showDiagnostic && (
  5504. <ConnectionDiagnosticModal
  5505. printerId={printer.id}
  5506. printerName={printer.name}
  5507. onClose={() => setShowDiagnostic(false)}
  5508. />
  5509. )}
  5510. {showPrinterInfo && (
  5511. <PrinterInfoModal
  5512. printer={printer}
  5513. status={status}
  5514. totalPrintHours={maintenanceInfo?.total_print_hours}
  5515. onClose={closePrinterInfo}
  5516. />
  5517. )}
  5518. {/* Plate Check Result Modal */}
  5519. {plateCheckResult && (
  5520. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5521. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5522. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5523. <div className="flex items-center gap-2">
  5524. {plateCheckResult.needs_calibration ? (
  5525. <ScanSearch className="w-5 h-5 text-blue-500" />
  5526. ) : plateCheckResult.is_empty ? (
  5527. <CheckCircle className="w-5 h-5 text-green-500" />
  5528. ) : (
  5529. <XCircle className="w-5 h-5 text-yellow-500" />
  5530. )}
  5531. <h2 className="text-lg font-semibold text-white">
  5532. Build Plate Check
  5533. </h2>
  5534. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5535. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5536. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5537. </span>
  5538. )}
  5539. </div>
  5540. <button
  5541. onClick={() => closePlateCheckModal()}
  5542. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5543. >
  5544. <X className="w-5 h-5" />
  5545. </button>
  5546. </div>
  5547. <div className="p-4 space-y-4">
  5548. {plateCheckResult.needs_calibration ? (
  5549. <>
  5550. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  5551. <p className="font-medium text-blue-700 dark:text-blue-400">
  5552. {t('printers.plateDetection.calibrationRequired')}
  5553. </p>
  5554. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5555. </div>
  5556. <div className="text-sm text-bambu-gray space-y-2">
  5557. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5558. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5559. </div>
  5560. </>
  5561. ) : (
  5562. <>
  5563. <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'}`}>
  5564. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  5565. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5566. </p>
  5567. <p className="text-sm text-bambu-gray mt-1">
  5568. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5569. </p>
  5570. </div>
  5571. {plateCheckResult.debug_image_url && (
  5572. <div>
  5573. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5574. <img
  5575. src={plateCheckResult.debug_image_url}
  5576. alt={t('printers.plateDetection.analysisPreview')}
  5577. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5578. />
  5579. <p className="text-xs text-bambu-gray mt-2">
  5580. {t('printers.plateDetection.analysisLegend')}
  5581. </p>
  5582. </div>
  5583. )}
  5584. <p className="text-xs text-bambu-gray">
  5585. {plateCheckResult.message}
  5586. </p>
  5587. </>
  5588. )}
  5589. {/* Saved References Grid */}
  5590. {plateReferences && plateReferences.references.length > 0 && (
  5591. <div className="mt-4">
  5592. <div className="flex items-center gap-2 mb-2">
  5593. <p className="text-sm font-medium text-white shrink-0">
  5594. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5595. </p>
  5596. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5597. </div>
  5598. <div className="grid grid-cols-5 gap-2">
  5599. {plateReferences.references.map((ref) => (
  5600. <div key={ref.index} className="relative group">
  5601. <img
  5602. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5603. alt={ref.label || `Reference ${ref.index + 1}`}
  5604. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5605. />
  5606. {/* Delete button */}
  5607. <button
  5608. onClick={() => handleDeleteRef(ref.index)}
  5609. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5610. title={t('printers.plateDetection.deleteReference')}
  5611. >
  5612. <X className="w-3 h-3 text-white" />
  5613. </button>
  5614. {/* Label */}
  5615. {editingRefLabel?.index === ref.index ? (
  5616. <input
  5617. type="text"
  5618. value={editingRefLabel.label}
  5619. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5620. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5621. onKeyDown={(e) => {
  5622. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5623. if (e.key === 'Escape') setEditingRefLabel(null);
  5624. }}
  5625. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5626. autoFocus
  5627. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5628. />
  5629. ) : (
  5630. <p
  5631. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5632. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5633. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5634. >
  5635. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5636. </p>
  5637. )}
  5638. {/* Timestamp */}
  5639. <p className="text-[10px] text-bambu-gray/60">
  5640. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5641. </p>
  5642. </div>
  5643. ))}
  5644. </div>
  5645. </div>
  5646. )}
  5647. {/* ROI Editor */}
  5648. {!plateCheckResult.needs_calibration && (
  5649. <div className="mt-4">
  5650. <div className="flex items-center justify-between mb-2">
  5651. <div className="flex min-w-0 flex-1 items-center gap-2">
  5652. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5653. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5654. </div>
  5655. {!editingRoi ? (
  5656. <Button
  5657. variant="ghost"
  5658. size="sm"
  5659. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5660. >
  5661. <Pencil className="w-3 h-3 mr-1" />
  5662. {t('common.edit')}
  5663. </Button>
  5664. ) : (
  5665. <div className="flex gap-1">
  5666. <Button
  5667. variant="ghost"
  5668. size="sm"
  5669. onClick={() => setEditingRoi(null)}
  5670. disabled={isSavingRoi}
  5671. >
  5672. {t('common.cancel')}
  5673. </Button>
  5674. <Button
  5675. size="sm"
  5676. onClick={handleSaveRoi}
  5677. disabled={isSavingRoi}
  5678. >
  5679. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5680. </Button>
  5681. </div>
  5682. )}
  5683. </div>
  5684. {editingRoi ? (
  5685. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5686. <div className="grid grid-cols-2 gap-3">
  5687. <div>
  5688. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5689. <input
  5690. type="range"
  5691. min="0"
  5692. max="0.9"
  5693. step="0.01"
  5694. value={editingRoi.x}
  5695. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5696. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5697. />
  5698. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5699. </div>
  5700. <div>
  5701. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5702. <input
  5703. type="range"
  5704. min="0"
  5705. max="0.9"
  5706. step="0.01"
  5707. value={editingRoi.y}
  5708. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5709. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5710. />
  5711. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5712. </div>
  5713. <div>
  5714. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5715. <input
  5716. type="range"
  5717. min="0.1"
  5718. max="1"
  5719. step="0.01"
  5720. value={editingRoi.w}
  5721. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5722. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5723. />
  5724. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5725. </div>
  5726. <div>
  5727. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5728. <input
  5729. type="range"
  5730. min="0.1"
  5731. max="1"
  5732. step="0.01"
  5733. value={editingRoi.h}
  5734. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5735. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5736. />
  5737. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5738. </div>
  5739. </div>
  5740. <p className="text-xs text-bambu-gray">
  5741. {t('printers.roi.instruction')}
  5742. </p>
  5743. </div>
  5744. ) : (
  5745. <p className="text-xs text-bambu-gray">
  5746. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5747. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5748. </p>
  5749. )}
  5750. </div>
  5751. )}
  5752. </div>
  5753. <div className="flex justify-end gap-2 p-4">
  5754. {plateCheckResult.needs_calibration ? (
  5755. <>
  5756. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5757. {t('common.cancel')}
  5758. </Button>
  5759. <Button
  5760. onClick={() => handleCalibratePlate()}
  5761. disabled={isCalibrating}
  5762. >
  5763. {isCalibrating ? (
  5764. <>
  5765. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5766. Calibrating...
  5767. </>
  5768. ) : (
  5769. 'Calibrate Empty Plate'
  5770. )}
  5771. </Button>
  5772. </>
  5773. ) : (
  5774. <>
  5775. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5776. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5777. </Button>
  5778. <Button onClick={() => closePlateCheckModal()}>
  5779. Close
  5780. </Button>
  5781. </>
  5782. )}
  5783. </div>
  5784. </div>
  5785. </div>
  5786. )}
  5787. {/* Power On Confirmation */}
  5788. {showPowerOnConfirm && smartPlug && (
  5789. <ConfirmModal
  5790. title={t('printers.confirm.powerOnTitle')}
  5791. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  5792. confirmText={t('printers.confirm.powerOnButton')}
  5793. variant="default"
  5794. onConfirm={() => {
  5795. powerControlMutation.mutate('on');
  5796. setShowPowerOnConfirm(false);
  5797. }}
  5798. onCancel={() => setShowPowerOnConfirm(false)}
  5799. />
  5800. )}
  5801. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  5802. disconnects MQTT, which stops progress tracking + completion
  5803. notifications for the in-flight job. Idle / FINISH / FAILED states
  5804. skip this dialog and toggle directly. */}
  5805. {confirmMaintenanceEnter && (
  5806. <ConfirmModal
  5807. title={t('printers.maintenance.confirmMidPrintTitle')}
  5808. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  5809. confirmText={t('printers.maintenance.menuEnter')}
  5810. variant="danger"
  5811. onConfirm={() => {
  5812. maintenanceMutation.mutate(false);
  5813. setConfirmMaintenanceEnter(false);
  5814. }}
  5815. onCancel={() => setConfirmMaintenanceEnter(false)}
  5816. />
  5817. )}
  5818. {/* Power Off Confirmation */}
  5819. {showPowerOffConfirm && smartPlug && (
  5820. <ConfirmModal
  5821. title={t('printers.confirm.powerOffTitle')}
  5822. message={
  5823. status?.state === 'RUNNING'
  5824. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  5825. : t('printers.confirm.powerOffMessage', { name: printer.name })
  5826. }
  5827. confirmText={t('printers.confirm.powerOffButton')}
  5828. variant="danger"
  5829. onConfirm={() => {
  5830. powerControlMutation.mutate('off');
  5831. setShowPowerOffConfirm(false);
  5832. }}
  5833. onCancel={() => setShowPowerOffConfirm(false)}
  5834. />
  5835. )}
  5836. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  5837. {haToggleConfirm && (
  5838. <ConfirmModal
  5839. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  5840. message={
  5841. status?.state === 'RUNNING'
  5842. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5843. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  5844. }
  5845. confirmText={t('printers.confirm.haToggleButton')}
  5846. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  5847. onConfirm={() => {
  5848. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  5849. setHaToggleConfirm(null);
  5850. }}
  5851. onCancel={() => setHaToggleConfirm(null)}
  5852. />
  5853. )}
  5854. {/* Stop Print Confirmation */}
  5855. {showStopConfirm && (
  5856. <ConfirmModal
  5857. title={t('printers.confirm.stopTitle')}
  5858. message={t('printers.confirm.stopMessage', { name: printer.name })}
  5859. confirmText={t('printers.confirm.stopButton')}
  5860. variant="danger"
  5861. onConfirm={() => {
  5862. stopPrintMutation.mutate();
  5863. setShowStopConfirm(false);
  5864. }}
  5865. onCancel={() => setShowStopConfirm(false)}
  5866. />
  5867. )}
  5868. {/* Pause Print Confirmation */}
  5869. {showPauseConfirm && (
  5870. <ConfirmModal
  5871. title={t('printers.confirm.pauseTitle')}
  5872. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  5873. confirmText={t('printers.confirm.pauseButton')}
  5874. variant="default"
  5875. onConfirm={() => {
  5876. pausePrintMutation.mutate();
  5877. setShowPauseConfirm(false);
  5878. }}
  5879. onCancel={() => setShowPauseConfirm(false)}
  5880. />
  5881. )}
  5882. {/* Resume Print Confirmation */}
  5883. {showResumeConfirm && (
  5884. <ConfirmModal
  5885. title={t('printers.confirm.resumeTitle')}
  5886. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  5887. confirmText={t('printers.confirm.resumeButton')}
  5888. variant="default"
  5889. onConfirm={() => {
  5890. resumePrintMutation.mutate();
  5891. setShowResumeConfirm(false);
  5892. }}
  5893. onCancel={() => setShowResumeConfirm(false)}
  5894. />
  5895. )}
  5896. {/* Skip Objects Modal */}
  5897. <SkipObjectsModal
  5898. printerId={printer.id}
  5899. isOpen={showSkipObjectsModal}
  5900. onClose={() => setShowSkipObjectsModal(false)}
  5901. />
  5902. {/* HMS Error Modal */}
  5903. {showHMSModal && (
  5904. <HMSErrorModal
  5905. printerName={printer.name}
  5906. errors={status?.hms_errors || []}
  5907. onClose={() => setShowHMSModal(false)}
  5908. printerId={printer.id}
  5909. hasPermission={hasPermission}
  5910. />
  5911. )}
  5912. {/* AMS Filament Backup status / control modal (#1762) */}
  5913. {amsBackupModalOpen && status && (
  5914. <AmsBackupModal
  5915. isOpen={amsBackupModalOpen}
  5916. state={status.ams_filament_backup}
  5917. amsUnits={status.ams}
  5918. amsExtruderMap={status.ams_extruder_map}
  5919. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  5920. canToggle={hasPermission('printers:control')}
  5921. pending={setAmsBackupMutation.isPending}
  5922. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  5923. onClose={() => setAmsBackupModalOpen(false)}
  5924. />
  5925. )}
  5926. {/* AMS History Modal */}
  5927. {amsHistoryModal && (
  5928. <AMSHistoryModal
  5929. isOpen={!!amsHistoryModal}
  5930. onClose={() => setAmsHistoryModal(null)}
  5931. printerId={printer.id}
  5932. printerName={printer.name}
  5933. amsId={amsHistoryModal.amsId}
  5934. amsLabel={amsHistoryModal.amsLabel}
  5935. initialMode={amsHistoryModal.mode}
  5936. thresholds={amsThresholds}
  5937. />
  5938. )}
  5939. {/* Heater History Modal (nozzle / bed / chamber) */}
  5940. {heaterHistoryModal && (
  5941. <HeaterHistoryModal
  5942. isOpen={!!heaterHistoryModal}
  5943. onClose={() => setHeaterHistoryModal(null)}
  5944. printerId={printer.id}
  5945. printerName={printer.name}
  5946. initialKind={heaterHistoryModal.initialKind}
  5947. availableKinds={heaterHistoryModal.availableKinds}
  5948. />
  5949. )}
  5950. {/* Link Spool Modal */}
  5951. {linkSpoolModal && (
  5952. <LinkSpoolModal
  5953. isOpen={!!linkSpoolModal}
  5954. onClose={() => setLinkSpoolModal(null)}
  5955. tagUid={linkSpoolModal.tagUid}
  5956. trayUuid={linkSpoolModal.trayUuid}
  5957. printerId={linkSpoolModal.printerId}
  5958. amsId={linkSpoolModal.amsId}
  5959. trayId={linkSpoolModal.trayId}
  5960. />
  5961. )}
  5962. {/* Assign Spool Modal */}
  5963. {assignSpoolModal && (
  5964. <AssignSpoolModal
  5965. isOpen={!!assignSpoolModal}
  5966. onClose={() => setAssignSpoolModal(null)}
  5967. printerId={assignSpoolModal.printerId}
  5968. amsId={assignSpoolModal.amsId}
  5969. trayId={assignSpoolModal.trayId}
  5970. trayInfo={assignSpoolModal.trayInfo}
  5971. spoolmanEnabled={!!spoolmanEnabled}
  5972. />
  5973. )}
  5974. {/* Configure AMS Slot Modal */}
  5975. {configureSlotModal && (
  5976. <ConfigureAmsSlotModal
  5977. isOpen={!!configureSlotModal}
  5978. onClose={() => setConfigureSlotModal(null)}
  5979. printerId={printer.id}
  5980. slotInfo={configureSlotModal}
  5981. printerModel={mapModelCode(printer.model) || undefined}
  5982. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  5983. onSuccess={() => {
  5984. // Refresh slot presets to show updated profile name
  5985. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  5986. // Printer status will update automatically via WebSocket when AMS data changes
  5987. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  5988. }}
  5989. />
  5990. )}
  5991. {/* Edit Printer Modal */}
  5992. {showEditModal && (
  5993. <EditPrinterModal
  5994. printer={printer}
  5995. onClose={() => setShowEditModal(false)}
  5996. />
  5997. )}
  5998. {/* Firmware Update Modal */}
  5999. {showFirmwareModal && firmwareInfo && (
  6000. <FirmwareUpdateModal
  6001. printer={printer}
  6002. firmwareInfo={firmwareInfo}
  6003. onClose={() => setShowFirmwareModal(false)}
  6004. />
  6005. )}
  6006. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6007. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6008. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6009. const sliderMin = 35;
  6010. const sliderMax = maxTemp + 10;
  6011. return (
  6012. <>
  6013. {/* Backdrop */}
  6014. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  6015. {/* Popover */}
  6016. <div
  6017. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6018. style={{
  6019. top: dryingPopoverPos.top,
  6020. left: dryingPopoverPos.left,
  6021. // Cap to the space between the popover's top and the bottom
  6022. // viewport margin (8px, matching computePopoverPosition's
  6023. // margin). When the popover is taller than that space — short
  6024. // viewport, landscape phone, zoomed-in — the body scrolls and
  6025. // the footer stays pinned, so the Start button is always
  6026. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6027. // Safari's bottom toolbar overlay doesn't clip the footer
  6028. // (#1669, iPhone 17 Safari).
  6029. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6030. }}
  6031. onClick={e => e.stopPropagation()}
  6032. >
  6033. {/* Header */}
  6034. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6035. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6036. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6037. </div>
  6038. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6039. {/* Body */}
  6040. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6041. {/* Filament type select */}
  6042. <div>
  6043. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6044. <ToolbarDropdown
  6045. value={dryingFilament}
  6046. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6047. onChange={fil => {
  6048. setDryingFilament(fil);
  6049. const preset = dryingPresets[fil];
  6050. if (preset) {
  6051. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6052. setDryingTemp(preset[key]);
  6053. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6054. }
  6055. }}
  6056. fullWidth
  6057. />
  6058. </div>
  6059. {/* Temperature */}
  6060. <div>
  6061. <div className="flex items-center justify-between mb-1">
  6062. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6063. <div className="flex items-center gap-1">
  6064. <input
  6065. type="number"
  6066. min={45}
  6067. max={maxTemp}
  6068. value={dryingTemp}
  6069. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6070. 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"
  6071. />
  6072. <span className="text-[10px] text-bambu-gray">°C</span>
  6073. </div>
  6074. </div>
  6075. <input
  6076. type="range"
  6077. min={sliderMin}
  6078. max={sliderMax}
  6079. value={dryingTemp}
  6080. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6081. className="w-full h-1 accent-bambu-green cursor-pointer"
  6082. />
  6083. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6084. <span>45°C</span>
  6085. <span>{maxTemp}°C</span>
  6086. </div>
  6087. </div>
  6088. {/* Duration */}
  6089. <div>
  6090. <div className="flex items-center justify-between mb-1">
  6091. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6092. <div className="flex items-center gap-1">
  6093. <input
  6094. type="number"
  6095. min={1}
  6096. max={24}
  6097. value={dryingDuration}
  6098. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6099. 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"
  6100. />
  6101. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6102. </div>
  6103. </div>
  6104. <input
  6105. type="range"
  6106. min={1}
  6107. max={24}
  6108. value={dryingDuration}
  6109. onChange={e => setDryingDuration(Number(e.target.value))}
  6110. className="w-full h-1 accent-bambu-green cursor-pointer"
  6111. />
  6112. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6113. <span>1h</span>
  6114. <span>24h</span>
  6115. </div>
  6116. </div>
  6117. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6118. filament threaded out into the feed tube. The whole AMS
  6119. rotates as one mechanism (all 4 spools turn together), so a
  6120. single loaded slot locks the entire unit. Bambu per-tray
  6121. `state`: 9 = empty, 10 = spool present but not loaded
  6122. (rotation possible), 11 = loaded into tube (rotation impossible).
  6123. Catches both mid-print (active feed) AND idle-with-threaded-
  6124. filament — the H2D's post-print state leaves filament in the
  6125. tube but tray_now resets to 255, which a tray_now-only check
  6126. would silently miss. */}
  6127. {(() => {
  6128. const targetAms = dryingPopoverAmsId !== null
  6129. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6130. : undefined;
  6131. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6132. tray => tray.state === 11,
  6133. );
  6134. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6135. return (
  6136. <button
  6137. type="button"
  6138. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6139. aria-pressed={rotateChecked}
  6140. disabled={trayLoadedInThisAms}
  6141. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6142. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6143. rotateChecked
  6144. ? 'bg-bambu-green border-bambu-green text-white'
  6145. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6146. }`}
  6147. >
  6148. {t('printers.drying.rotateTray')}
  6149. </button>
  6150. );
  6151. })()}
  6152. </div>
  6153. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6154. {/* Footer */}
  6155. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6156. <button
  6157. onClick={() => {
  6158. if (dryingPopoverAmsId !== null) {
  6159. // Clamp rotateTray off when any tray in this AMS is loaded into
  6160. // the tube — the rotate UI is disabled there, but the state may
  6161. // linger as `true` from a previous AMS, or a print may have
  6162. // started while the popover was open. Without this clamp the
  6163. // Start payload would carry rotate_tray=true and firmware would
  6164. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  6165. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  6166. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6167. tray => tray.state === 11,
  6168. );
  6169. startDryingMutation.mutate({
  6170. amsId: dryingPopoverAmsId,
  6171. temp: dryingTemp,
  6172. duration: dryingDuration,
  6173. filament: dryingFilament,
  6174. rotateTray: dryingRotateTray && !trayLoadedInThisAms,
  6175. });
  6176. }
  6177. }}
  6178. disabled={startDryingMutation.isPending}
  6179. data-testid="drying-start-confirm"
  6180. 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"
  6181. >
  6182. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6183. </button>
  6184. </div>
  6185. </div>
  6186. </>
  6187. );
  6188. })()}
  6189. </Card>
  6190. );
  6191. }
  6192. export function AddPrinterModal({
  6193. onClose,
  6194. onAdd,
  6195. existingSerials,
  6196. }: {
  6197. onClose: () => void;
  6198. onAdd: (data: PrinterCreate) => void;
  6199. existingSerials: string[];
  6200. }) {
  6201. const { t } = useTranslation();
  6202. const [form, setForm] = useState<PrinterCreate>({
  6203. name: '',
  6204. serial_number: '',
  6205. ip_address: '',
  6206. access_code: '',
  6207. model: '',
  6208. location: '',
  6209. auto_archive: true,
  6210. });
  6211. // Discovery state
  6212. const [discovering, setDiscovering] = useState(false);
  6213. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6214. const [discoveryError, setDiscoveryError] = useState('');
  6215. const [hasScanned, setHasScanned] = useState(false);
  6216. const [isDocker, setIsDocker] = useState(false);
  6217. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6218. const [subnet, setSubnet] = useState('');
  6219. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6220. // text input so users can scan a subnet Bambuddy isn't directly on
  6221. // (printer behind a router on a different L3 segment — SSDP multicast
  6222. // won't cross that boundary, only an active unicast scan will). #1564
  6223. const [customSubnet, setCustomSubnet] = useState('');
  6224. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6225. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6226. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6227. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6228. // (not block) when checks fail, so the user doesn't add a printer that
  6229. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6230. // failed result awaiting an explicit "save anyway".
  6231. const [checkingSave, setCheckingSave] = useState(false);
  6232. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6233. // Fetch discovery info on mount + restore the last custom CIDR the user
  6234. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6235. // time they open this modal).
  6236. useEffect(() => {
  6237. discoveryApi.getInfo().then(info => {
  6238. setIsDocker(info.is_docker);
  6239. if (info.subnets.length > 0) {
  6240. setDetectedSubnets(info.subnets);
  6241. setSubnet(info.subnets[0]);
  6242. }
  6243. }).catch(() => {
  6244. // Ignore errors, assume not Docker
  6245. });
  6246. try {
  6247. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6248. if (saved) setCustomSubnet(saved);
  6249. } catch {
  6250. // localStorage unavailable (private mode, quota); recall is opportunistic
  6251. }
  6252. }, []);
  6253. // Filter out already-added printers
  6254. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6255. const handleAddSubmit = async (e: React.FormEvent) => {
  6256. e.preventDefault();
  6257. setCheckingSave(true);
  6258. try {
  6259. const result = await api.diagnoseConnection({
  6260. ip_address: form.ip_address.trim(),
  6261. serial_number: form.serial_number.trim() || undefined,
  6262. access_code: form.access_code || undefined,
  6263. });
  6264. if (result.checks.some((c) => c.status === 'fail')) {
  6265. setSaveWarning(result);
  6266. return;
  6267. }
  6268. } catch {
  6269. // Diagnostic infrastructure failed — never block the save on it.
  6270. } finally {
  6271. setCheckingSave(false);
  6272. }
  6273. onAdd(form);
  6274. };
  6275. const startDiscovery = async () => {
  6276. setDiscoveryError('');
  6277. setDiscovered([]);
  6278. setDiscovering(true);
  6279. setHasScanned(false);
  6280. setScanProgress({ scanned: 0, total: 0 });
  6281. // Native installs fall back to subnet scanning when the user picks
  6282. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6283. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6284. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6285. const wantsSubnetScan = isDocker || useCustomSubnet;
  6286. if (wantsSubnetScan && useCustomSubnet) {
  6287. try {
  6288. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6289. } catch {
  6290. // localStorage write best-effort; user just retypes next time
  6291. }
  6292. }
  6293. try {
  6294. if (wantsSubnetScan) {
  6295. await discoveryApi.startSubnetScan(scanCidr);
  6296. // Poll for scan status and results
  6297. const pollInterval = setInterval(async () => {
  6298. try {
  6299. const status = await discoveryApi.getScanStatus();
  6300. setScanProgress({ scanned: status.scanned, total: status.total });
  6301. const printers = await discoveryApi.getDiscoveredPrinters();
  6302. setDiscovered(printers);
  6303. if (!status.running) {
  6304. clearInterval(pollInterval);
  6305. setDiscovering(false);
  6306. setHasScanned(true);
  6307. }
  6308. } catch (e) {
  6309. console.error('Failed to get scan status:', e);
  6310. }
  6311. }, 500);
  6312. } else {
  6313. // Use SSDP discovery for native installs
  6314. await discoveryApi.startDiscovery(10);
  6315. // Poll for discovered printers every second
  6316. const pollInterval = setInterval(async () => {
  6317. try {
  6318. const printers = await discoveryApi.getDiscoveredPrinters();
  6319. setDiscovered(printers);
  6320. } catch (e) {
  6321. console.error('Failed to get discovered printers:', e);
  6322. }
  6323. }, 1000);
  6324. // Stop after 10 seconds
  6325. setTimeout(async () => {
  6326. clearInterval(pollInterval);
  6327. try {
  6328. await discoveryApi.stopDiscovery();
  6329. } catch {
  6330. // Ignore stop errors
  6331. }
  6332. setDiscovering(false);
  6333. setHasScanned(true);
  6334. // Final fetch
  6335. try {
  6336. const printers = await discoveryApi.getDiscoveredPrinters();
  6337. setDiscovered(printers);
  6338. } catch (e) {
  6339. console.error('Failed to get final discovered printers:', e);
  6340. }
  6341. }, 10000);
  6342. }
  6343. } catch (e) {
  6344. console.error('Failed to start discovery:', e);
  6345. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6346. setDiscovering(false);
  6347. setHasScanned(true);
  6348. }
  6349. };
  6350. // Reuse module-level mapModelCode
  6351. const selectPrinter = (printer: DiscoveredPrinter) => {
  6352. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6353. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6354. setForm({
  6355. ...form,
  6356. name: printer.name || '',
  6357. serial_number: serialNumber,
  6358. ip_address: printer.ip_address,
  6359. model: mapModelCode(printer.model),
  6360. });
  6361. // Clear discovery results after selection
  6362. setDiscovered([]);
  6363. };
  6364. // Cleanup discovery on unmount
  6365. useEffect(() => {
  6366. return () => {
  6367. discoveryApi.stopDiscovery().catch(() => {});
  6368. discoveryApi.stopSubnetScan().catch(() => {});
  6369. };
  6370. }, []);
  6371. // Close on Escape key
  6372. useEffect(() => {
  6373. const handleKeyDown = (e: KeyboardEvent) => {
  6374. if (e.key === 'Escape') onClose();
  6375. };
  6376. window.addEventListener('keydown', handleKeyDown);
  6377. return () => window.removeEventListener('keydown', handleKeyDown);
  6378. }, [onClose]);
  6379. return (
  6380. <>
  6381. <div
  6382. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6383. onClick={onClose}
  6384. >
  6385. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6386. <CardContent>
  6387. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6388. {/* Discovery Section */}
  6389. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6390. {/* Subnet picker — always visible. The dropdown lists detected
  6391. interface subnets and a "Custom..." sentinel that reveals
  6392. a CIDR text input for printers on a different L3 segment
  6393. (router, VLAN, etc.). #1564 */}
  6394. <div className="mb-3">
  6395. <label className="block text-sm text-bambu-gray mb-1">
  6396. {t('printers.discovery.subnetToScan')}
  6397. </label>
  6398. {detectedSubnets.length > 0 ? (
  6399. <select
  6400. 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"
  6401. value={useCustomSubnet ? '__custom__' : subnet}
  6402. onChange={(e) => {
  6403. if (e.target.value === '__custom__') {
  6404. setUseCustomSubnet(true);
  6405. } else {
  6406. setUseCustomSubnet(false);
  6407. setSubnet(e.target.value);
  6408. }
  6409. }}
  6410. disabled={discovering}
  6411. >
  6412. {detectedSubnets.map(s => (
  6413. <option key={s} value={s}>{s}</option>
  6414. ))}
  6415. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6416. </select>
  6417. ) : (
  6418. <input
  6419. type="text"
  6420. 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"
  6421. value={subnet}
  6422. onChange={(e) => setSubnet(e.target.value)}
  6423. placeholder="192.168.1.0/24"
  6424. disabled={discovering}
  6425. />
  6426. )}
  6427. {useCustomSubnet && (
  6428. <input
  6429. type="text"
  6430. aria-label={t('printers.discovery.customSubnetLabel')}
  6431. 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"
  6432. value={customSubnet}
  6433. onChange={(e) => setCustomSubnet(e.target.value)}
  6434. placeholder="10.1.1.0/24"
  6435. disabled={discovering}
  6436. />
  6437. )}
  6438. <p className="mt-1 text-xs text-bambu-gray">
  6439. {isDocker
  6440. ? t('printers.discovery.dockerNote')
  6441. : t('printers.discovery.customSubnetNote')}
  6442. </p>
  6443. </div>
  6444. <Button
  6445. type="button"
  6446. variant="secondary"
  6447. onClick={startDiscovery}
  6448. disabled={discovering}
  6449. className="w-full"
  6450. >
  6451. {discovering ? (
  6452. <>
  6453. <Loader2 className="w-4 h-4 animate-spin" />
  6454. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6455. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6456. : t('printers.discovery.scanning')}
  6457. </>
  6458. ) : (
  6459. <>
  6460. <Search className="w-4 h-4" />
  6461. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6462. </>
  6463. )}
  6464. </Button>
  6465. {discoveryError && (
  6466. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  6467. )}
  6468. {newPrinters.length > 0 && (
  6469. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6470. {newPrinters.map((printer) => (
  6471. <div
  6472. key={printer.serial}
  6473. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6474. onClick={() => selectPrinter(printer)}
  6475. >
  6476. <div className="min-w-0 flex-1">
  6477. <p className="font-medium text-white text-sm truncate">
  6478. {printer.name || printer.serial}
  6479. </p>
  6480. <p className="text-xs text-bambu-gray truncate">
  6481. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6482. {printer.serial.startsWith('unknown-') && (
  6483. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6484. )}
  6485. </p>
  6486. </div>
  6487. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6488. </div>
  6489. ))}
  6490. </div>
  6491. )}
  6492. {discovering && (
  6493. <p className="mt-2 text-sm text-bambu-gray text-center">
  6494. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6495. </p>
  6496. )}
  6497. {hasScanned && !discovering && discovered.length === 0 && (
  6498. <p className="mt-2 text-sm text-bambu-gray text-center">
  6499. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6500. </p>
  6501. )}
  6502. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6503. <p className="mt-2 text-sm text-bambu-gray text-center">
  6504. {t('printers.discovery.allConfigured')}
  6505. </p>
  6506. )}
  6507. </div>
  6508. <form onSubmit={handleAddSubmit} className="space-y-4">
  6509. <div>
  6510. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6511. <input
  6512. type="text"
  6513. required
  6514. 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"
  6515. value={form.name}
  6516. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6517. placeholder={t('printers.modal.myPrinter')}
  6518. />
  6519. </div>
  6520. <div>
  6521. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6522. <input
  6523. type="text"
  6524. required
  6525. 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])?)*)"
  6526. 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"
  6527. value={form.ip_address}
  6528. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6529. placeholder="192.168.1.100 or printer.local"
  6530. />
  6531. </div>
  6532. <div>
  6533. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6534. <input
  6535. type="text"
  6536. required
  6537. 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"
  6538. value={form.serial_number}
  6539. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6540. placeholder="01P00A000000000"
  6541. />
  6542. </div>
  6543. <div>
  6544. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6545. <input
  6546. type="password"
  6547. required
  6548. 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"
  6549. value={form.access_code}
  6550. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6551. placeholder={t('printers.modal.fromPrinterSettings')}
  6552. />
  6553. </div>
  6554. <div>
  6555. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6556. <select
  6557. 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"
  6558. value={form.model || ''}
  6559. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6560. >
  6561. <option value="">{t('printers.modal.selectModel')}</option>
  6562. <optgroup label="A1 Series">
  6563. <option value="A1">A1</option>
  6564. <option value="A1 Mini">A1 Mini</option>
  6565. </optgroup>
  6566. <optgroup label="A2 Series">
  6567. <option value="A2L">A2L</option>
  6568. </optgroup>
  6569. <optgroup label="H2 Series">
  6570. <option value="H2C">H2C</option>
  6571. <option value="H2D">H2D</option>
  6572. <option value="H2D Pro">H2D Pro</option>
  6573. <option value="H2S">H2S</option>
  6574. </optgroup>
  6575. <optgroup label="P Series">
  6576. <option value="P1P">P1P</option>
  6577. <option value="P1S">P1S</option>
  6578. <option value="P2S">P2S</option>
  6579. </optgroup>
  6580. <optgroup label="X1 Series">
  6581. <option value="X1">X1</option>
  6582. <option value="X1C">X1 Carbon</option>
  6583. <option value="X1E">X1E</option>
  6584. </optgroup>
  6585. <optgroup label="X2 Series">
  6586. <option value="X2D">X2D</option>
  6587. </optgroup>
  6588. </select>
  6589. </div>
  6590. <div>
  6591. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6592. <input
  6593. type="text"
  6594. 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"
  6595. value={form.location || ''}
  6596. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6597. placeholder={t('printers.modal.locationPlaceholder')}
  6598. />
  6599. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6600. </div>
  6601. <div className="flex items-center gap-2">
  6602. <input
  6603. type="checkbox"
  6604. id="auto_archive"
  6605. checked={form.auto_archive}
  6606. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6607. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6608. />
  6609. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6610. {t('printers.modal.autoArchiveLabel')}
  6611. </label>
  6612. </div>
  6613. <button
  6614. type="button"
  6615. onClick={() => setShowDiagnostic(true)}
  6616. disabled={!form.ip_address.trim()}
  6617. 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"
  6618. >
  6619. <Stethoscope className="w-4 h-4" />
  6620. {t('diagnostic.runButton')}
  6621. </button>
  6622. {saveWarning ? (
  6623. <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">
  6624. <div className="flex items-start gap-2">
  6625. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  6626. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  6627. </div>
  6628. <DiagnosticChecklist result={saveWarning} />
  6629. <div className="flex gap-3">
  6630. <Button
  6631. type="button"
  6632. variant="secondary"
  6633. onClick={() => setSaveWarning(null)}
  6634. className="flex-1"
  6635. >
  6636. {t('printers.addPreflight.back')}
  6637. </Button>
  6638. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6639. {t('printers.addPreflight.saveAnyway')}
  6640. </Button>
  6641. </div>
  6642. </div>
  6643. ) : (
  6644. <div className="flex gap-3 pt-2">
  6645. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6646. {t('common.cancel')}
  6647. </Button>
  6648. <Button type="submit" disabled={checkingSave} className="flex-1">
  6649. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6650. </Button>
  6651. </div>
  6652. )}
  6653. </form>
  6654. </CardContent>
  6655. </Card>
  6656. </div>
  6657. {showDiagnostic && (
  6658. <ConnectionDiagnosticModal
  6659. connection={{
  6660. ip_address: form.ip_address.trim(),
  6661. serial_number: form.serial_number.trim() || undefined,
  6662. access_code: form.access_code || undefined,
  6663. }}
  6664. printerName={form.name || null}
  6665. onClose={() => setShowDiagnostic(false)}
  6666. />
  6667. )}
  6668. </>
  6669. );
  6670. }
  6671. function FirmwareUpdateModal({
  6672. printer,
  6673. firmwareInfo,
  6674. onClose,
  6675. }: {
  6676. printer: Printer;
  6677. firmwareInfo: FirmwareUpdateInfo;
  6678. onClose: () => void;
  6679. }) {
  6680. const { t } = useTranslation();
  6681. const queryClient = useQueryClient();
  6682. const { showToast } = useToast();
  6683. const { hasPermission } = useAuth();
  6684. const canUpdate = hasPermission('firmware:update');
  6685. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6686. const [isUploading, setIsUploading] = useState(false);
  6687. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6688. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6689. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6690. );
  6691. // Prepare check query — runs when a version is selected and user can update
  6692. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6693. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6694. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6695. staleTime: 30000,
  6696. enabled: !!selectedVersion && canUpdate && !isUploading,
  6697. });
  6698. // Start upload mutation
  6699. const uploadMutation = useMutation({
  6700. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6701. onSuccess: () => {
  6702. setIsUploading(true);
  6703. // Start polling for status
  6704. const interval = setInterval(async () => {
  6705. try {
  6706. const status = await firmwareApi.getUploadStatus(printer.id);
  6707. setUploadStatus(status);
  6708. if (status.status === 'complete' || status.status === 'error') {
  6709. clearInterval(interval);
  6710. setPollInterval(null);
  6711. setIsUploading(false);
  6712. if (status.status === 'complete') {
  6713. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6714. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6715. }
  6716. }
  6717. } catch {
  6718. // Ignore errors during polling
  6719. }
  6720. }, 2000);
  6721. setPollInterval(interval);
  6722. },
  6723. onError: (error: Error) => {
  6724. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6725. setIsUploading(false);
  6726. },
  6727. });
  6728. // Cleanup on unmount
  6729. useEffect(() => {
  6730. return () => {
  6731. if (pollInterval) clearInterval(pollInterval);
  6732. };
  6733. }, [pollInterval]);
  6734. const handleStartUpload = () => {
  6735. setUploadStatus(null);
  6736. uploadMutation.mutate();
  6737. };
  6738. return (
  6739. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6740. <Card className="w-full max-w-md mx-4">
  6741. <CardContent>
  6742. <div className="flex items-start gap-3 mb-4">
  6743. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6744. {firmwareInfo.update_available
  6745. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  6746. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6747. </div>
  6748. <div className="flex-1">
  6749. <h3 className="text-lg font-semibold text-white">
  6750. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6751. </h3>
  6752. <p className="text-sm text-bambu-gray mt-1">
  6753. {printer.name}
  6754. </p>
  6755. </div>
  6756. </div>
  6757. {/* Version Info */}
  6758. {(() => {
  6759. const selectedEntry = selectedVersion
  6760. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6761. : null;
  6762. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6763. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6764. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6765. return (
  6766. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6767. <div className="flex justify-between items-center text-sm">
  6768. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6769. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6770. {firmwareInfo.current_version || t('common.unknown')}
  6771. </span>
  6772. </div>
  6773. {showSecondLine && (
  6774. <div className="flex justify-between items-center text-sm mt-1">
  6775. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  6776. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  6777. </div>
  6778. )}
  6779. {displayNotes && (
  6780. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  6781. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  6782. {t('printers.firmwareModal.releaseNotes')}
  6783. </summary>
  6784. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  6785. {displayNotes}
  6786. </div>
  6787. </details>
  6788. )}
  6789. </div>
  6790. );
  6791. })()}
  6792. {/* Available versions list */}
  6793. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  6794. <div className="mb-4">
  6795. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  6796. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  6797. {firmwareInfo.available_versions.map((v) => {
  6798. const isCurrent = firmwareInfo.current_version === v.version;
  6799. const isSelected = selectedVersion === v.version;
  6800. const cmp = firmwareInfo.current_version
  6801. ? compareFwVersions(v.version, firmwareInfo.current_version)
  6802. : 0;
  6803. const relLabel = isCurrent
  6804. ? t('printers.firmwareModal.currentBadge')
  6805. : cmp > 0
  6806. ? t('printers.firmwareModal.newerBadge')
  6807. : t('printers.firmwareModal.olderBadge');
  6808. const relClass = isCurrent
  6809. ? 'text-bambu-gray'
  6810. : cmp > 0
  6811. ? 'text-orange-700 dark:text-orange-400'
  6812. : 'text-blue-700 dark:text-blue-400';
  6813. return (
  6814. <button
  6815. key={v.version}
  6816. type="button"
  6817. disabled={!v.file_available || !canUpdate || isCurrent}
  6818. onClick={() => setSelectedVersion(v.version)}
  6819. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  6820. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  6821. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  6822. >
  6823. <div className="flex items-center gap-2 min-w-0">
  6824. <span className="font-mono text-white">{v.version}</span>
  6825. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  6826. </div>
  6827. <span className={`text-xs px-2 py-0.5 rounded-full ${
  6828. isCurrent
  6829. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  6830. : v.file_available
  6831. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  6832. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  6833. }`}>
  6834. {isCurrent
  6835. ? t('printers.firmwareModal.installed')
  6836. : v.file_available
  6837. ? t('printers.firmwareModal.usable')
  6838. : t('printers.firmwareModal.unavailable')}
  6839. </span>
  6840. </button>
  6841. );
  6842. })}
  6843. </div>
  6844. </div>
  6845. )}
  6846. {/* Status / Progress (only when a version is selected) */}
  6847. {!selectedVersion ? null : isPreparing ? (
  6848. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  6849. <Loader2 className="w-4 h-4 animate-spin" />
  6850. {t('printers.firmwareModal.checkingPrereqs')}
  6851. </div>
  6852. ) : prepareInfo && !isUploading && !uploadStatus ? (
  6853. <div className="mb-4">
  6854. {prepareInfo.can_proceed ? (
  6855. <div className="flex items-center gap-2 text-bambu-green text-sm">
  6856. <Box className="w-4 h-4" />
  6857. {t('printers.firmwareModal.sdCardReady')}
  6858. </div>
  6859. ) : (
  6860. <div className="space-y-1">
  6861. {prepareInfo.errors.map((error, i) => (
  6862. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  6863. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  6864. {error}
  6865. </div>
  6866. ))}
  6867. </div>
  6868. )}
  6869. </div>
  6870. ) : null}
  6871. {/* Upload Progress */}
  6872. {(isUploading || uploadStatus) && uploadStatus && (
  6873. <div className="mb-4">
  6874. <div className="flex items-center justify-between text-sm mb-1">
  6875. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  6876. <span className="text-white">{uploadStatus.progress}%</span>
  6877. </div>
  6878. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  6879. <div
  6880. className={`h-2 rounded-full transition-all ${
  6881. uploadStatus.status === 'error' ? 'bg-status-error' :
  6882. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  6883. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  6884. style={{ width: `${uploadStatus.progress}%` }}
  6885. />
  6886. </div>
  6887. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  6888. {uploadStatus.error && (
  6889. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  6890. )}
  6891. </div>
  6892. )}
  6893. {/* Success Message */}
  6894. {uploadStatus?.status === 'complete' && (
  6895. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  6896. <p className="text-sm text-bambu-green font-medium mb-2">
  6897. {t('printers.firmwareModal.uploadedSuccess')}
  6898. </p>
  6899. <p className="text-xs text-bambu-gray">
  6900. {t('printers.firmwareModal.applyInstructions')}
  6901. </p>
  6902. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  6903. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  6904. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  6905. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  6906. <li>{t('printers.firmwareModal.step4')}</li>
  6907. </ol>
  6908. </div>
  6909. )}
  6910. {/* Buttons */}
  6911. <div className="flex gap-2 justify-end">
  6912. <Button variant="secondary" onClick={onClose}>
  6913. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  6914. </Button>
  6915. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  6916. <Button
  6917. onClick={handleStartUpload}
  6918. disabled={uploadMutation.isPending}
  6919. >
  6920. {uploadMutation.isPending ? (
  6921. <>
  6922. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  6923. {t('printers.firmwareModal.starting')}
  6924. </>
  6925. ) : (
  6926. <>
  6927. <Download className="w-4 h-4 mr-2" />
  6928. {t('printers.firmwareModal.uploadFirmware')}
  6929. </>
  6930. )}
  6931. </Button>
  6932. )}
  6933. </div>
  6934. </CardContent>
  6935. </Card>
  6936. </div>
  6937. );
  6938. }
  6939. function EditPrinterModal({
  6940. printer,
  6941. onClose,
  6942. }: {
  6943. printer: Printer;
  6944. onClose: () => void;
  6945. }) {
  6946. const { t } = useTranslation();
  6947. const queryClient = useQueryClient();
  6948. const { showToast } = useToast();
  6949. const [form, setForm] = useState({
  6950. name: printer.name,
  6951. ip_address: printer.ip_address,
  6952. access_code: '',
  6953. model: printer.model || '',
  6954. location: printer.location || '',
  6955. auto_archive: printer.auto_archive,
  6956. is_active: printer.is_active,
  6957. });
  6958. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  6959. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  6960. const [checkingSave, setCheckingSave] = useState(false);
  6961. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6962. const updateMutation = useMutation({
  6963. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  6964. onSuccess: () => {
  6965. queryClient.invalidateQueries({ queryKey: ['printers'] });
  6966. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6967. onClose();
  6968. },
  6969. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  6970. });
  6971. // Close on Escape key
  6972. useEffect(() => {
  6973. const handleKeyDown = (e: KeyboardEvent) => {
  6974. if (e.key === 'Escape') onClose();
  6975. };
  6976. window.addEventListener('keydown', handleKeyDown);
  6977. return () => window.removeEventListener('keydown', handleKeyDown);
  6978. }, [onClose]);
  6979. const doSave = () => {
  6980. const data: Partial<PrinterCreate> = {
  6981. name: form.name,
  6982. ip_address: form.ip_address,
  6983. model: form.model || undefined,
  6984. location: form.location || undefined,
  6985. auto_archive: form.auto_archive,
  6986. is_active: form.is_active,
  6987. };
  6988. // Only include access_code if it was changed
  6989. if (form.access_code) {
  6990. data.access_code = form.access_code;
  6991. }
  6992. updateMutation.mutate(data);
  6993. };
  6994. const handleSubmit = async (e: React.FormEvent) => {
  6995. e.preventDefault();
  6996. setCheckingSave(true);
  6997. try {
  6998. const result = await api.diagnoseConnection({
  6999. ip_address: form.ip_address.trim(),
  7000. serial_number: printer.serial_number,
  7001. access_code: form.access_code || undefined,
  7002. });
  7003. if (result.checks.some((c) => c.status === 'fail')) {
  7004. setSaveWarning(result);
  7005. return;
  7006. }
  7007. } catch {
  7008. // Diagnostic infrastructure failed — never block the save on it.
  7009. } finally {
  7010. setCheckingSave(false);
  7011. }
  7012. doSave();
  7013. };
  7014. return (
  7015. <div
  7016. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7017. onClick={onClose}
  7018. >
  7019. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7020. <CardContent>
  7021. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7022. <form onSubmit={handleSubmit} className="space-y-4">
  7023. <div>
  7024. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7025. <input
  7026. type="text"
  7027. required
  7028. 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"
  7029. value={form.name}
  7030. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7031. placeholder={t('printers.modal.myPrinter')}
  7032. />
  7033. </div>
  7034. <div>
  7035. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7036. <input
  7037. type="text"
  7038. required
  7039. 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])?)*)"
  7040. 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"
  7041. value={form.ip_address}
  7042. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7043. placeholder="192.168.1.100 or printer.local"
  7044. />
  7045. </div>
  7046. <div>
  7047. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7048. <input
  7049. type="text"
  7050. disabled
  7051. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7052. value={printer.serial_number}
  7053. />
  7054. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7055. </div>
  7056. <div>
  7057. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7058. <input
  7059. type="password"
  7060. 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"
  7061. value={form.access_code}
  7062. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7063. placeholder={t('printers.accessCodePlaceholder')}
  7064. />
  7065. </div>
  7066. <div>
  7067. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7068. <select
  7069. 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"
  7070. value={form.model}
  7071. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7072. >
  7073. <option value="">{t('printers.modal.selectModel')}</option>
  7074. <optgroup label="A1 Series">
  7075. <option value="A1">A1</option>
  7076. <option value="A1 Mini">A1 Mini</option>
  7077. </optgroup>
  7078. <optgroup label="A2 Series">
  7079. <option value="A2L">A2L</option>
  7080. </optgroup>
  7081. <optgroup label="H2 Series">
  7082. <option value="H2C">H2C</option>
  7083. <option value="H2D">H2D</option>
  7084. <option value="H2D Pro">H2D Pro</option>
  7085. <option value="H2S">H2S</option>
  7086. </optgroup>
  7087. <optgroup label="P Series">
  7088. <option value="P1P">P1P</option>
  7089. <option value="P1S">P1S</option>
  7090. <option value="P2S">P2S</option>
  7091. </optgroup>
  7092. <optgroup label="X1 Series">
  7093. <option value="X1">X1</option>
  7094. <option value="X1C">X1 Carbon</option>
  7095. <option value="X1E">X1E</option>
  7096. </optgroup>
  7097. <optgroup label="X2 Series">
  7098. <option value="X2D">X2D</option>
  7099. </optgroup>
  7100. </select>
  7101. </div>
  7102. <div>
  7103. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7104. <input
  7105. type="text"
  7106. 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"
  7107. value={form.location}
  7108. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7109. placeholder={t('printers.modal.locationPlaceholder')}
  7110. />
  7111. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7112. </div>
  7113. <div className="flex items-center gap-2">
  7114. <input
  7115. type="checkbox"
  7116. id="edit_auto_archive"
  7117. checked={form.auto_archive}
  7118. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7119. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7120. />
  7121. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7122. {t('printers.modal.autoArchiveLabel')}
  7123. </label>
  7124. </div>
  7125. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7126. is_active because the user-facing concept is "is this printer
  7127. in maintenance" not "is it active". */}
  7128. <div>
  7129. <div className="flex items-center gap-2">
  7130. <input
  7131. type="checkbox"
  7132. id="edit_maintenance_mode"
  7133. checked={!form.is_active}
  7134. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7135. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7136. />
  7137. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7138. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  7139. {t('printers.maintenance.editFieldLabel')}
  7140. </label>
  7141. </div>
  7142. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7143. {t('printers.maintenance.editFieldHelp')}
  7144. </p>
  7145. </div>
  7146. {saveWarning ? (
  7147. <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">
  7148. <div className="flex items-start gap-2">
  7149. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7150. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7151. </div>
  7152. <DiagnosticChecklist result={saveWarning} />
  7153. <div className="flex gap-3">
  7154. <Button
  7155. type="button"
  7156. variant="secondary"
  7157. onClick={() => setSaveWarning(null)}
  7158. className="flex-1"
  7159. >
  7160. {t('printers.addPreflight.back')}
  7161. </Button>
  7162. <Button
  7163. type="button"
  7164. onClick={doSave}
  7165. className="flex-1"
  7166. disabled={updateMutation.isPending}
  7167. >
  7168. {t('printers.addPreflight.saveAnyway')}
  7169. </Button>
  7170. </div>
  7171. </div>
  7172. ) : (
  7173. <div className="flex gap-3 pt-4">
  7174. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7175. {t('common.cancel')}
  7176. </Button>
  7177. <Button
  7178. type="submit"
  7179. className="flex-1"
  7180. disabled={updateMutation.isPending || checkingSave}
  7181. >
  7182. {checkingSave
  7183. ? t('printers.addPreflight.checking')
  7184. : updateMutation.isPending
  7185. ? t('common.saving')
  7186. : t('printers.modal.saveChanges')}
  7187. </Button>
  7188. </div>
  7189. )}
  7190. </form>
  7191. </CardContent>
  7192. </Card>
  7193. </div>
  7194. );
  7195. }
  7196. // Component to check if a printer is offline (for power dropdown)
  7197. function usePrinterOfflineStatus(printerId: number) {
  7198. const { data: status } = useQuery({
  7199. queryKey: ['printerStatus', printerId],
  7200. queryFn: () => api.getPrinterStatus(printerId),
  7201. refetchInterval: 30000,
  7202. });
  7203. return !status?.connected;
  7204. }
  7205. // Power dropdown item for an offline printer
  7206. function PowerDropdownItem({
  7207. printer,
  7208. plug,
  7209. onPowerOn,
  7210. isPowering,
  7211. }: {
  7212. printer: Printer;
  7213. plug: { id: number; name: string };
  7214. onPowerOn: (plugId: number) => void;
  7215. isPowering: boolean;
  7216. }) {
  7217. const isOffline = usePrinterOfflineStatus(printer.id);
  7218. // Fetch plug status
  7219. const { data: plugStatus } = useQuery({
  7220. queryKey: ['smartPlugStatus', plug.id],
  7221. queryFn: () => api.getSmartPlugStatus(plug.id),
  7222. refetchInterval: 10000,
  7223. });
  7224. // Only show if printer is offline
  7225. if (!isOffline) {
  7226. return null;
  7227. }
  7228. return (
  7229. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7230. <div className="flex items-center gap-2 min-w-0">
  7231. <span className="text-sm text-white truncate">{printer.name}</span>
  7232. {plugStatus && (
  7233. <span
  7234. className={`text-xs px-1.5 py-0.5 rounded ${
  7235. plugStatus.state === 'ON'
  7236. ? 'bg-bambu-green/20 text-bambu-green'
  7237. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  7238. }`}
  7239. >
  7240. {plugStatus.state || '?'}
  7241. </span>
  7242. )}
  7243. </div>
  7244. <button
  7245. onClick={() => onPowerOn(plug.id)}
  7246. disabled={isPowering || plugStatus?.state === 'ON'}
  7247. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7248. plugStatus?.state === 'ON'
  7249. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7250. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7251. }`}
  7252. >
  7253. <Power className="w-3 h-3" />
  7254. {isPowering ? '...' : 'On'}
  7255. </button>
  7256. </div>
  7257. );
  7258. }
  7259. export function PrintersPage() {
  7260. const { t } = useTranslation();
  7261. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7262. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7263. const accentButtonClass = {
  7264. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7265. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7266. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7267. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7268. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7269. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7270. }[activeAccent];
  7271. const [showAddModal, setShowAddModal] = useState(false);
  7272. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7273. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7274. });
  7275. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7276. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7277. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7278. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7279. });
  7280. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7281. return localStorage.getItem('printerSortAsc') !== 'false';
  7282. });
  7283. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7284. const [cardSize, setCardSize] = useState<number>(() => {
  7285. const saved = localStorage.getItem('printerCardSize');
  7286. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7287. });
  7288. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  7289. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  7290. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  7291. });
  7292. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  7293. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  7294. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  7295. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  7296. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  7297. });
  7298. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  7299. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  7300. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  7301. });
  7302. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  7303. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  7304. // Defaulting to 'full' because the cards already show this info — users who
  7305. // pick cam-wall view still want to glance the same details without flipping.
  7306. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  7307. const saved = localStorage.getItem('camWallStatusMode');
  7308. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  7309. });
  7310. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7311. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7312. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7313. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7314. requestAnimationFrame(() => {
  7315. requestAnimationFrame(() => {
  7316. const card = document.getElementById(`printer-card-${printerId}`);
  7317. if (!card) return;
  7318. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7319. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7320. window.scrollTo({
  7321. top: Math.max(0, top),
  7322. behavior: 'smooth',
  7323. });
  7324. });
  7325. });
  7326. }, []);
  7327. const openCompactCard = useCallback((printerId: number) => {
  7328. setCompactDrilldownPrinterId(printerId);
  7329. setCardSize(2);
  7330. localStorage.setItem('printerCardSize', '2');
  7331. scrollPrinterIntoView(printerId);
  7332. }, [scrollPrinterIntoView]);
  7333. const returnToCompactCards = useCallback(() => {
  7334. const printerId = compactDrilldownPrinterId;
  7335. setCompactDrilldownPrinterId(null);
  7336. setCardSize(1);
  7337. localStorage.setItem('printerCardSize', '1');
  7338. if (printerId != null) {
  7339. scrollPrinterIntoView(printerId);
  7340. }
  7341. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7342. const [search, setSearch] = useState('');
  7343. const [statusFilter, setStatusFilter] = useState<string>('all');
  7344. const [locationFilter, setLocationFilter] = useState<string>('all');
  7345. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7346. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7347. try {
  7348. const saved = localStorage.getItem('printerCollapsedSections');
  7349. return saved ? JSON.parse(saved) : {};
  7350. } catch { return {}; }
  7351. });
  7352. const queryClient = useQueryClient();
  7353. const { showToast } = useToast();
  7354. const { hasPermission } = useAuth();
  7355. // Embedded camera viewer state - supports multiple simultaneous viewers
  7356. // Persisted to localStorage so cameras reopen after navigation
  7357. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7358. // Initialize from localStorage if camera_view_mode is embedded
  7359. const saved = localStorage.getItem('openEmbeddedCameras');
  7360. if (saved) {
  7361. try {
  7362. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7363. return new Map(cameras.map(c => [c.id, c]));
  7364. } catch {
  7365. return new Map();
  7366. }
  7367. }
  7368. return new Map();
  7369. });
  7370. // Persist open cameras to localStorage when they change
  7371. useEffect(() => {
  7372. const cameras = Array.from(embeddedCameraPrinters.values());
  7373. if (cameras.length > 0) {
  7374. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7375. } else {
  7376. localStorage.removeItem('openEmbeddedCameras');
  7377. }
  7378. }, [embeddedCameraPrinters]);
  7379. const { data: printers, isLoading } = useQuery({
  7380. queryKey: ['printers'],
  7381. queryFn: api.getPrinters,
  7382. });
  7383. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7384. // so users with printers:read but no settings:read still get the values needed
  7385. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7386. const { data: settings } = useQuery({
  7387. queryKey: ['ui-preferences'],
  7388. queryFn: api.getUiPreferences,
  7389. });
  7390. // Parse user-configured temperature/fan presets once, with defensive fallback
  7391. // to built-in defaults on parse failure (validators on the backend already
  7392. // reject malformed writes, so this is just forward-compat).
  7393. const effectiveNozzleTempPresets = useMemo(
  7394. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7395. [settings?.nozzle_temp_presets],
  7396. );
  7397. const effectiveBedTempPresets = useMemo(
  7398. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7399. [settings?.bed_temp_presets],
  7400. );
  7401. const effectiveChamberTempPresets = useMemo(
  7402. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, 60),
  7403. [settings?.chamber_temp_presets],
  7404. );
  7405. const effectiveFanSpeedPresets = useMemo(
  7406. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7407. [settings?.fan_speed_presets],
  7408. );
  7409. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7410. const effectiveDryingPresets = useMemo(() => {
  7411. if (settings?.drying_presets) {
  7412. try {
  7413. const userPresets = JSON.parse(settings.drying_presets);
  7414. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7415. return { ...DRYING_PRESETS, ...userPresets };
  7416. }
  7417. } catch { /* ignore parse errors, use defaults */ }
  7418. }
  7419. return DRYING_PRESETS;
  7420. }, [settings?.drying_presets]);
  7421. // Close embedded cameras if mode changes to 'window'
  7422. useEffect(() => {
  7423. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7424. setEmbeddedCameraPrinters(new Map());
  7425. }
  7426. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7427. // Fetch all smart plugs to know which printers have them
  7428. const { data: smartPlugs } = useQuery({
  7429. queryKey: ['smart-plugs'],
  7430. queryFn: api.getSmartPlugs,
  7431. });
  7432. // Fetch maintenance overview for all printers to show badges
  7433. const { data: maintenanceOverview } = useQuery({
  7434. queryKey: ['maintenanceOverview'],
  7435. queryFn: api.getMaintenanceOverview,
  7436. staleTime: 60 * 1000, // 1 minute
  7437. });
  7438. // Fetch Spoolman status to enable link spool feature
  7439. const { data: spoolmanStatus } = useQuery({
  7440. queryKey: ['spoolman-status'],
  7441. queryFn: api.getSpoolmanStatus,
  7442. staleTime: 60 * 1000, // 1 minute
  7443. });
  7444. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7445. // Fetch Spoolman settings to get sync mode
  7446. const { data: spoolmanSettings } = useQuery({
  7447. queryKey: ['spoolman-settings'],
  7448. queryFn: api.getSpoolmanSettings,
  7449. enabled: !!spoolmanEnabled,
  7450. staleTime: 60 * 1000, // 1 minute
  7451. });
  7452. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7453. // Fetch unlinked spools to know if link button should be enabled
  7454. const { data: unlinkedSpools } = useQuery({
  7455. queryKey: ['unlinked-spools'],
  7456. queryFn: api.getUnlinkedSpools,
  7457. enabled: !!spoolmanEnabled,
  7458. staleTime: 30 * 1000, // 30 seconds
  7459. });
  7460. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7461. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7462. const { data: linkedSpoolsData } = useQuery({
  7463. queryKey: ['linked-spools'],
  7464. queryFn: api.getLinkedSpools,
  7465. enabled: !!spoolmanEnabled,
  7466. staleTime: 30 * 1000, // 30 seconds
  7467. });
  7468. const linkedSpools = linkedSpoolsData?.linked;
  7469. // Fetch spool assignments for inventory feature
  7470. const { data: spoolAssignments } = useQuery({
  7471. queryKey: ['spool-assignments'],
  7472. queryFn: () => api.getAssignments(),
  7473. enabled: hasPermission('inventory:view_assignments'),
  7474. staleTime: 30 * 1000,
  7475. });
  7476. const unassignMutation = useMutation({
  7477. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7478. api.unassignSpool(printerId, amsId, trayId),
  7479. onSuccess: () => {
  7480. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7481. },
  7482. });
  7483. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7484. queryKey: ['spoolman-inventory-spools'],
  7485. queryFn: () => api.getSpoolmanInventorySpools(false),
  7486. enabled: !!spoolmanEnabled,
  7487. staleTime: 30 * 1000,
  7488. });
  7489. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7490. queryKey: ['spoolman-slot-assignments'],
  7491. queryFn: () => api.getSpoolmanSlotAssignments(),
  7492. enabled: !!spoolmanEnabled,
  7493. staleTime: 30 * 1000,
  7494. });
  7495. const unassignSpoolmanMutation = useMutation({
  7496. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7497. onSuccess: () => {
  7498. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7499. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7500. },
  7501. });
  7502. // Helper to find assignment for a specific slot
  7503. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7504. return spoolAssignments?.find(
  7505. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7506. );
  7507. };
  7508. // Create a map of printer_id -> maintenance info for quick lookup
  7509. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7510. (acc, overview) => {
  7511. acc[overview.printer_id] = {
  7512. due_count: overview.due_count,
  7513. warning_count: overview.warning_count,
  7514. total_print_hours: overview.total_print_hours,
  7515. };
  7516. return acc;
  7517. },
  7518. {} as Record<number, PrinterMaintenanceInfo>
  7519. ) || {};
  7520. // Create a map of printer_id -> smart plug
  7521. const smartPlugByPrinter = smartPlugs?.reduce(
  7522. (acc, plug) => {
  7523. if (plug.printer_id) {
  7524. acc[plug.printer_id] = plug;
  7525. }
  7526. return acc;
  7527. },
  7528. {} as Record<number, typeof smartPlugs[0]>
  7529. ) || {};
  7530. const addMutation = useMutation({
  7531. mutationFn: api.createPrinter,
  7532. onSuccess: () => {
  7533. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7534. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7535. setShowAddModal(false);
  7536. },
  7537. onError: (error: Error) => {
  7538. // Localized message when the backend returns a stable error code;
  7539. // the raw message is an English fallback for non-UI clients.
  7540. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7541. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7542. return;
  7543. }
  7544. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7545. },
  7546. });
  7547. const powerOnMutation = useMutation({
  7548. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7549. onSuccess: () => {
  7550. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7551. setPoweringOn(null);
  7552. },
  7553. onError: () => {
  7554. setPoweringOn(null);
  7555. },
  7556. });
  7557. // Bulk selection state
  7558. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7559. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7560. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7561. const [bulkActionPending, setBulkActionPending] = useState(false);
  7562. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7563. const toggleSelect = useCallback((id: number) => {
  7564. setSelectedPrinterIds(prev => {
  7565. const next = new Set(prev);
  7566. if (next.has(id)) next.delete(id);
  7567. else next.add(id);
  7568. return next;
  7569. });
  7570. }, []);
  7571. const clearSelection = useCallback(() => {
  7572. setSelectedPrinterIds(new Set());
  7573. setIsSelectionMode(false);
  7574. }, []);
  7575. // Escape key exits selection mode
  7576. useEffect(() => {
  7577. const handleKeyDown = (e: KeyboardEvent) => {
  7578. if (e.key === 'Escape' && selectionMode) {
  7579. clearSelection();
  7580. }
  7581. };
  7582. window.addEventListener('keydown', handleKeyDown);
  7583. return () => window.removeEventListener('keydown', handleKeyDown);
  7584. }, [selectionMode, clearSelection]);
  7585. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7586. setBulkActionPending(true);
  7587. const ids = Array.from(selectedPrinterIds);
  7588. // Filter to only applicable printers based on cached state
  7589. const applicableIds = ids.filter(id => {
  7590. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7591. if (!status?.connected) return false;
  7592. switch (action) {
  7593. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7594. case 'pause': return status.state === 'RUNNING';
  7595. case 'resume': return status.state === 'PAUSE';
  7596. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7597. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7598. default: return false;
  7599. }
  7600. });
  7601. if (applicableIds.length === 0) {
  7602. showToast(t('printers.bulk.noneApplicable'), 'error');
  7603. setBulkActionPending(false);
  7604. setBulkConfirmAction(null);
  7605. return;
  7606. }
  7607. const apiCall = {
  7608. stop: api.stopPrint,
  7609. pause: api.pausePrint,
  7610. resume: api.resumePrint,
  7611. clearPlate: api.clearPlate,
  7612. clearHMS: api.clearHMSErrors,
  7613. }[action];
  7614. const results = await Promise.allSettled(
  7615. applicableIds.map(id => apiCall(id))
  7616. );
  7617. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7618. const failed = results.filter(r => r.status === 'rejected').length;
  7619. if (failed === 0) {
  7620. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7621. } else {
  7622. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7623. }
  7624. // Invalidate status queries for affected printers
  7625. applicableIds.forEach(id => {
  7626. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7627. });
  7628. setBulkActionPending(false);
  7629. setBulkConfirmAction(null);
  7630. }, [selectedPrinterIds, queryClient, showToast, t]);
  7631. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7632. // Actions that need confirmation
  7633. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7634. setBulkConfirmAction(action);
  7635. } else {
  7636. executeBulkAction(action);
  7637. }
  7638. }, [executeBulkAction]);
  7639. const toggleHideDisconnected = () => {
  7640. const newValue = !hideDisconnected;
  7641. setHideDisconnected(newValue);
  7642. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7643. };
  7644. const handleSortChange = (newSort: SortOption) => {
  7645. setSortBy(newSort);
  7646. localStorage.setItem('printerSortBy', newSort);
  7647. };
  7648. const toggleSortDirection = () => {
  7649. const newAsc = !sortAsc;
  7650. setSortAsc(newAsc);
  7651. localStorage.setItem('printerSortAsc', String(newAsc));
  7652. };
  7653. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7654. const getGridClasses = () => {
  7655. switch (cardSize) {
  7656. 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
  7657. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7658. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7659. case 4: return 'grid-cols-1'; // XL: single column, full width
  7660. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7661. }
  7662. };
  7663. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7664. // Increment version counter whenever a printer status cache entry is updated so
  7665. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7666. useEffect(() => {
  7667. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7668. if (
  7669. event.type === 'updated' &&
  7670. Array.isArray(event.query.queryKey) &&
  7671. event.query.queryKey[0] === 'printerStatus'
  7672. ) {
  7673. setStatusCacheVersion(v => v + 1);
  7674. }
  7675. });
  7676. return unsubscribe;
  7677. }, [queryClient]);
  7678. // Filter printers by search term, status, and location
  7679. const filteredPrinters = useMemo(() => {
  7680. if (!printers) return [];
  7681. let result = printers;
  7682. // Text search
  7683. if (search.trim()) {
  7684. const q = search.trim().toLowerCase();
  7685. result = result.filter(p =>
  7686. p.name.toLowerCase().includes(q) ||
  7687. (p.model || '').toLowerCase().includes(q) ||
  7688. (p.location || '').toLowerCase().includes(q) ||
  7689. (p.serial_number || '').toLowerCase().includes(q)
  7690. );
  7691. }
  7692. // Location filter
  7693. if (locationFilter !== 'all') {
  7694. result = result.filter(p => (p.location || '') === locationFilter);
  7695. }
  7696. // Status filter
  7697. if (statusFilter !== 'all') {
  7698. result = result.filter(p => {
  7699. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7700. if (!status?.connected) return statusFilter === 'offline';
  7701. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7702. switch (statusFilter) {
  7703. case 'printing': return status.state === 'RUNNING';
  7704. case 'paused': return status.state === 'PAUSE';
  7705. case 'finished': return status.state === 'FINISH';
  7706. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7707. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7708. case 'offline': return false; // Connected printers are never offline
  7709. default: return true;
  7710. }
  7711. });
  7712. }
  7713. return result;
  7714. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7715. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7716. // Derive unique locations for the location filter dropdown
  7717. const availableLocations = useMemo(() => {
  7718. if (!printers) return [];
  7719. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7720. }, [printers]);
  7721. // Sort printers based on selected option
  7722. const sortedPrinters = useMemo(() => {
  7723. const sorted = [...filteredPrinters];
  7724. switch (sortBy) {
  7725. case 'name':
  7726. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7727. break;
  7728. case 'model':
  7729. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7730. break;
  7731. case 'location':
  7732. // Sort by location, with ungrouped printers last
  7733. sorted.sort((a, b) => {
  7734. const locA = a.location || '';
  7735. const locB = b.location || '';
  7736. if (!locA && locB) return 1;
  7737. if (locA && !locB) return -1;
  7738. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7739. });
  7740. break;
  7741. case 'status':
  7742. // Sort by status: HMS errors > printing > idle > offline
  7743. sorted.sort((a, b) => {
  7744. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7745. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7746. const getPriority = (s: typeof statusA) => {
  7747. if (!s?.connected) return 3; // offline
  7748. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7749. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7750. if (s.state === 'RUNNING') return 1; // printing
  7751. return 2; // idle
  7752. };
  7753. return getPriority(statusA) - getPriority(statusB);
  7754. });
  7755. break;
  7756. case 'eta':
  7757. sorted.sort((a, b) => {
  7758. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  7759. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  7760. const tier = (s: typeof statusA) => {
  7761. if (!s?.connected) return 3; // offline last
  7762. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  7763. if (s.state === 'RUNNING') return 1; // printing without ETA
  7764. return 2; // idle
  7765. };
  7766. const ta = tier(statusA);
  7767. const tb = tier(statusB);
  7768. if (ta !== tb) return ta - tb;
  7769. if (ta === 0) {
  7770. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  7771. if (diff !== 0) return diff;
  7772. }
  7773. return a.name.localeCompare(b.name);
  7774. });
  7775. break;
  7776. }
  7777. // Apply ascending/descending
  7778. if (!sortAsc) {
  7779. sorted.reverse();
  7780. }
  7781. return sorted;
  7782. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  7783. const selectAll = useCallback(() => {
  7784. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  7785. setIsSelectionMode(true);
  7786. }, [sortedPrinters]);
  7787. const selectByState = useCallback((state: PrinterState) => {
  7788. setSelectedPrinterIds(prev => {
  7789. const next = new Set(prev);
  7790. sortedPrinters.forEach(p => {
  7791. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7792. if (classifyPrinterStatus(status) === state) next.add(p.id);
  7793. });
  7794. return next;
  7795. });
  7796. setIsSelectionMode(true);
  7797. }, [sortedPrinters, queryClient]);
  7798. const selectByLocation = useCallback((location: string) => {
  7799. setSelectedPrinterIds(prev => {
  7800. const next = new Set(prev);
  7801. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  7802. return next;
  7803. });
  7804. setIsSelectionMode(true);
  7805. }, [sortedPrinters]);
  7806. const selectByModel = useCallback((model: string) => {
  7807. setSelectedPrinterIds(prev => {
  7808. const next = new Set(prev);
  7809. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  7810. return next;
  7811. });
  7812. setIsSelectionMode(true);
  7813. }, [sortedPrinters]);
  7814. const toggleSectionCollapse = useCallback((key: string) => {
  7815. setCollapsedSections(prev => {
  7816. const next = { ...prev, [key]: !prev[key] };
  7817. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  7818. return next;
  7819. });
  7820. }, []);
  7821. // Group printers when sorted by location, status, or model
  7822. const groupedPrinters = useMemo(() => {
  7823. if (sortBy === 'name' || sortBy === 'eta') return null;
  7824. const groups: Record<string, typeof sortedPrinters> = {};
  7825. if (sortBy === 'location') {
  7826. sortedPrinters.forEach(printer => {
  7827. const location = printer.location || 'Ungrouped';
  7828. if (!groups[location]) groups[location] = [];
  7829. groups[location].push(printer);
  7830. });
  7831. } else if (sortBy === 'model') {
  7832. sortedPrinters.forEach(printer => {
  7833. const model = printer.model || 'Unknown';
  7834. if (!groups[model]) groups[model] = [];
  7835. groups[model].push(printer);
  7836. });
  7837. } else if (sortBy === 'status') {
  7838. sortedPrinters.forEach(printer => {
  7839. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  7840. const group = classifyPrinterStatus(status);
  7841. if (!groups[group]) groups[group] = [];
  7842. groups[group].push(printer);
  7843. });
  7844. }
  7845. return groups;
  7846. // 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
  7847. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  7848. const toolbarRef = useRef<HTMLDivElement>(null);
  7849. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  7850. const expandedToolbarWidthRef = useRef(0);
  7851. const [compactToolbar, setCompactToolbar] = useState(false);
  7852. const measureToolbar = useCallback(() => {
  7853. const toolbar = toolbarRef.current;
  7854. if (!toolbar) return;
  7855. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  7856. if (measuredControlsWidth) {
  7857. expandedToolbarWidthRef.current = measuredControlsWidth;
  7858. }
  7859. const searchMinimumWidth = 220;
  7860. const gapWidth = 8;
  7861. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  7862. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  7863. }, []);
  7864. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  7865. useLayoutEffect(() => {
  7866. measureToolbar();
  7867. const toolbar = toolbarRef.current;
  7868. if (!toolbar) return;
  7869. if (typeof ResizeObserver === 'undefined') {
  7870. window.addEventListener('resize', measureToolbar);
  7871. return () => window.removeEventListener('resize', measureToolbar);
  7872. }
  7873. const resizeObserver = new ResizeObserver(() => measureToolbar());
  7874. resizeObserver.observe(toolbar);
  7875. window.addEventListener('resize', measureToolbar);
  7876. return () => {
  7877. resizeObserver.disconnect();
  7878. window.removeEventListener('resize', measureToolbar);
  7879. };
  7880. }, [
  7881. measureToolbar,
  7882. printers?.length,
  7883. availableLocations.length,
  7884. hideDisconnected,
  7885. smartPlugCount,
  7886. ]);
  7887. const renderFilterControls = (inMenu = false) => (
  7888. <>
  7889. {/* Status filter */}
  7890. {printers && printers.length > 0 && (
  7891. <ToolbarDropdown
  7892. value={statusFilter}
  7893. onChange={setStatusFilter}
  7894. fullWidth={inMenu}
  7895. options={[
  7896. { value: 'all', label: t('printers.filter.allStatuses') },
  7897. { value: 'printing', label: t('printers.status.printing') },
  7898. { value: 'paused', label: t('printers.status.paused') },
  7899. { value: 'idle', label: t('printers.status.idle') },
  7900. { value: 'finished', label: t('printers.status.finished') },
  7901. { value: 'error', label: t('printers.status.error') },
  7902. { value: 'offline', label: t('printers.status.offline') },
  7903. ]}
  7904. />
  7905. )}
  7906. {/* Location filter — only shown when at least one printer has a location */}
  7907. {printers && printers.length > 0 && availableLocations.length > 0 && (
  7908. <ToolbarDropdown
  7909. value={locationFilter}
  7910. onChange={setLocationFilter}
  7911. fullWidth={inMenu}
  7912. options={[
  7913. { value: 'all', label: t('printers.filter.allLocations') },
  7914. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  7915. ]}
  7916. />
  7917. )}
  7918. <button
  7919. type="button"
  7920. onClick={toggleHideDisconnected}
  7921. aria-pressed={hideDisconnected}
  7922. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  7923. hideDisconnected
  7924. ? 'bg-bambu-green border-bambu-green text-white'
  7925. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7926. }`}
  7927. >
  7928. {t('printers.hideOffline')}
  7929. </button>
  7930. </>
  7931. );
  7932. const renderViewControls = (inMenu = false) => (
  7933. <>
  7934. {/* Sort dropdown */}
  7935. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  7936. <ToolbarDropdown<SortOption>
  7937. value={sortBy}
  7938. onChange={handleSortChange}
  7939. fullWidth={inMenu}
  7940. options={[
  7941. { value: 'name', label: t('printers.sort.name') },
  7942. { value: 'status', label: t('printers.sort.status') },
  7943. { value: 'model', label: t('printers.sort.model') },
  7944. { value: 'location', label: t('printers.sort.location') },
  7945. { value: 'eta', label: t('printers.sort.eta') },
  7946. ]}
  7947. />
  7948. <button
  7949. onClick={toggleSortDirection}
  7950. 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"
  7951. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  7952. >
  7953. {sortAsc ? (
  7954. <ArrowUp className="w-4 h-4 text-white" />
  7955. ) : (
  7956. <ArrowDown className="w-4 h-4 text-white" />
  7957. )}
  7958. </button>
  7959. </div>
  7960. {/* Page view toggle: Cards / Cam Wall */}
  7961. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  7962. <button
  7963. type="button"
  7964. onClick={() => {
  7965. setPageView('cards');
  7966. localStorage.setItem('printerPageView', 'cards');
  7967. }}
  7968. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  7969. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  7970. }`}
  7971. title={t('printers.pageView.cards')}
  7972. aria-pressed={pageView === 'cards'}
  7973. >
  7974. <LayoutGrid className="w-3.5 h-3.5" />
  7975. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  7976. </button>
  7977. <button
  7978. type="button"
  7979. onClick={() => {
  7980. setPageView('camwall');
  7981. localStorage.setItem('printerPageView', 'camwall');
  7982. }}
  7983. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  7984. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  7985. }`}
  7986. title={t('printers.pageView.camWall')}
  7987. aria-pressed={pageView === 'camwall'}
  7988. disabled={!hasPermission('camera:view')}
  7989. >
  7990. <MonitorPlay className="w-3.5 h-3.5" />
  7991. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  7992. </button>
  7993. </div>
  7994. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  7995. view, and the page a kiosk token points at. Only offered once the wall
  7996. is the active view, so it doesn't compete with the toggle above. */}
  7997. {pageView === 'camwall' && hasPermission('camera:view') && (
  7998. <RouterLink
  7999. to="/camwall"
  8000. 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' : ''}`}
  8001. title={t('printers.pageView.openCamWallPage')}
  8002. >
  8003. <ExternalLink className="w-3.5 h-3.5" />
  8004. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8005. </RouterLink>
  8006. )}
  8007. {/* Card size selector */}
  8008. <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' : ''}`}>
  8009. {cardSizeLabels.map((label, index) => {
  8010. const size = index + 1;
  8011. const isSelected = cardSize === size;
  8012. return (
  8013. <button
  8014. key={label}
  8015. onClick={() => {
  8016. setCompactDrilldownPrinterId(null);
  8017. setCardSize(size);
  8018. localStorage.setItem('printerCardSize', String(size));
  8019. }}
  8020. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8021. index === 0 ? 'rounded-l-lg' : ''
  8022. } ${
  8023. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8024. } ${
  8025. isSelected
  8026. ? 'bg-bambu-green text-white'
  8027. : 'text-white hover:bg-bambu-dark-tertiary'
  8028. }`}
  8029. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8030. >
  8031. {label}
  8032. </button>
  8033. );
  8034. })}
  8035. </div>
  8036. </>
  8037. );
  8038. const renderActionControls = (inMenu = false) => (
  8039. <>
  8040. {/* Bulk select toggle */}
  8041. <button
  8042. onClick={() => {
  8043. if (selectionMode) clearSelection();
  8044. else setIsSelectionMode(true);
  8045. }}
  8046. 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' : ''} ${
  8047. selectionMode
  8048. ? 'bg-bambu-green border-bambu-green text-white'
  8049. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8050. }`}
  8051. title={t('printers.bulk.select')}
  8052. disabled={!hasPermission('printers:control')}
  8053. >
  8054. <CheckSquare className="w-4 h-4" />
  8055. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8056. </button>
  8057. {/* Power dropdown for offline printers with smart plugs */}
  8058. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8059. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8060. <button
  8061. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8062. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8063. inMenu
  8064. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8065. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8066. }`}
  8067. >
  8068. <span className="flex items-center gap-1.5">
  8069. <Power className="w-4 h-4" />
  8070. {t('printers.powerOn')}
  8071. </span>
  8072. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8073. </button>
  8074. {showPowerDropdown && (
  8075. <>
  8076. {/* Backdrop to close dropdown */}
  8077. <div
  8078. className="fixed inset-0 z-10"
  8079. onClick={() => setShowPowerDropdown(false)}
  8080. />
  8081. <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">
  8082. <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">
  8083. {t('printers.offlinePrintersWithPlugs')}
  8084. </div>
  8085. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  8086. <PowerDropdownItem
  8087. key={printer.id}
  8088. printer={printer}
  8089. plug={smartPlugByPrinter[printer.id]}
  8090. onPowerOn={(plugId) => {
  8091. setPoweringOn(plugId);
  8092. powerOnMutation.mutate(plugId);
  8093. }}
  8094. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  8095. />
  8096. ))}
  8097. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  8098. <div className="px-3 py-2 text-sm text-bambu-gray">
  8099. No printers with smart plugs
  8100. </div>
  8101. )}
  8102. </div>
  8103. </>
  8104. )}
  8105. </div>
  8106. )}
  8107. <Button
  8108. onClick={() => setShowAddModal(true)}
  8109. disabled={!hasPermission('printers:create')}
  8110. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8111. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  8112. >
  8113. <Plus className="w-4 h-4" />
  8114. {t('printers.addPrinter')}
  8115. </Button>
  8116. </>
  8117. );
  8118. return (
  8119. <div className="p-4 md:p-8">
  8120. <div className="space-y-3 mb-6">
  8121. <div>
  8122. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  8123. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  8124. {t('printers.title')}
  8125. </h1>
  8126. <StatusSummaryBar printers={printers} />
  8127. </div>
  8128. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8129. {/* Only show search bar when printers exist */}
  8130. {printers && printers.length > 0 && (
  8131. <div className="relative min-w-0 flex-1">
  8132. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8133. <input
  8134. type="search"
  8135. name="printer-search"
  8136. autoComplete="off"
  8137. data-1p-ignore
  8138. data-lpignore="true"
  8139. value={search}
  8140. onChange={(e) => setSearch(e.target.value)}
  8141. placeholder={t('printers.search')}
  8142. aria-label={t('printers.search')}
  8143. 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"
  8144. />
  8145. {search && (
  8146. <button
  8147. type="button"
  8148. aria-label={t('common.clear')}
  8149. onClick={() => setSearch('')}
  8150. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8151. >
  8152. <X className="w-4 h-4" />
  8153. </button>
  8154. )}
  8155. </div>
  8156. )}
  8157. <div
  8158. ref={expandedToolbarControlsRef}
  8159. aria-hidden={compactToolbar}
  8160. inert={compactToolbar}
  8161. 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`}
  8162. >
  8163. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8164. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8165. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8166. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8167. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8168. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8169. </div>
  8170. {compactToolbar && (
  8171. <div className="ml-auto flex items-center justify-end gap-1">
  8172. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8173. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8174. </ToolbarMenu>
  8175. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8176. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8177. </ToolbarMenu>
  8178. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8179. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8180. </ToolbarMenu>
  8181. </div>
  8182. )}
  8183. </div>
  8184. </div>
  8185. {isLoading ? (
  8186. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8187. ) : printers?.length === 0 ? (
  8188. <Card>
  8189. <CardContent className="text-center py-12">
  8190. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8191. <Button
  8192. onClick={() => setShowAddModal(true)}
  8193. disabled={!hasPermission('printers:create')}
  8194. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8195. >
  8196. <Plus className="w-4 h-4" />
  8197. {t('printers.addPrinter')}
  8198. </Button>
  8199. </CardContent>
  8200. </Card>
  8201. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8202. <Card>
  8203. <CardContent className="text-center py-12">
  8204. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8205. </CardContent>
  8206. </Card>
  8207. ) : pageView === 'camwall' ? (
  8208. <CameraWall
  8209. printers={sortedPrinters}
  8210. maxLive={camWallMaxLive}
  8211. snapshotIntervalSec={camWallSnapshotSec}
  8212. onTileClick={(id, name) => {
  8213. const cameraMode = settings?.camera_view_mode || 'window';
  8214. if (cameraMode === 'embedded') {
  8215. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  8216. } else {
  8217. const saved = localStorage.getItem('cameraWindowState');
  8218. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  8219. const features = [
  8220. `width=${state.width}`,
  8221. `height=${state.height}`,
  8222. state.left !== undefined ? `left=${state.left}` : '',
  8223. state.top !== undefined ? `top=${state.top}` : '',
  8224. 'menubar=no,toolbar=no,location=no,status=no',
  8225. ].filter(Boolean).join(',');
  8226. window.open(`/camera/${id}`, `camera-${id}`, features);
  8227. }
  8228. }}
  8229. statusMode={camWallStatusMode}
  8230. onChangeMaxLive={(next) => {
  8231. setCamWallMaxLive(next);
  8232. localStorage.setItem('camWallMaxLive', String(next));
  8233. }}
  8234. onChangeSnapshotIntervalSec={(next) => {
  8235. setCamWallSnapshotSec(next);
  8236. localStorage.setItem('camWallSnapshotSec', String(next));
  8237. }}
  8238. onChangeStatusMode={(next) => {
  8239. setCamWallStatusMode(next);
  8240. localStorage.setItem('camWallStatusMode', next);
  8241. }}
  8242. />
  8243. ) : groupedPrinters ? (
  8244. /* Grouped view (location, status, or model) */
  8245. <div className="space-y-6">
  8246. {(() => {
  8247. const keys = sortBy === 'status'
  8248. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8249. : Object.keys(groupedPrinters);
  8250. // For status grouping, asc/desc flips the fixed priority order
  8251. // (asc = error→offline, desc = offline→error). This matches the
  8252. // sort-toggle behaviour for other groupings.
  8253. return (sortAsc ? keys : [...keys].reverse());
  8254. })().map((groupKey) => {
  8255. const groupPrinters = groupedPrinters[groupKey];
  8256. const collapseKey = `${sortBy}:${groupKey}`;
  8257. const isOpen = !collapsedSections[collapseKey];
  8258. const dot = sortBy === 'status'
  8259. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8260. : 'bg-bambu-green';
  8261. const label = sortBy === 'status'
  8262. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8263. : groupKey;
  8264. return (
  8265. <Collapsible
  8266. key={groupKey}
  8267. open={isOpen}
  8268. onToggle={() => toggleSectionCollapse(collapseKey)}
  8269. summaryClassName="py-1"
  8270. summary={
  8271. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8272. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8273. {label}
  8274. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8275. {selectionMode && (
  8276. <button
  8277. onClick={(e) => {
  8278. e.stopPropagation();
  8279. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8280. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8281. else if (sortBy === 'model') selectByModel(groupKey);
  8282. }}
  8283. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8284. >
  8285. {t('printers.bulk.selectAll')}
  8286. </button>
  8287. )}
  8288. </h2>
  8289. }
  8290. >
  8291. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8292. {groupPrinters.map((printer) => (
  8293. <PrinterCard
  8294. key={printer.id}
  8295. printer={printer}
  8296. hideIfDisconnected={hideDisconnected}
  8297. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8298. viewMode={viewMode}
  8299. cardSize={cardSize}
  8300. amsThresholds={settings ? {
  8301. humidityGood: Number(settings.ams_humidity_good) || 40,
  8302. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8303. tempGood: Number(settings.ams_temp_good) || 28,
  8304. tempFair: Number(settings.ams_temp_fair) || 35,
  8305. } : undefined}
  8306. spoolmanEnabled={spoolmanEnabled}
  8307. hasUnlinkedSpools={hasUnlinkedSpools}
  8308. linkedSpools={linkedSpools}
  8309. spoolmanUrl={spoolmanStatus?.url}
  8310. spoolmanSyncMode={spoolmanSyncMode}
  8311. onGetAssignment={getAssignment}
  8312. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8313. spoolmanSpools={spoolmanSpools}
  8314. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8315. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8316. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8317. timeFormat={settings?.time_format || 'system'}
  8318. cameraViewMode={settings?.camera_view_mode || 'window'}
  8319. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8320. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8321. dryingPresets={effectiveDryingPresets}
  8322. nozzleTempPresets={effectiveNozzleTempPresets}
  8323. bedTempPresets={effectiveBedTempPresets}
  8324. chamberTempPresets={effectiveChamberTempPresets}
  8325. fanSpeedPresets={effectiveFanSpeedPresets}
  8326. requirePlateClear={settings?.require_plate_clear === true}
  8327. selectionMode={selectionMode}
  8328. isSelected={selectedPrinterIds.has(printer.id)}
  8329. onToggleSelect={toggleSelect}
  8330. onOpenCompactCard={openCompactCard}
  8331. />
  8332. ))}
  8333. </div>
  8334. </Collapsible>
  8335. );
  8336. })}
  8337. </div>
  8338. ) : (
  8339. /* Regular grid view */
  8340. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8341. {sortedPrinters.map((printer) => (
  8342. <PrinterCard
  8343. key={printer.id}
  8344. printer={printer}
  8345. hideIfDisconnected={hideDisconnected}
  8346. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8347. viewMode={viewMode}
  8348. cardSize={cardSize}
  8349. spoolmanEnabled={spoolmanEnabled}
  8350. hasUnlinkedSpools={hasUnlinkedSpools}
  8351. linkedSpools={linkedSpools}
  8352. spoolmanUrl={spoolmanStatus?.url}
  8353. spoolmanSyncMode={spoolmanSyncMode}
  8354. onGetAssignment={getAssignment}
  8355. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8356. spoolmanSpools={spoolmanSpools}
  8357. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8358. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8359. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8360. amsThresholds={settings ? {
  8361. humidityGood: Number(settings.ams_humidity_good) || 40,
  8362. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8363. tempGood: Number(settings.ams_temp_good) || 28,
  8364. tempFair: Number(settings.ams_temp_fair) || 35,
  8365. } : undefined}
  8366. timeFormat={settings?.time_format || 'system'}
  8367. cameraViewMode={settings?.camera_view_mode || 'window'}
  8368. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8369. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8370. dryingPresets={effectiveDryingPresets}
  8371. nozzleTempPresets={effectiveNozzleTempPresets}
  8372. bedTempPresets={effectiveBedTempPresets}
  8373. chamberTempPresets={effectiveChamberTempPresets}
  8374. fanSpeedPresets={effectiveFanSpeedPresets}
  8375. requirePlateClear={settings?.require_plate_clear === true}
  8376. selectionMode={selectionMode}
  8377. isSelected={selectedPrinterIds.has(printer.id)}
  8378. onToggleSelect={toggleSelect}
  8379. onOpenCompactCard={openCompactCard}
  8380. />
  8381. ))}
  8382. </div>
  8383. )}
  8384. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8385. <button
  8386. type="button"
  8387. onClick={returnToCompactCards}
  8388. 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}`}
  8389. title={t('common.back', 'Back')}
  8390. >
  8391. <ArrowLeft className="w-4 h-4" />
  8392. {t('common.back', 'Back')}
  8393. </button>
  8394. )}
  8395. {showAddModal && (
  8396. <AddPrinterModal
  8397. onClose={() => setShowAddModal(false)}
  8398. onAdd={(data) => addMutation.mutate(data)}
  8399. existingSerials={printers?.map(p => p.serial_number) || []}
  8400. />
  8401. )}
  8402. {/* Bulk selection toolbar */}
  8403. {selectionMode && printers && (
  8404. <BulkPrinterToolbar
  8405. selectedIds={selectedPrinterIds}
  8406. printers={printers}
  8407. onClose={clearSelection}
  8408. onSelectAll={selectAll}
  8409. onSelectByLocation={selectByLocation}
  8410. onSelectByState={selectByState}
  8411. onAction={handleBulkAction}
  8412. actionPending={bulkActionPending}
  8413. />
  8414. )}
  8415. {/* Bulk action confirmation modals */}
  8416. {bulkConfirmAction === 'stop' && (
  8417. <ConfirmModal
  8418. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8419. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8420. confirmText={t('printers.bulk.confirm.stopButton')}
  8421. variant="danger"
  8422. isLoading={bulkActionPending}
  8423. onConfirm={() => executeBulkAction('stop')}
  8424. onCancel={() => setBulkConfirmAction(null)}
  8425. />
  8426. )}
  8427. {bulkConfirmAction === 'pause' && (
  8428. <ConfirmModal
  8429. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8430. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8431. confirmText={t('printers.bulk.confirm.pauseButton')}
  8432. isLoading={bulkActionPending}
  8433. onConfirm={() => executeBulkAction('pause')}
  8434. onCancel={() => setBulkConfirmAction(null)}
  8435. />
  8436. )}
  8437. {bulkConfirmAction === 'clearPlate' && (
  8438. <ConfirmModal
  8439. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8440. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8441. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8442. isLoading={bulkActionPending}
  8443. onConfirm={() => executeBulkAction('clearPlate')}
  8444. onCancel={() => setBulkConfirmAction(null)}
  8445. />
  8446. )}
  8447. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8448. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8449. <EmbeddedCameraViewer
  8450. key={camera.id}
  8451. printerId={camera.id}
  8452. printerName={camera.name}
  8453. viewerIndex={index}
  8454. onClose={() => setEmbeddedCameraPrinters(prev => {
  8455. const next = new Map(prev);
  8456. next.delete(camera.id);
  8457. return next;
  8458. })}
  8459. />
  8460. ))}
  8461. </div>
  8462. );
  8463. }