PrintersPage.tsx 476 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850
  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, type PopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. openCameraWindow,
  8. readStoredCameraViewMode,
  9. storeCameraViewMode,
  10. type CameraViewMode,
  11. } from '../utils/camera';
  12. import { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  13. import { computeStartAfter, type DryingStartMode } from '../lib/scheduledDrying';
  14. import {
  15. isExternalSpoolHidden,
  16. setExternalSpoolHidden as persistExternalSpoolHidden,
  17. } from '../utils/printerCardPrefs';
  18. import {
  19. BED_TEMP_DEFAULTS,
  20. CHAMBER_TEMP_DEFAULTS,
  21. FAN_SPEED_DEFAULTS,
  22. NOZZLE_TEMP_DEFAULTS,
  23. buildPresetOptions,
  24. parsePresetTriple,
  25. } from '../utils/temperatureFanPresets';
  26. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  27. // covers header + filament select + temp slider + duration + rotate-tray
  28. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  29. // earlier); under-estimating leaves the popover clipped off the bottom (the
  30. // original bug at #1447).
  31. const DRYING_POPOVER_WIDTH = 240;
  32. // Height in "now" mode plus the tallest start-mode control; a conservative
  33. // over-estimate just flips the popover above the trigger sooner.
  34. const DRYING_POPOVER_ESTIMATED_HEIGHT = 440;
  35. // Delay presets for the "After delay" drying start mode, in minutes.
  36. const DRYING_DELAY_OPTIONS = [30, 60, 120, 240, 480, 720, 1440];
  37. // Every printer card reads the same fleet-wide scheduled-drying list.
  38. const SCHEDULED_DRYINGS_KEY = ['scheduled-dryings'] as const;
  39. // Why a due run has not started yet: every waiting_reason the scheduler can
  40. // set. An unmapped one leaves the card showing a bare "Drying scheduled
  41. // for ..." with no hint why nothing is happening.
  42. const WAITING_REASON_KEYS: Record<string, string> = {
  43. ams_power_required: 'printers.drying.powerRequired',
  44. ams_retract_filament: 'printers.drying.retractFilament',
  45. ams_blocked: 'printers.drying.cannotDryNow',
  46. ams_not_found: 'printers.drying.waitingAmsNotFound',
  47. printer_offline: 'printers.drying.waitingOffline',
  48. printer_busy: 'printers.drying.waitingPrinterBusy',
  49. already_drying: 'printers.drying.waitingAlreadyDrying',
  50. interrupted: 'printers.drying.waitingInterrupted',
  51. };
  52. function waitingReasonKey(reason: string | null | undefined): string | undefined {
  53. return reason ? WAITING_REASON_KEYS[reason] : undefined;
  54. }
  55. // Which cannot-dry code to name when the firmware reports several at once.
  56. // Same priority as the backend's drying_preflight.primary_reason_code, so the
  57. // button's tooltip and a scheduled row's waiting reason describe one blocked
  58. // AMS the same way: codes 1 and 8 are a power-supply problem, 3 is filament
  59. // left at the outlet, and both need the user to go and do something. The rest
  60. // (AMS busy, cooling down) clear by themselves and share the generic wording.
  61. function dryingBlockedKey(reasons: Array<number | string> | undefined): string {
  62. const codes = (reasons ?? []).map(r => Number(r));
  63. if (codes.some(c => c === 1 || c === 8)) return 'printers.drying.powerRequired';
  64. if (codes.includes(3)) return 'printers.drying.retractFilament';
  65. return 'printers.drying.cannotDryNow';
  66. }
  67. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  68. import { useTranslation } from 'react-i18next';
  69. import { useTheme } from '../contexts/ThemeContext';
  70. import { useAuth } from '../contexts/AuthContext';
  71. import {
  72. Plus,
  73. Link,
  74. Unlink,
  75. Signal,
  76. Clock,
  77. MoreVertical,
  78. Trash2,
  79. RefreshCw,
  80. RotateCw,
  81. Box,
  82. HardDrive,
  83. AlertTriangle,
  84. AlertCircle,
  85. Terminal,
  86. Power,
  87. Zap,
  88. Wrench,
  89. ChevronDown,
  90. Eye,
  91. EyeOff,
  92. Filter,
  93. Pencil,
  94. ArrowLeft,
  95. ArrowRight,
  96. ArrowUp,
  97. ArrowDown,
  98. Layers,
  99. Video,
  100. Search,
  101. Loader2,
  102. Square,
  103. Pause,
  104. Play,
  105. X,
  106. Fan,
  107. Wind,
  108. AirVent,
  109. Download,
  110. ScanSearch,
  111. CheckCircle,
  112. CheckSquare,
  113. XCircle,
  114. User,
  115. Home,
  116. Printer as PrinterIcon,
  117. Info,
  118. Cable,
  119. Flame,
  120. Repeat,
  121. Snowflake,
  122. Gauge,
  123. DoorOpen,
  124. DoorClosed,
  125. Move,
  126. LogIn,
  127. LogOut,
  128. MoreHorizontal,
  129. SlidersHorizontal,
  130. Stethoscope,
  131. ScanEye,
  132. LineChart as LineChartIcon,
  133. LayoutGrid,
  134. MonitorPlay,
  135. ExternalLink,
  136. PictureInPicture2,
  137. } from 'lucide-react';
  138. // Aliased: lucide-react already exports a `Link` icon into this module.
  139. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  140. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  141. import { formatDateOnly, formatDateTime, formatETA, formatDuration, formatDurationFromHours, parseUTCDate } from '../utils/date';
  142. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  143. import { Card, CardContent } from '../components/Card';
  144. import { Button } from '../components/Button';
  145. import { ConfirmModal } from '../components/ConfirmModal';
  146. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  147. import { FileManagerModal } from '../components/FileManagerModal';
  148. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  149. import { CameraWall } from '../components/CameraWall';
  150. import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
  151. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  152. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  153. import { AiDetectionModal } from '../components/AiDetectionModal';
  154. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  155. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  156. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  157. import { AmsBackupModal } from '../components/AmsBackupModal';
  158. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  159. import type { HeaterSensorKind } from '../api/client';
  160. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  161. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  162. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  163. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  164. import { useToast } from '../contexts/ToastContext';
  165. import { ChamberLight } from '../components/icons/ChamberLight';
  166. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  167. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  168. import { FileUploadModal } from '../components/FileUploadModal';
  169. import { PrintModal } from '../components/PrintModal';
  170. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  171. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter, resolveSlotExtruder, FTS_INLET_SIDE } from '../utils/amsHelpers';
  172. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems, isPrinterCurrentlyDispatchable } from '../utils/printer';
  173. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  174. import { Collapsible } from '../components/Collapsible';
  175. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  176. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  177. // The status filter's options, and the only values it may hold. One list so a
  178. // saved filter cannot be validated against a set the dropdown has since moved
  179. // on from (#2833). Labels stay literal so they remain greppable.
  180. const STATUS_FILTER_OPTIONS = [
  181. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  182. { value: 'printing', labelKey: 'printers.status.printing' },
  183. { value: 'paused', labelKey: 'printers.status.paused' },
  184. { value: 'idle', labelKey: 'printers.status.idle' },
  185. { value: 'finished', labelKey: 'printers.status.finished' },
  186. { value: 'error', labelKey: 'printers.status.error' },
  187. { value: 'offline', labelKey: 'printers.status.offline' },
  188. ] as const;
  189. function isKnownStatusFilter(value: string | null): boolean {
  190. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  191. }
  192. export interface SpoolmanSlotAssignmentRow {
  193. printer_id: number;
  194. ams_id: number;
  195. tray_id: number;
  196. spoolman_spool_id: number;
  197. }
  198. // Color names resolve via getColorName() which reads the backend color_catalog
  199. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  200. // Format K value with 3 decimal places, default to 0.020 if null
  201. function formatKValue(k: number | null | undefined): string {
  202. const value = k ?? 0.020;
  203. return value.toFixed(3);
  204. }
  205. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  206. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  207. const { mode } = useTheme();
  208. const { t } = useTranslation();
  209. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  210. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  211. return (
  212. <span
  213. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  214. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  215. title={side === 'L' ? t('common.left') : t('common.right')}
  216. >
  217. {side}
  218. </span>
  219. );
  220. }
  221. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  222. // deliberately a different colour, because it means something different: this
  223. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  224. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  225. const { mode } = useTheme();
  226. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  227. return (
  228. <span
  229. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  230. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  231. title={title}
  232. >
  233. {FTS_INLET_SIDE[inlet]}
  234. </span>
  235. );
  236. }
  237. /**
  238. * Which side indicator, if any, belongs on an AMS card header.
  239. *
  240. * Three sources, in descending authority:
  241. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  242. * through the switch, so the inlet is the only meaningful label.
  243. * 2. A real extruder id from ams_extruder_map.
  244. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  245. * never reported a map. This one is only a guess, and it is suppressed
  246. * when a switch is installed: with an FTS every unit reports extruder
  247. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  248. * nothing but their unit numbers.
  249. */
  250. function amsSideBadge(
  251. amsId: number,
  252. amsExtruderMap: Record<string, number>,
  253. amsSwitchInlet: Record<string, 'A' | 'B'>,
  254. ftsInstalled: boolean
  255. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  256. const inlet = amsSwitchInlet[String(amsId)];
  257. if (inlet) return { kind: 'inlet', inlet };
  258. const mapped = amsExtruderMap[String(amsId)];
  259. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  260. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  261. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  262. return null;
  263. }
  264. // Expand nozzle type codes to material names
  265. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  266. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  267. function nozzleTypeName(type: string, t: (key: string) => string): string {
  268. if (!type) return '';
  269. // Full text names (from main nozzle info)
  270. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  271. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  272. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  273. // 4-char codes (e.g. "HS01"): last 2 digits = material
  274. if (type.length >= 4) {
  275. const material = type.slice(2, 4);
  276. if (material === '00') return t('printers.nozzleStainlessSteel');
  277. if (material === '01') return t('printers.nozzleHardenedSteel');
  278. if (material === '05') return t('printers.nozzleTungstenCarbide');
  279. }
  280. // 2-digit numeric codes
  281. if (type === '00') return t('printers.nozzleStainlessSteel');
  282. if (type === '01') return t('printers.nozzleHardenedSteel');
  283. if (type === '05') return t('printers.nozzleTungstenCarbide');
  284. // 2-char alpha codes: H prefix = hardened steel
  285. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  286. return type;
  287. }
  288. // Parse flow type from nozzle type code
  289. // HH = high flow, HS = standard/normal
  290. function nozzleFlowName(type: string, t: (key: string) => string): string {
  291. if (!type) return '';
  292. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  293. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  294. return '';
  295. }
  296. // Per-slot hover card for nozzle rack
  297. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  298. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  299. slot: import('../api/client').NozzleRackSlot;
  300. index: number;
  301. activeStatus?: boolean;
  302. filamentName?: string;
  303. children: React.ReactNode;
  304. }) {
  305. const { t } = useTranslation();
  306. const [isVisible, setIsVisible] = useState(false);
  307. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  308. const triggerRef = useRef<HTMLDivElement>(null);
  309. const cardRef = useRef<HTMLDivElement>(null);
  310. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  311. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  312. const isMounted = slot.stat === 1;
  313. useEffect(() => {
  314. if (isVisible && triggerRef.current && cardRef.current) {
  315. const triggerRect = triggerRef.current.getBoundingClientRect();
  316. const cardHeight = cardRef.current.offsetHeight;
  317. const headerHeight = 56;
  318. const spaceAbove = triggerRect.top - headerHeight;
  319. const spaceBelow = window.innerHeight - triggerRect.bottom;
  320. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  321. setPosition('bottom');
  322. } else {
  323. setPosition('top');
  324. }
  325. }
  326. }, [isVisible]);
  327. const handleMouseEnter = () => {
  328. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  329. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  330. };
  331. const handleMouseLeave = () => {
  332. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  333. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  334. };
  335. useEffect(() => {
  336. return () => {
  337. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  338. };
  339. }, []);
  340. const filamentCss = parseFilamentColor(slot.filament_color);
  341. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  342. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  343. return (
  344. <div
  345. ref={triggerRef}
  346. className="relative"
  347. onMouseEnter={handleMouseEnter}
  348. onMouseLeave={handleMouseLeave}
  349. >
  350. {children}
  351. {isVisible && (
  352. <div
  353. ref={cardRef}
  354. className={`
  355. absolute left-1/2 -translate-x-1/2 z-50
  356. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  357. animate-in fade-in-0 zoom-in-95 duration-150
  358. `}
  359. style={{ maxWidth: 'calc(100vw - 24px)' }}
  360. >
  361. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  362. {isEmpty ? (
  363. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  364. Slot {index + 1} — Empty
  365. </div>
  366. ) : (
  367. <div className="p-2.5 space-y-1.5">
  368. {/* Diameter */}
  369. <div className="flex items-center justify-between">
  370. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  371. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  372. </div>
  373. {/* Type */}
  374. {typeFull && (
  375. <div className="flex items-center justify-between">
  376. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  377. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  378. </div>
  379. )}
  380. {/* Flow (hide if empty) */}
  381. {flowFull && (
  382. <div className="flex items-center justify-between">
  383. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  384. <span className="text-xs text-white font-semibold">{flowFull}</span>
  385. </div>
  386. )}
  387. {/* Status badge */}
  388. <div className="flex items-center justify-between">
  389. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  390. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  391. activeStatus || isMounted
  392. ? 'bg-green-900/50 text-green-400'
  393. : 'bg-bambu-dark-tertiary text-bambu-gray'
  394. }`}>
  395. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  396. </span>
  397. </div>
  398. {/* Wear (hide if null) */}
  399. {slot.wear != null && (
  400. <div className="flex items-center justify-between">
  401. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  402. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  403. </div>
  404. )}
  405. {/* Max Temp (hide if 0) */}
  406. {slot.max_temp > 0 && (
  407. <div className="flex items-center justify-between">
  408. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  409. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  410. </div>
  411. )}
  412. {/* Serial (hide if empty) */}
  413. {slot.serial_number && (
  414. <div className="flex items-center justify-between">
  415. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  416. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  417. </div>
  418. )}
  419. {/* Filament: material type + color swatch (hide if no color) */}
  420. {(filamentCss || slot.filament_type) && (
  421. <div className="flex items-center justify-between">
  422. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  423. <div className="flex items-center gap-1">
  424. {filamentCss && (
  425. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  426. )}
  427. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  428. </div>
  429. </div>
  430. )}
  431. </div>
  432. )}
  433. </div>
  434. {/* Arrow pointer */}
  435. <div
  436. className={`
  437. absolute left-1/2 -translate-x-1/2 w-0 h-0
  438. border-l-[6px] border-l-transparent
  439. border-r-[6px] border-r-transparent
  440. ${position === 'top'
  441. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  442. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  443. `}
  444. />
  445. </div>
  446. )}
  447. </div>
  448. );
  449. }
  450. // Dual-nozzle hover card showing L and R nozzle details side by side
  451. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  452. leftSlot?: import('../api/client').NozzleRackSlot;
  453. rightSlot?: import('../api/client').NozzleRackSlot;
  454. activeNozzle: 'L' | 'R';
  455. filamentInfo?: Record<string, { name: string; k: number | null }>;
  456. children: React.ReactNode;
  457. }) {
  458. const { t } = useTranslation();
  459. const [isVisible, setIsVisible] = useState(false);
  460. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  461. const triggerRef = useRef<HTMLDivElement>(null);
  462. const cardRef = useRef<HTMLDivElement>(null);
  463. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  464. useEffect(() => {
  465. if (isVisible && triggerRef.current && cardRef.current) {
  466. const triggerRect = triggerRef.current.getBoundingClientRect();
  467. const cardHeight = cardRef.current.offsetHeight;
  468. const headerHeight = 56;
  469. const spaceAbove = triggerRect.top - headerHeight;
  470. const spaceBelow = window.innerHeight - triggerRect.bottom;
  471. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  472. setPosition('bottom');
  473. } else {
  474. setPosition('top');
  475. }
  476. }
  477. }, [isVisible]);
  478. const handleMouseEnter = () => {
  479. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  480. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  481. };
  482. const handleMouseLeave = () => {
  483. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  484. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  485. };
  486. useEffect(() => {
  487. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  488. }, []);
  489. if (!leftSlot && !rightSlot) return <>{children}</>;
  490. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  491. const isActive = activeNozzle === side;
  492. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  493. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  494. const filamentCss = parseFilamentColor(slot.filament_color);
  495. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  496. return (
  497. <div className="flex-1 space-y-1.5">
  498. <div className={`text-[length:var(--pc-t10,10px)] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  499. {side === 'L' ? t('common.left') : t('common.right')}
  500. </div>
  501. {slot.nozzle_diameter && (
  502. <div className="flex items-center justify-between">
  503. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  504. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  505. </div>
  506. )}
  507. {typeFull && (
  508. <div className="flex items-center justify-between">
  509. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  510. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  511. </div>
  512. )}
  513. {flowFull && (
  514. <div className="flex items-center justify-between">
  515. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  516. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  517. </div>
  518. )}
  519. <div className="flex items-center justify-between">
  520. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  521. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  522. isActive
  523. ? 'bg-green-900/50 text-green-400'
  524. : 'bg-bambu-dark-tertiary text-bambu-gray'
  525. }`}>
  526. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  527. </span>
  528. </div>
  529. {slot.wear != null && (
  530. <div className="flex items-center justify-between">
  531. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  532. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  533. </div>
  534. )}
  535. {/* Serial and max temp only available on the right (removable) nozzle */}
  536. {side === 'R' && slot.max_temp > 0 && (
  537. <div className="flex items-center justify-between">
  538. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  539. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  540. </div>
  541. )}
  542. {side === 'R' && slot.serial_number && (
  543. <div className="flex items-center justify-between">
  544. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  545. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  546. </div>
  547. )}
  548. {(filamentCss || slot.filament_type || slot.filament_id) && (
  549. <div className="flex items-center justify-between">
  550. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  551. <div className="flex items-center gap-1">
  552. {filamentCss && (
  553. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  554. )}
  555. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  556. {filamentName || slot.filament_type || slot.filament_id || ''}
  557. </span>
  558. </div>
  559. </div>
  560. )}
  561. </div>
  562. );
  563. };
  564. return (
  565. <div
  566. ref={triggerRef}
  567. className="relative flex-1"
  568. onMouseEnter={handleMouseEnter}
  569. onMouseLeave={handleMouseLeave}
  570. >
  571. {children}
  572. {isVisible && (
  573. <div
  574. ref={cardRef}
  575. className={`
  576. absolute left-1/2 -translate-x-1/2 z-50
  577. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  578. animate-in fade-in-0 zoom-in-95 duration-150
  579. `}
  580. style={{ maxWidth: 'calc(100vw - 24px)' }}
  581. >
  582. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  583. <div className="p-2.5 flex gap-3">
  584. {leftSlot && renderColumn(leftSlot, 'L')}
  585. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  586. {rightSlot && renderColumn(rightSlot, 'R')}
  587. </div>
  588. </div>
  589. {/* Arrow pointer */}
  590. <div
  591. className={`
  592. absolute left-1/2 -translate-x-1/2 w-0 h-0
  593. border-l-[6px] border-l-transparent
  594. border-r-[6px] border-r-transparent
  595. ${position === 'top'
  596. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  597. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  598. `}
  599. />
  600. </div>
  601. )}
  602. </div>
  603. );
  604. }
  605. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  606. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  607. const { t } = useTranslation();
  608. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  609. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  610. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  611. // base — computing it from min(present IDs) shifts everything left when slot 16
  612. // is the one currently mounted (#943).
  613. const rackNozzles = slots.filter(s => s.id >= 2);
  614. const RACK_SIZE = 6;
  615. const RACK_BASE_ID = 16;
  616. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  617. { length: RACK_SIZE },
  618. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  619. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  620. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  621. },
  622. );
  623. return (
  624. // Sized to its contents rather than growing: the six chips are a fixed
  625. // width at any one card size, so extra width would be dead space taken
  626. // from the temperature cards beside it — which are flex-1 with a 0 basis
  627. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  628. // stays enabled so the card still gives way on a narrow printer card
  629. // instead of overflowing.
  630. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  631. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  632. <div className="flex gap-[3px] justify-center">
  633. {rackSlots.map((slot, i) => {
  634. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  635. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  636. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  637. return (
  638. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  639. <div className="flex flex-col items-center gap-0.5">
  640. <div
  641. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  642. isEmpty
  643. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  644. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  645. }`}
  646. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  647. >
  648. <span
  649. data-rack-diameter
  650. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  651. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  652. >
  653. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  654. </span>
  655. </div>
  656. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  657. acted on without counting chips. Sits below the chip rather
  658. than inside it: the chip is barely wider than its own
  659. diameter text and already carries that over a
  660. filament-coloured background. */}
  661. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  662. {i + 1}
  663. </span>
  664. </div>
  665. </NozzleSlotHoverCard>
  666. );
  667. })}
  668. </div>
  669. </div>
  670. );
  671. }
  672. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  673. function WaterDropEmpty({ className }: { className?: string }) {
  674. return (
  675. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  676. <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"/>
  677. </svg>
  678. );
  679. }
  680. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  681. function WaterDropHalf({ className }: { className?: string }) {
  682. return (
  683. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  684. <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"/>
  685. <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"/>
  686. </svg>
  687. );
  688. }
  689. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  690. function WaterDropFull({ className }: { className?: string }) {
  691. return (
  692. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  693. <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"/>
  694. <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"/>
  695. </svg>
  696. );
  697. }
  698. // Thermometer SVG - empty outline
  699. function ThermometerEmpty({ className }: { className?: string }) {
  700. return (
  701. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  702. <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"/>
  703. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  704. </svg>
  705. );
  706. }
  707. // Thermometer SVG - half filled (gold - same as humidity fair)
  708. function ThermometerHalf({ className }: { className?: string }) {
  709. return (
  710. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  711. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  712. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  713. <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"/>
  714. </svg>
  715. );
  716. }
  717. // Thermometer SVG - fully filled (red - same as humidity bad)
  718. function ThermometerFull({ className }: { className?: string }) {
  719. return (
  720. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  721. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  722. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  723. <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"/>
  724. </svg>
  725. );
  726. }
  727. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  728. // Added for visual parity with the thermometer icons on the dual-nozzle card
  729. // that previously had no icon at all (#1115, design by @m4rtini2).
  730. function NozzleIcon({ className }: { className?: string }) {
  731. return (
  732. <svg
  733. className={className}
  734. viewBox="0 0 24 24"
  735. fill="none"
  736. xmlns="http://www.w3.org/2000/svg"
  737. stroke="currentColor"
  738. strokeWidth="1.5"
  739. strokeLinecap="round"
  740. strokeLinejoin="round"
  741. >
  742. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  743. <rect x="6" y="11.5" width="12.1" height="3.7" />
  744. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  745. </svg>
  746. );
  747. }
  748. // Heater thermometer icon - filled when heating, outline when off
  749. interface HeaterThermometerProps {
  750. className?: string;
  751. color: string; // The color class (e.g., "text-orange-400")
  752. isHeating: boolean;
  753. }
  754. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  755. // Extract the actual color from Tailwind class for SVG fill
  756. const colorMap: Record<string, string> = {
  757. 'text-orange-400': '#fb923c',
  758. 'text-blue-400': '#60a5fa',
  759. 'text-green-400': '#4ade80',
  760. };
  761. const fillColor = colorMap[color] || '#888';
  762. // Glow style when heating
  763. const glowStyle = isHeating ? {
  764. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  765. } : {};
  766. if (isHeating) {
  767. // Filled thermometer with glow - heater is ON
  768. return (
  769. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  770. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  771. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  772. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  773. </svg>
  774. );
  775. }
  776. // Empty thermometer - heater is OFF
  777. return (
  778. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  779. <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"/>
  780. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  781. </svg>
  782. );
  783. }
  784. // AMS Filament Backup tri-state indicator + toggle.
  785. // state=true → ON, click to disable
  786. // state=false → OFF, click opens modal
  787. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  788. interface AmsBackupBadgeProps {
  789. state: boolean | null;
  790. onClick: () => void;
  791. }
  792. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  793. const { t } = useTranslation();
  794. const known = state !== null;
  795. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  796. let title: string;
  797. if (state === true) {
  798. className += known
  799. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  800. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  801. title = t('printers.amsBackup.titleOn');
  802. } else if (state === false) {
  803. className += known
  804. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  805. : 'bg-bambu-dark text-bambu-gray cursor-default';
  806. title = t('printers.amsBackup.titleOff');
  807. } else {
  808. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  809. title = t('printers.amsBackup.titleUnknown');
  810. }
  811. return (
  812. <button
  813. type="button"
  814. disabled={!known}
  815. onClick={() => known && onClick()}
  816. className={className}
  817. title={title}
  818. aria-label={title}
  819. >
  820. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  821. </button>
  822. );
  823. }
  824. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  825. // like AmsBackupBadge so the two sit together in the section header, but
  826. // pinned to the right-hand end of the rule: this is a view preference for the
  827. // row, not a property of the printer.
  828. interface ExternalSpoolToggleProps {
  829. hidden: boolean;
  830. onClick: () => void;
  831. }
  832. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  833. const { t } = useTranslation();
  834. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  835. return (
  836. <button
  837. type="button"
  838. onClick={onClick}
  839. aria-pressed={hidden}
  840. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  841. hidden
  842. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  843. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  844. }`}
  845. title={title}
  846. aria-label={title}
  847. >
  848. {hidden ? <EyeOff className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Eye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  849. </button>
  850. );
  851. }
  852. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  853. // Reference: https://github.com/theicedmango/bambu-humidity
  854. interface HumidityIndicatorProps {
  855. humidity: number | string;
  856. goodThreshold?: number; // <= this is green
  857. fairThreshold?: number; // <= this is orange, > is red
  858. onClick?: () => void;
  859. compact?: boolean; // Smaller version for grid layout
  860. }
  861. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  862. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  863. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  864. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  865. // Status thresholds (configurable via settings)
  866. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  867. let textColor: string;
  868. let statusText: string;
  869. if (isNaN(humidityValue)) {
  870. textColor = '#C3C2C1';
  871. statusText = 'Unknown';
  872. } else if (humidityValue <= good) {
  873. textColor = '#22a352'; // Green - Good
  874. statusText = 'Good';
  875. } else if (humidityValue <= fair) {
  876. textColor = '#d4a017'; // Gold - Fair
  877. statusText = 'Fair';
  878. } else {
  879. textColor = '#c62828'; // Red - Bad
  880. statusText = 'Bad';
  881. }
  882. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  883. let DropComponent: React.FC<{ className?: string }>;
  884. if (isNaN(humidityValue)) {
  885. DropComponent = WaterDropEmpty;
  886. } else if (humidityValue <= good) {
  887. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  888. } else if (humidityValue <= fair) {
  889. DropComponent = WaterDropHalf; // Fair - half filled
  890. } else {
  891. DropComponent = WaterDropFull; // Bad - full (too humid)
  892. }
  893. return (
  894. <button
  895. type="button"
  896. onClick={onClick}
  897. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  898. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  899. >
  900. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  901. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  902. </button>
  903. );
  904. }
  905. // Temperature indicator with dynamic icon and coloring
  906. interface TemperatureIndicatorProps {
  907. temp: number;
  908. goodThreshold?: number; // <= this is blue
  909. fairThreshold?: number; // <= this is orange, > is red
  910. onClick?: () => void;
  911. compact?: boolean; // Smaller version for grid layout
  912. }
  913. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  914. // Ensure thresholds are numbers
  915. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  916. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  917. let textColor: string;
  918. let statusText: string;
  919. let ThermoComponent: React.FC<{ className?: string }>;
  920. if (temp <= good) {
  921. textColor = '#22a352'; // Green - good (same as humidity)
  922. statusText = 'Good';
  923. ThermoComponent = ThermometerEmpty;
  924. } else if (temp <= fair) {
  925. textColor = '#d4a017'; // Gold - fair (same as humidity)
  926. statusText = 'Fair';
  927. ThermoComponent = ThermometerHalf;
  928. } else {
  929. textColor = '#c62828'; // Red - bad (same as humidity)
  930. statusText = 'Bad';
  931. ThermoComponent = ThermometerFull;
  932. }
  933. return (
  934. <button
  935. type="button"
  936. onClick={onClick}
  937. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  938. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  939. >
  940. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  941. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  942. </button>
  943. );
  944. }
  945. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  946. *
  947. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  948. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  949. * every empty-by-bitmask slot lands here regardless of firmware payload
  950. * shape.
  951. *
  952. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  953. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  954. * the user cleared with "Reset Slot" where a physical spool may still be
  955. * loaded but unassigned.
  956. *
  957. * Returns null when the slot is loaded (tray_type is present).
  958. */
  959. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  960. if (tray?.tray_type) return null;
  961. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  962. // spool the firmware can't identify is physically present (exists === true)
  963. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  964. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  965. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  966. if (tray?.exists === true) return 'reset';
  967. if (tray?.exists === false) return 'physical';
  968. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  969. }
  970. // How long to wait for an AMS to report a live drying cycle after the printer
  971. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  972. // within a couple of seconds; 30s covers the slowest observed push cadence
  973. // without leaving the user waiting on a verdict.
  974. const DRY_START_CONFIRM_MS = 30_000;
  975. export function CoverImage({
  976. url,
  977. printName,
  978. className = 'w-20 h-20',
  979. radiusClass = 'rounded-lg',
  980. }: {
  981. url: string | null;
  982. printName?: string;
  983. className?: string;
  984. radiusClass?: string;
  985. }) {
  986. const { t } = useTranslation();
  987. const [loaded, setLoaded] = useState(false);
  988. const [error, setError] = useState(false);
  989. const [showOverlay, setShowOverlay] = useState(false);
  990. const imgRef = useRef<HTMLImageElement>(null);
  991. // Cache-bust the image URL when the print name changes so the browser
  992. // fetches the new cover instead of serving the stale cached image.
  993. const cacheBustedUrl = useMemo(() => {
  994. if (!url) return null;
  995. const sep = url.includes('?') ? '&' : '?';
  996. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  997. }, [url, printName]);
  998. // Re-evaluate load state when the image URL changes, and ask the element
  999. // whether it is already showing something rather than assuming it is not.
  1000. //
  1001. // `onLoad` used to be the only thing that could set `loaded`, and this
  1002. // effect reset it to false unconditionally. That is right when the URL
  1003. // really changes, but it also runs on mount — and the two are not the same
  1004. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1005. // constant for the duration of a print, so navigating away from the
  1006. // printers page and back re-mounts with a byte-identical src that the
  1007. // browser serves from its in-memory cache. The `load` event for a cache hit
  1008. // and React's passive-effect flush are both plain tasks with no ordering
  1009. // between them, so when `load` won, this effect ran afterwards and undid
  1010. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1011. // sat there until a full reload. Nothing recovered it, because the URL
  1012. // never changes again during the print and so this effect never re-runs.
  1013. //
  1014. // Being a race, it reproduced every time for #2826's reporter and not at
  1015. // all here, which is also why the network panel showed no request: there
  1016. // was no request to show.
  1017. //
  1018. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1019. // which of the two ran first. It is also correct for the case the reporter
  1020. // proposed (a `load` that fires before React's handler is live), so the
  1021. // fix stands whichever mechanism is really at work.
  1022. useEffect(() => {
  1023. setError(false);
  1024. const el = imgRef.current;
  1025. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1026. }, [cacheBustedUrl]);
  1027. return (
  1028. <>
  1029. <div
  1030. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1031. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1032. >
  1033. {cacheBustedUrl && !error ? (
  1034. <>
  1035. <img
  1036. ref={imgRef}
  1037. src={cacheBustedUrl}
  1038. alt={t('printers.printPreview')}
  1039. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1040. onLoad={() => setLoaded(true)}
  1041. onError={() => setError(true)}
  1042. />
  1043. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1044. </>
  1045. ) : (
  1046. <Box className="w-8 h-8 text-bambu-gray" />
  1047. )}
  1048. </div>
  1049. {/* Cover Image Overlay */}
  1050. {showOverlay && cacheBustedUrl && (
  1051. <div
  1052. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1053. onClick={() => setShowOverlay(false)}
  1054. >
  1055. <div className="relative max-w-2xl max-h-full">
  1056. <img
  1057. src={cacheBustedUrl}
  1058. alt={t('printers.printPreview')}
  1059. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1060. />
  1061. {printName && (
  1062. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1063. )}
  1064. </div>
  1065. </div>
  1066. )}
  1067. </>
  1068. );
  1069. }
  1070. interface PrinterMaintenanceInfo {
  1071. due_count: number;
  1072. warning_count: number;
  1073. total_print_hours: number;
  1074. }
  1075. // Status summary bar component - uses queryClient to read cached statuses
  1076. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1077. const { t } = useTranslation();
  1078. const queryClient = useQueryClient();
  1079. // Subscribe to query cache changes to re-render when status updates
  1080. // Throttled to prevent rapid re-renders from causing tab crashes
  1081. const [cacheTick, setCacheTick] = useState(0);
  1082. useEffect(() => {
  1083. let pending = false;
  1084. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1085. if (!pending) {
  1086. pending = true;
  1087. requestAnimationFrame(() => {
  1088. setCacheTick(t => t + 1);
  1089. pending = false;
  1090. });
  1091. }
  1092. });
  1093. return () => unsubscribe();
  1094. }, [queryClient]);
  1095. const { counts, nextFinish } = useMemo(() => {
  1096. let printing = 0;
  1097. let paused = 0;
  1098. let finished = 0;
  1099. let idle = 0;
  1100. let offline = 0;
  1101. let loading = 0;
  1102. let error = 0;
  1103. let nextPrinterName: string | null = null;
  1104. let nextRemainingMin: number | null = null;
  1105. let nextProgress: number = 0;
  1106. printers?.forEach((printer) => {
  1107. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1108. if (status === undefined) {
  1109. // Status not yet loaded - don't count as offline yet
  1110. loading++;
  1111. } else if (!status.connected) {
  1112. offline++;
  1113. } else {
  1114. // Count printers with active HMS errors as problems
  1115. const knownHmsCount =
  1116. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1117. if (knownHmsCount > 0) {
  1118. error++;
  1119. }
  1120. switch (status.state) {
  1121. case 'RUNNING':
  1122. printing++;
  1123. if (status.remaining_time != null && status.remaining_time > 0) {
  1124. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1125. nextRemainingMin = status.remaining_time;
  1126. nextPrinterName = printer.name;
  1127. nextProgress = status.progress || 0;
  1128. }
  1129. }
  1130. break;
  1131. case 'PAUSE':
  1132. paused++;
  1133. break;
  1134. case 'FINISH':
  1135. finished++;
  1136. break;
  1137. case 'FAILED':
  1138. // FAILED is the printer's terminal gcode_state after a print stops —
  1139. // including user cancellations, where there's no actual fault. Only
  1140. // count it as a "problem" when an HMS error is also active; otherwise
  1141. // it's just a print that ended unsuccessfully and the plate needs
  1142. // clearing (same as FINISH from the operator's perspective).
  1143. if (knownHmsCount > 0) {
  1144. // Already counted above
  1145. } else {
  1146. finished++;
  1147. }
  1148. break;
  1149. default:
  1150. idle++;
  1151. break;
  1152. }
  1153. }
  1154. });
  1155. return {
  1156. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1157. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1158. };
  1159. // eslint-disable-next-line react-hooks/exhaustive-deps
  1160. }, [printers, queryClient, cacheTick]);
  1161. if (!printers?.length) return null;
  1162. const badges: { count: number; dot: string; label: string }[] = [
  1163. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1164. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1165. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1166. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1167. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1168. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1169. ];
  1170. return (
  1171. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1172. {badges.map(({ count, dot, label }) => count > 0 && (
  1173. <div key={label} className="flex items-center gap-1.5">
  1174. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1175. <span className="text-bambu-gray">
  1176. <span className="text-white font-medium">{count}</span> {label}
  1177. </span>
  1178. </div>
  1179. ))}
  1180. {nextFinish && (
  1181. <>
  1182. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1183. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1184. <div className="flex items-center gap-2">
  1185. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1186. <span className="text-white font-medium">{nextFinish.name}</span>
  1187. </div>
  1188. <div className="flex items-center gap-2 w-full sm:w-auto">
  1189. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1190. <div
  1191. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1192. style={{ width: `${nextFinish.progress}%` }}
  1193. />
  1194. </div>
  1195. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1196. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1197. </div>
  1198. </div>
  1199. </>
  1200. )}
  1201. </div>
  1202. );
  1203. }
  1204. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1205. type ViewMode = 'expanded' | 'compact';
  1206. type ToolbarDropdownOption<T extends string> = {
  1207. value: T;
  1208. label: string;
  1209. };
  1210. function ToolbarDropdown<T extends string>({
  1211. value,
  1212. options,
  1213. onChange,
  1214. fullWidth = false,
  1215. }: {
  1216. value: T;
  1217. options: ToolbarDropdownOption<T>[];
  1218. onChange: (value: T) => void;
  1219. fullWidth?: boolean;
  1220. }) {
  1221. const [isOpen, setIsOpen] = useState(false);
  1222. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1223. return (
  1224. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1225. <button
  1226. type="button"
  1227. onClick={() => setIsOpen(open => !open)}
  1228. 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'}`}
  1229. >
  1230. <span className="truncate">{selectedOption?.label}</span>
  1231. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1232. </button>
  1233. {isOpen && (
  1234. <>
  1235. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1236. <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">
  1237. {options.map(option => (
  1238. <button
  1239. key={option.value}
  1240. type="button"
  1241. onClick={() => {
  1242. onChange(option.value);
  1243. setIsOpen(false);
  1244. }}
  1245. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1246. option.value === value ? 'text-bambu-green' : 'text-white'
  1247. }`}
  1248. >
  1249. {option.label}
  1250. </button>
  1251. ))}
  1252. </div>
  1253. </>
  1254. )}
  1255. </div>
  1256. );
  1257. }
  1258. function ToolbarMenu({
  1259. label,
  1260. icon,
  1261. children,
  1262. }: {
  1263. label: string;
  1264. icon: React.ReactNode;
  1265. children: React.ReactNode;
  1266. }) {
  1267. const [isOpen, setIsOpen] = useState(false);
  1268. return (
  1269. <div className="relative">
  1270. <button
  1271. type="button"
  1272. onClick={() => setIsOpen(open => !open)}
  1273. 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"
  1274. aria-label={label}
  1275. title={label}
  1276. >
  1277. {icon}
  1278. </button>
  1279. {isOpen && (
  1280. <>
  1281. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1282. <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">
  1283. {children}
  1284. </div>
  1285. </>
  1286. )}
  1287. </div>
  1288. );
  1289. }
  1290. function IndicatorControlPopover({
  1291. title,
  1292. options = [],
  1293. unit,
  1294. customMin,
  1295. customMax,
  1296. customStep = 1,
  1297. widthClass = 'w-[240px]',
  1298. popoverWidth = 240,
  1299. popoverHeight = 280,
  1300. isPending,
  1301. onClose,
  1302. onSubmit,
  1303. children,
  1304. }: {
  1305. title: string;
  1306. options?: Array<{ label: string; value: number }>;
  1307. unit?: string;
  1308. customMin?: number;
  1309. customMax?: number;
  1310. customStep?: number;
  1311. widthClass?: string;
  1312. popoverWidth?: number;
  1313. popoverHeight?: number;
  1314. isPending?: boolean;
  1315. onClose: () => void;
  1316. onSubmit?: (value: number) => void;
  1317. children?: React.ReactNode;
  1318. }) {
  1319. const anchorRef = useRef<HTMLSpanElement>(null);
  1320. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1321. const [customValue, setCustomValue] = useState('');
  1322. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1323. // can position via fixed coords. Portaling to document.body escapes
  1324. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1325. // own contexts and would otherwise cover the popover even at z-[60].
  1326. useLayoutEffect(() => {
  1327. const trigger = anchorRef.current?.parentElement;
  1328. if (!trigger) return;
  1329. const measure = () => {
  1330. const rect = trigger.getBoundingClientRect();
  1331. setCoords(computePopoverPosition({
  1332. triggerRect: rect,
  1333. popoverWidth,
  1334. estimatedHeight: popoverHeight,
  1335. horizontalAlign: 'center',
  1336. }));
  1337. };
  1338. measure();
  1339. window.addEventListener('resize', measure);
  1340. window.addEventListener('scroll', measure, true);
  1341. return () => {
  1342. window.removeEventListener('resize', measure);
  1343. window.removeEventListener('scroll', measure, true);
  1344. };
  1345. }, [popoverWidth, popoverHeight]);
  1346. const showCustomInput = unit !== undefined;
  1347. const submitCustom = () => {
  1348. const value = Number(customValue);
  1349. if (!Number.isFinite(value)) return;
  1350. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1351. onSubmit?.(Math.round(bounded));
  1352. };
  1353. return (
  1354. <>
  1355. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1356. {createPortal(
  1357. <>
  1358. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1359. <div
  1360. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1361. style={{
  1362. top: coords?.top ?? -9999,
  1363. left: coords?.left ?? -9999,
  1364. visibility: coords ? 'visible' : 'hidden',
  1365. }}
  1366. onClick={e => e.stopPropagation()}
  1367. >
  1368. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1369. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1370. {options.length > 0 && (
  1371. <div className="px-3 py-2.5">
  1372. <div className="grid grid-cols-2 gap-1.5">
  1373. {options.map(option => (
  1374. <button
  1375. key={`${option.label}-${option.value}`}
  1376. type="button"
  1377. disabled={isPending}
  1378. onClick={() => onSubmit?.(option.value)}
  1379. 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"
  1380. >
  1381. {option.label}
  1382. </button>
  1383. ))}
  1384. </div>
  1385. </div>
  1386. )}
  1387. {children}
  1388. {showCustomInput && (
  1389. <>
  1390. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1391. <form
  1392. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1393. onSubmit={(e) => {
  1394. e.preventDefault();
  1395. submitCustom();
  1396. }}
  1397. >
  1398. <input
  1399. type="number"
  1400. min={customMin}
  1401. max={customMax}
  1402. step={customStep}
  1403. value={customValue}
  1404. onChange={e => setCustomValue(e.target.value)}
  1405. placeholder="Custom"
  1406. 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"
  1407. />
  1408. <button
  1409. type="submit"
  1410. disabled={isPending || customValue.trim() === ''}
  1411. 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"
  1412. >
  1413. Set
  1414. </button>
  1415. </form>
  1416. </>
  1417. )}
  1418. </div>
  1419. </>,
  1420. document.body
  1421. )}
  1422. </>
  1423. );
  1424. }
  1425. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1426. function NozzleTemperatureControlBox({
  1427. label,
  1428. current,
  1429. target,
  1430. isActive,
  1431. isPending,
  1432. onSubmit,
  1433. options = NOZZLE_TEMPERATURE_OPTIONS,
  1434. }: {
  1435. label: string;
  1436. current?: number;
  1437. target?: number;
  1438. isActive: boolean;
  1439. isPending?: boolean;
  1440. onSubmit: (value: number) => void;
  1441. options?: Array<{ label: string; value: number }>;
  1442. }) {
  1443. const [customValue, setCustomValue] = useState('');
  1444. const submitCustom = () => {
  1445. const value = Number(customValue);
  1446. if (!Number.isFinite(value)) return;
  1447. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1448. };
  1449. return (
  1450. <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'}`}>
  1451. <div className="mb-1.5 flex items-center justify-between gap-2">
  1452. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1453. <span className="text-[10px] text-bambu-gray">
  1454. {Math.round(current ?? 0)}°C
  1455. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1456. </span>
  1457. </div>
  1458. <div className="grid grid-cols-2 gap-1">
  1459. {options.map(option => (
  1460. <button
  1461. key={`${label}-${option.value}`}
  1462. type="button"
  1463. disabled={isPending}
  1464. onClick={() => onSubmit(option.value)}
  1465. 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"
  1466. >
  1467. {option.label}
  1468. </button>
  1469. ))}
  1470. </div>
  1471. <form
  1472. className="mt-1.5 flex gap-1"
  1473. onSubmit={(e) => {
  1474. e.preventDefault();
  1475. submitCustom();
  1476. }}
  1477. >
  1478. <input
  1479. type="number"
  1480. min={0}
  1481. max={320}
  1482. step={1}
  1483. value={customValue}
  1484. onChange={e => setCustomValue(e.target.value)}
  1485. placeholder="Custom"
  1486. 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"
  1487. />
  1488. <button
  1489. type="submit"
  1490. disabled={isPending || customValue.trim() === ''}
  1491. 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"
  1492. >
  1493. Set
  1494. </button>
  1495. </form>
  1496. </div>
  1497. );
  1498. }
  1499. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1500. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1501. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1502. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1503. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1504. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1505. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1506. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1507. };
  1508. /** Classify a printer into one of the UI status buckets. */
  1509. function classifyPrinterStatus(
  1510. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1511. ): PrinterState {
  1512. if (!status?.connected) return 'offline';
  1513. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1514. if (hmsErrors.length > 0) return 'error';
  1515. switch (status.state) {
  1516. case 'RUNNING': return 'printing';
  1517. case 'PAUSE': return 'paused';
  1518. case 'FINISH': return 'finished';
  1519. // FAILED without an active HMS error is the printer's terminal state after
  1520. // any unsuccessful end — including user-cancellations. Treat the same as
  1521. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1522. // HMS code is actually attached (handled by the early-return above).
  1523. case 'FAILED': return 'finished';
  1524. default: return 'idle';
  1525. }
  1526. }
  1527. /**
  1528. * Get human-readable status display text for a printer.
  1529. * Uses stg_cur_name for detailed calibration/preparation stages,
  1530. * otherwise formats the gcode_state nicely.
  1531. */
  1532. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1533. // If we have a specific stage name (calibration, heating, etc.), use it
  1534. if (stg_cur_name) {
  1535. return stg_cur_name;
  1536. }
  1537. // Format the gcode_state nicely
  1538. switch (state) {
  1539. case 'RUNNING':
  1540. return 'Printing';
  1541. case 'PAUSE':
  1542. return 'Paused';
  1543. case 'FINISH':
  1544. return 'Finished';
  1545. case 'FAILED':
  1546. return 'Failed';
  1547. case 'IDLE':
  1548. return 'Idle';
  1549. default:
  1550. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1551. }
  1552. }
  1553. // Bambu models that ship with an enclosure chamber fan (firmware field
  1554. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1555. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1556. // widget is hidden in fanItems instead of rendered greyed-out.
  1557. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1558. 'X1C',
  1559. 'X1',
  1560. 'X1E',
  1561. 'X2D',
  1562. 'P1S',
  1563. 'P2S',
  1564. 'H2D',
  1565. 'H2D Pro',
  1566. 'H2C',
  1567. 'H2S',
  1568. ]);
  1569. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1570. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1571. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1572. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1573. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1574. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1575. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1576. 'P2S',
  1577. 'X2D',
  1578. ]);
  1579. // Map SSDP model codes to display names
  1580. function mapModelCode(ssdpModel: string | null): string {
  1581. if (!ssdpModel) return '';
  1582. const modelMap: Record<string, string> = {
  1583. // H2 Series
  1584. 'O1D': 'H2D',
  1585. 'O1E': 'H2D Pro',
  1586. 'O2D': 'H2D Pro',
  1587. 'O1C': 'H2C',
  1588. 'O1C2': 'H2C',
  1589. 'O1S': 'H2S',
  1590. // X1 Series
  1591. 'BL-P001': 'X1C',
  1592. 'BL-P002': 'X1',
  1593. 'BL-P003': 'X1E',
  1594. // X2 Series
  1595. 'N6': 'X2D',
  1596. // A2 Series
  1597. 'N9': 'A2L',
  1598. // P Series
  1599. 'C11': 'P1S',
  1600. 'C12': 'P1P',
  1601. 'C13': 'P2S',
  1602. // A1 Series
  1603. 'N2S': 'A1',
  1604. 'N1': 'A1 Mini',
  1605. // Direct matches
  1606. 'X1C': 'X1C',
  1607. 'X1': 'X1',
  1608. 'X1E': 'X1E',
  1609. 'X2D': 'X2D',
  1610. 'P1S': 'P1S',
  1611. 'P1P': 'P1P',
  1612. 'P2S': 'P2S',
  1613. 'A1': 'A1',
  1614. 'A1 Mini': 'A1 Mini',
  1615. 'A2L': 'A2L',
  1616. 'H2D': 'H2D',
  1617. 'H2D Pro': 'H2D Pro',
  1618. 'H2C': 'H2C',
  1619. 'H2S': 'H2S',
  1620. };
  1621. return modelMap[ssdpModel] || ssdpModel;
  1622. }
  1623. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1624. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1625. // • User-defined friendly name (editable, protected by printers:update)
  1626. // • AMS serial number
  1627. // • AMS firmware version
  1628. export function AmsNameHoverCard({
  1629. ams,
  1630. printerId,
  1631. label,
  1632. amsLabels,
  1633. canEdit,
  1634. onSaved,
  1635. children,
  1636. }: {
  1637. ams: import('../api/client').AMSUnit;
  1638. printerId: number;
  1639. label: string; // auto-generated label, e.g. "AMS-A"
  1640. amsLabels?: Record<number, string>;
  1641. canEdit: boolean;
  1642. onSaved: () => void;
  1643. children: React.ReactNode;
  1644. }) {
  1645. const { t } = useTranslation();
  1646. const [isVisible, setIsVisible] = useState(false);
  1647. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1648. const [editValue, setEditValue] = useState('');
  1649. const [isSaving, setIsSaving] = useState(false);
  1650. const [saveError, setSaveError] = useState<string | null>(null);
  1651. const [isInputFocused, setIsInputFocused] = useState(false);
  1652. const triggerRef = useRef<HTMLDivElement>(null);
  1653. const cardRef = useRef<HTMLDivElement>(null);
  1654. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1655. useEffect(() => {
  1656. if (isVisible) {
  1657. setEditValue(amsLabels?.[ams.id] ?? '');
  1658. setSaveError(null);
  1659. requestAnimationFrame(() => {
  1660. if (triggerRef.current && cardRef.current) {
  1661. const rect = triggerRef.current.getBoundingClientRect();
  1662. const spaceAbove = rect.top - 56;
  1663. const spaceBelow = window.innerHeight - rect.bottom;
  1664. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1665. }
  1666. });
  1667. }
  1668. }, [isVisible, amsLabels, ams.id]);
  1669. const handleMouseEnter = () => {
  1670. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1671. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1672. };
  1673. const handleMouseLeave = () => {
  1674. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1675. if (!isInputFocused) {
  1676. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1677. }
  1678. };
  1679. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1680. const handleSave = async () => {
  1681. if (!canEdit) return;
  1682. setIsSaving(true);
  1683. setSaveError(null);
  1684. try {
  1685. const trimmed = editValue.trim();
  1686. if (trimmed) {
  1687. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1688. } else {
  1689. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1690. }
  1691. onSaved();
  1692. setIsVisible(false);
  1693. } catch (err) {
  1694. setSaveError(err instanceof Error ? err.message : String(err));
  1695. } finally {
  1696. setIsSaving(false);
  1697. }
  1698. };
  1699. const handleClear = async () => {
  1700. if (!canEdit) return;
  1701. setIsSaving(true);
  1702. setSaveError(null);
  1703. try {
  1704. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1705. onSaved();
  1706. setIsVisible(false);
  1707. } catch (err) {
  1708. setSaveError(err instanceof Error ? err.message : String(err));
  1709. } finally {
  1710. setIsSaving(false);
  1711. }
  1712. };
  1713. return (
  1714. <div
  1715. ref={triggerRef}
  1716. className="relative inline-block"
  1717. onMouseEnter={handleMouseEnter}
  1718. onMouseLeave={handleMouseLeave}
  1719. >
  1720. {children}
  1721. {isVisible && (
  1722. <div
  1723. ref={cardRef}
  1724. className={`
  1725. absolute left-0 z-50
  1726. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1727. animate-in fade-in-0 zoom-in-95 duration-150
  1728. `}
  1729. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1730. onMouseEnter={handleMouseEnter}
  1731. onMouseLeave={handleMouseLeave}
  1732. >
  1733. <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">
  1734. {/* AMS auto-label */}
  1735. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1736. {/* Serial number */}
  1737. <div className="flex items-center justify-between gap-2">
  1738. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1739. {t('printers.amsPopup.serialNumber')}
  1740. </span>
  1741. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1742. </div>
  1743. {/* Firmware version */}
  1744. <div className="flex items-center justify-between gap-2">
  1745. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1746. {t('printers.amsPopup.firmwareVersion')}
  1747. </span>
  1748. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1749. </div>
  1750. {/* Friendly name editor */}
  1751. <div className="space-y-1">
  1752. <div className="flex items-center gap-2">
  1753. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1754. {t('printers.amsPopup.friendlyName')}
  1755. </span>
  1756. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1757. </div>
  1758. <input
  1759. type="text"
  1760. value={editValue}
  1761. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1762. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1763. onFocus={() => setIsInputFocused(true)}
  1764. onBlur={() => {
  1765. setIsInputFocused(false);
  1766. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1767. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1768. }}
  1769. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1770. disabled={!canEdit}
  1771. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1772. 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"
  1773. maxLength={100}
  1774. />
  1775. {canEdit && (
  1776. <div className="space-y-1">
  1777. {saveError && (
  1778. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1779. )}
  1780. <div className="flex gap-1 justify-end">
  1781. <button
  1782. onClick={handleSave}
  1783. disabled={isSaving}
  1784. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1785. >
  1786. {t('printers.amsPopup.save')}
  1787. </button>
  1788. {amsLabels?.[ams.id] && (
  1789. <button
  1790. onClick={handleClear}
  1791. disabled={isSaving}
  1792. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1793. >
  1794. {t('printers.amsPopup.clear')}
  1795. </button>
  1796. )}
  1797. </div>
  1798. </div>
  1799. )}
  1800. </div>
  1801. </div>
  1802. </div>
  1803. )}
  1804. </div>
  1805. );
  1806. }
  1807. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1808. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1809. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1810. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1811. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1812. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1813. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1814. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1815. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1816. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1817. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1818. };
  1819. // How much the printer card's body type and icons grow at each card size
  1820. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1821. // 1.0 and an existing install looks identical until the user picks L or XL --
  1822. // the same control the request asked to have this follow.
  1823. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1824. // The scaled sizes, handed to the card subtree as custom properties. Every
  1825. // converted class names its old fixed value as the fallback, so anything that
  1826. // renders outside a card root -- the portalled temperature popover -- keeps
  1827. // exactly the size it has today.
  1828. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1829. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1830. // Rounded to a tenth so the values stay readable in devtools.
  1831. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1832. return {
  1833. '--pc-t8': px(8),
  1834. '--pc-t9': px(9),
  1835. '--pc-t10': px(10),
  1836. '--pc-t11': px(11),
  1837. '--pc-i2': px(8),
  1838. '--pc-i25': px(10),
  1839. '--pc-i3': px(12),
  1840. '--pc-i35': px(14),
  1841. '--pc-i4': px(16),
  1842. '--pc-i5': px(20),
  1843. '--pc-i7': px(28),
  1844. } as React.CSSProperties;
  1845. }
  1846. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1847. const { t } = useTranslation();
  1848. const queryClient = useQueryClient();
  1849. const { showToast } = useToast();
  1850. // One fleet-wide query shared by every card, not one per card: the list is
  1851. // nearly always empty and a 20-printer fleet would otherwise make 20
  1852. // requests every 30s. React Query dedupes on the key.
  1853. const { data: scheduled = [] } = useQuery({
  1854. queryKey: SCHEDULED_DRYINGS_KEY,
  1855. queryFn: () => api.listScheduledDryings(),
  1856. refetchInterval: 30_000,
  1857. });
  1858. // The live AMS status reports a starting cycle well before the next poll;
  1859. // refetch so a just-dispatched schedule doesn't linger as pending.
  1860. useEffect(() => {
  1861. if (dryingActive) {
  1862. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1863. }
  1864. }, [dryingActive, queryClient]);
  1865. const cancelMutation = useMutation({
  1866. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1867. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1868. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1869. });
  1870. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1871. // old firmware on a printer that was offline at schedule time), and without
  1872. // this the run just vanishes with only the backend log saying why.
  1873. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1874. if (rows.length === 0) return null;
  1875. return (
  1876. <div className="mt-2 space-y-1">
  1877. {rows.map(s => {
  1878. const failed = s.status === 'failed';
  1879. const reasonKey = waitingReasonKey(s.waiting_reason);
  1880. return (
  1881. <div
  1882. key={s.id}
  1883. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1884. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1885. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1886. }`}
  1887. >
  1888. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1889. {failed ? (
  1890. t('printers.drying.scheduleFailedReason', {
  1891. reason: s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1892. })
  1893. ) : (
  1894. <>
  1895. {s.start_after
  1896. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1897. : t('printers.drying.scheduledAsap')}
  1898. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1899. </>
  1900. )}
  1901. </span>
  1902. <button
  1903. onClick={() => cancelMutation.mutate(s.id)}
  1904. disabled={cancelMutation.isPending}
  1905. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1906. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1907. >
  1908. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1909. </button>
  1910. </div>
  1911. );
  1912. })}
  1913. </div>
  1914. );
  1915. }
  1916. function PrinterCard({
  1917. printer,
  1918. hideIfDisconnected,
  1919. maintenanceInfo,
  1920. viewMode = 'expanded',
  1921. cardSize = 2,
  1922. amsThresholds,
  1923. spoolmanEnabled = false,
  1924. linkedSpools,
  1925. spoolmanUrl,
  1926. spoolmanSyncMode,
  1927. onGetAssignment,
  1928. onUnassignSpool,
  1929. spoolmanSpools,
  1930. spoolmanSlotAssignments,
  1931. spoolmanLoading = false,
  1932. onUnassignSpoolmanSpool,
  1933. timeFormat = 'system',
  1934. cameraViewMode = 'window',
  1935. onOpenEmbeddedCamera,
  1936. onSelectCameraViewMode,
  1937. checkPrinterFirmware = true,
  1938. dryingPresets = DRYING_PRESETS,
  1939. requirePlateClear = false,
  1940. selectionMode = false,
  1941. isSelected = false,
  1942. onToggleSelect,
  1943. onOpenCompactCard,
  1944. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1945. bedTempPresets = BED_TEMP_DEFAULTS,
  1946. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1947. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1948. aiDetectionEnabled = false,
  1949. aiDetection,
  1950. aiLastError = null,
  1951. }: {
  1952. printer: Printer;
  1953. hideIfDisconnected?: boolean;
  1954. maintenanceInfo?: PrinterMaintenanceInfo;
  1955. viewMode?: ViewMode;
  1956. cardSize?: number;
  1957. amsThresholds?: {
  1958. humidityGood: number;
  1959. humidityFair: number;
  1960. tempGood: number;
  1961. tempFair: number;
  1962. };
  1963. spoolmanEnabled?: boolean;
  1964. hasUnlinkedSpools?: boolean;
  1965. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1966. spoolmanUrl?: string | null;
  1967. spoolmanSyncMode?: string | null;
  1968. spoolAssignments?: SpoolAssignment[];
  1969. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1970. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1971. spoolmanSpools?: InventorySpool[];
  1972. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1973. spoolmanLoading?: boolean;
  1974. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1975. timeFormat?: 'system' | '12h' | '24h';
  1976. cameraViewMode?: CameraViewMode;
  1977. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1978. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  1979. checkPrinterFirmware?: boolean;
  1980. dryingPresets?: Record<string, DryingPreset>;
  1981. requirePlateClear?: boolean;
  1982. selectionMode?: boolean;
  1983. isSelected?: boolean;
  1984. onToggleSelect?: (id: number) => void;
  1985. onOpenCompactCard?: (id: number) => void;
  1986. nozzleTempPresets?: readonly [number, number, number];
  1987. bedTempPresets?: readonly [number, number, number];
  1988. chamberTempPresets?: readonly [number, number, number];
  1989. fanSpeedPresets?: readonly [number, number, number];
  1990. aiDetectionEnabled?: boolean;
  1991. aiDetection?: { class: string; frame_count: number; score: number };
  1992. aiLastError?: string | null;
  1993. }) {
  1994. const { t } = useTranslation();
  1995. const queryClient = useQueryClient();
  1996. const navigate = useNavigate();
  1997. const { showToast } = useToast();
  1998. const { hasPermission } = useAuth();
  1999. const [showMenu, setShowMenu] = useState(false);
  2000. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2001. const [deleteArchives, setDeleteArchives] = useState(true);
  2002. const [showEditModal, setShowEditModal] = useState(false);
  2003. const [showFileManager, setShowFileManager] = useState(false);
  2004. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2005. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2006. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2007. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2008. const [showHMSModal, setShowHMSModal] = useState(false);
  2009. // #1546: AI failure detection modal — opens from the AI badge.
  2010. const [showAiModal, setShowAiModal] = useState(false);
  2011. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2012. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2013. // External spool visibility (#1782) — browser-local, per printer. Read once
  2014. // per card; the toggle that writes it is the only thing that changes it.
  2015. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2016. isExternalSpoolHidden(printer.id),
  2017. );
  2018. const toggleExternalSpool = useCallback(() => {
  2019. setExternalSpoolHidden((prev) => {
  2020. const next = !prev;
  2021. persistExternalSpoolHidden(printer.id, next);
  2022. return next;
  2023. });
  2024. }, [printer.id]);
  2025. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2026. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2027. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2028. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2029. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2030. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2031. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2032. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2033. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2034. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2035. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2036. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2037. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2038. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2039. // AMS drying popover state: which AMS unit has the popover open
  2040. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2041. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2042. const [dryingFilament, setDryingFilament] = useState('PLA');
  2043. const [dryingTemp, setDryingTemp] = useState(50);
  2044. const [dryingDuration, setDryingDuration] = useState(4);
  2045. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2046. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2047. // go through scheduleDryingMutation.
  2048. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2049. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2050. const [dryingStartAt, setDryingStartAt] = useState('');
  2051. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2052. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2053. // Reset every field the popover owns, including the start mode. Leaving the
  2054. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2055. // the next open, by then in the past, and the POST rejected it.
  2056. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2057. const firstTray = ams.tray.find(t => t.tray_type);
  2058. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2059. // Only reachable if a custom preset set dropped PLA itself.
  2060. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2061. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2062. setDryingFilament(filType);
  2063. setDryingTemp(preset[moduleType] || preset.n3f);
  2064. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2065. setDryingRotateTray(false);
  2066. setDryingStartMode('now');
  2067. setDryingDelayMinutes(120);
  2068. setDryingStartAt('');
  2069. setDryingPopoverModuleType(ams.module_type);
  2070. setDryingPopoverAmsId(ams.id);
  2071. setDryingPopoverAnchor(trigger);
  2072. }, [dryingPresets]);
  2073. // Re-measure on resize/scroll so the popover and its arrow track the
  2074. // flame button, like IndicatorControlPopover.
  2075. useLayoutEffect(() => {
  2076. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2077. const measure = () => {
  2078. setDryingPopoverPos(computePopoverPosition({
  2079. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2080. popoverWidth: DRYING_POPOVER_WIDTH,
  2081. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2082. horizontalAlign: 'center',
  2083. }));
  2084. };
  2085. measure();
  2086. window.addEventListener('resize', measure);
  2087. window.addEventListener('scroll', measure, true);
  2088. return () => {
  2089. window.removeEventListener('resize', measure);
  2090. window.removeEventListener('scroll', measure, true);
  2091. };
  2092. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2093. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2094. // Whether the click hitting the backdrop is the one that dismissed the
  2095. // native datetime picker (see the backdrop's onMouseDown).
  2096. const dryingBackdropSkipCloseRef = useRef(false);
  2097. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2098. // an object rather than a bare id so restarting drying on the SAME unit produces
  2099. // a new identity and rearms the timeout below.
  2100. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2101. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2102. const [isDropUploading, setIsDropUploading] = useState(false);
  2103. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2104. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2105. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2106. // inside the card would have to open upward into the card body; anchored to
  2107. // the viewport it escapes the card and the grid's scroll container both.
  2108. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2109. const dragCounterRef = useRef(0);
  2110. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2111. amsId: number;
  2112. amsLabel: string;
  2113. mode: 'humidity' | 'temperature';
  2114. } | null>(null);
  2115. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2116. initialKind: HeaterSensorKind;
  2117. availableKinds: HeaterSensorKind[];
  2118. } | null>(null);
  2119. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2120. tagUid: string;
  2121. trayUuid: string;
  2122. printerId: number;
  2123. amsId: number;
  2124. trayId: number;
  2125. } | null>(null);
  2126. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2127. printerId: number;
  2128. amsId: number;
  2129. trayId: number;
  2130. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2131. } | null>(null);
  2132. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2133. amsId: number;
  2134. trayId: number;
  2135. trayCount: number;
  2136. trayType?: string;
  2137. trayColor?: string;
  2138. traySubBrands?: string;
  2139. trayInfoIdx?: string;
  2140. extruderId?: number;
  2141. caliIdx?: number | null;
  2142. savedPresetId?: string;
  2143. } | null>(null);
  2144. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2145. const [plateCheckResult, setPlateCheckResult] = useState<{
  2146. is_empty: boolean;
  2147. confidence: number;
  2148. difference_percent: number;
  2149. message: string;
  2150. debug_image_url?: string;
  2151. needs_calibration: boolean;
  2152. light_warning?: boolean;
  2153. reference_count?: number;
  2154. max_references?: number;
  2155. roi?: { x: number; y: number; w: number; h: number };
  2156. } | null>(null);
  2157. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2158. const [isCalibrating, setIsCalibrating] = useState(false);
  2159. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2160. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2161. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2162. const { data: status } = useQuery({
  2163. queryKey: ['printerStatus', printer.id],
  2164. queryFn: () => api.getPrinterStatus(printer.id),
  2165. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2166. });
  2167. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2168. const { data: firmwareInfo } = useQuery({
  2169. queryKey: ['firmwareUpdate', printer.id],
  2170. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2171. staleTime: 5 * 60 * 1000,
  2172. refetchInterval: 5 * 60 * 1000,
  2173. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2174. });
  2175. // Collect unique tray_info_idx values for cloud filament info lookup
  2176. const trayInfoIds = useMemo(() => {
  2177. const ids = new Set<string>();
  2178. if (status?.ams) {
  2179. for (const ams of status.ams) {
  2180. for (const tray of ams.tray || []) {
  2181. if (tray.tray_info_idx) {
  2182. ids.add(tray.tray_info_idx);
  2183. }
  2184. }
  2185. }
  2186. }
  2187. for (const vt of status?.vt_tray ?? []) {
  2188. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2189. }
  2190. if (status?.nozzle_rack) {
  2191. for (const slot of status.nozzle_rack) {
  2192. if (slot.filament_id) {
  2193. ids.add(slot.filament_id);
  2194. }
  2195. }
  2196. }
  2197. return Array.from(ids);
  2198. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2199. // Collect loaded filament types for queue widget filtering
  2200. const loadedFilamentTypes = useMemo(() => {
  2201. const types = new Set<string>();
  2202. if (status?.ams) {
  2203. for (const ams of status.ams) {
  2204. for (const tray of ams.tray || []) {
  2205. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2206. }
  2207. }
  2208. }
  2209. for (const vt of status?.vt_tray ?? []) {
  2210. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2211. }
  2212. return types;
  2213. }, [status?.ams, status?.vt_tray]);
  2214. // Collect loaded filament type+color pairs for queue widget override matching
  2215. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2216. const loadedFilaments = useMemo(() => {
  2217. const filaments = new Set<string>();
  2218. if (status?.ams) {
  2219. for (const ams of status.ams) {
  2220. for (const tray of ams.tray || []) {
  2221. if (tray.tray_type && tray.tray_color) {
  2222. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2223. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2224. }
  2225. }
  2226. }
  2227. }
  2228. for (const vt of status?.vt_tray ?? []) {
  2229. if (vt.tray_type && vt.tray_color) {
  2230. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2231. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2232. }
  2233. }
  2234. return filaments;
  2235. }, [status?.ams, status?.vt_tray]);
  2236. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2237. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2238. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2239. const loadedVariants = useMemo(() => {
  2240. const variants = new Set<string>();
  2241. if (status?.ams) {
  2242. for (const ams of status.ams) {
  2243. for (const tray of ams.tray || []) {
  2244. if (tray.tray_type && tray.tray_color) {
  2245. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2246. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2247. }
  2248. }
  2249. }
  2250. }
  2251. for (const vt of status?.vt_tray ?? []) {
  2252. if (vt.tray_type && vt.tray_color) {
  2253. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2254. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2255. }
  2256. }
  2257. return variants;
  2258. }, [status?.ams, status?.vt_tray]);
  2259. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2260. const { data: filamentInfo } = useQuery({
  2261. queryKey: ['filamentInfo', trayInfoIds],
  2262. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2263. enabled: trayInfoIds.length > 0,
  2264. staleTime: 5 * 60 * 1000, // 5 minutes
  2265. });
  2266. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2267. const { data: slotPresets } = useQuery({
  2268. queryKey: ['slotPresets', printer.id],
  2269. queryFn: () => api.getSlotPresets(printer.id),
  2270. staleTime: 2 * 60 * 1000, // 2 minutes
  2271. });
  2272. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2273. // Only queried when there's a running print backed by an archive; shared
  2274. // React Query cache with the Queue / Archives pages keeps it cheap.
  2275. const activeArchiveId =
  2276. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2277. const { data: activeArchivePlates } = useQuery({
  2278. queryKey: ['archive-plates', activeArchiveId],
  2279. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2280. enabled: activeArchiveId != null,
  2281. staleTime: 5 * 60 * 1000,
  2282. });
  2283. const activePlateLabel = (() => {
  2284. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2285. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2286. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2287. })();
  2288. // Fetch user-defined AMS friendly names from the database
  2289. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2290. queryKey: ['amsLabels', printer.id],
  2291. queryFn: () => api.getAmsLabels(printer.id),
  2292. staleTime: 5 * 60 * 1000, // 5 minutes
  2293. });
  2294. // Cache WiFi signal to prevent it disappearing on updates
  2295. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2296. useEffect(() => {
  2297. if (status?.wifi_signal != null) {
  2298. setCachedWifiSignal(status.wifi_signal);
  2299. }
  2300. }, [status?.wifi_signal]);
  2301. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2302. // Cache connected state to prevent flicker when status briefly becomes undefined
  2303. const cachedConnected = useRef<boolean | undefined>(undefined);
  2304. useEffect(() => {
  2305. if (status?.connected !== undefined) {
  2306. cachedConnected.current = status.connected;
  2307. }
  2308. }, [status?.connected]);
  2309. const isConnected = status?.connected ?? cachedConnected.current;
  2310. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2311. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2312. useEffect(() => {
  2313. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2314. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2315. }
  2316. }, [status?.ams_extruder_map]);
  2317. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2318. ? status.ams_extruder_map
  2319. : cachedAmsExtruderMap.current;
  2320. // Same caching for the Filament Track Switch inlet bindings, for the same
  2321. // reason: a partial MQTT frame briefly empties the map and the badges would
  2322. // otherwise blink out.
  2323. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2324. useEffect(() => {
  2325. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2326. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2327. }
  2328. }, [status?.ams_switch_inlet]);
  2329. const ftsInstalled = status?.fila_switch?.installed === true;
  2330. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2331. ? status.ams_switch_inlet
  2332. : cachedAmsSwitchInlet.current;
  2333. // Cache AMS data to prevent it disappearing on idle/offline printers
  2334. const cachedAmsData = useRef<AMSUnit[]>([]);
  2335. useEffect(() => {
  2336. if (status?.ams && status.ams.length > 0) {
  2337. cachedAmsData.current = status.ams;
  2338. }
  2339. }, [status?.ams]);
  2340. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2341. // Confirm a drying cycle actually started (#2533). Firmware answers
  2342. // ams_filament_drying with result=success even when it then silently declines,
  2343. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2344. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2345. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2346. // means the printer took the command and dropped it.
  2347. useEffect(() => {
  2348. if (!dryStartWatch) return;
  2349. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2350. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2351. }, [dryStartWatch, amsData]);
  2352. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2353. // otherwise rearm the timeout on every frame, so it would never elapse.
  2354. useEffect(() => {
  2355. if (!dryStartWatch) return;
  2356. const timer = setTimeout(() => {
  2357. setDryStartWatch(null);
  2358. showToast(t('printers.drying.toastNotStarted'), 'error');
  2359. }, DRY_START_CONFIRM_MS);
  2360. return () => clearTimeout(timer);
  2361. }, [dryStartWatch, showToast, t]);
  2362. // Cache tray_now to prevent flickering when undefined values come in
  2363. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2364. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2365. const cachedTrayNow = useRef<number | undefined>(undefined);
  2366. const currentTrayNow = status?.tray_now;
  2367. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2368. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2369. cachedTrayNow.current = currentTrayNow;
  2370. } else if (currentTrayNow === 255) {
  2371. cachedTrayNow.current = undefined;
  2372. }
  2373. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2374. ? currentTrayNow
  2375. : cachedTrayNow.current;
  2376. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2377. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2378. // expectedTray = the slot the firmware now expects filament in
  2379. // previousTray = the slot that ran out
  2380. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2381. // so these are often different — the graphic highlights the expected one.
  2382. const expectedTray = status?.expected_tray ?? null;
  2383. const previousTray = status?.previous_tray ?? null;
  2384. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2385. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2386. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2387. if (globalId === null) return null;
  2388. if (globalId === 254) return t('printers.expectedSlot.external');
  2389. if (globalId >= 128 && globalId <= 135) {
  2390. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2391. }
  2392. const amsId = Math.floor(globalId / 4);
  2393. const slot = globalId % 4;
  2394. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2395. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2396. };
  2397. const runoutGuidance = status?.state === 'PAUSE'
  2398. ? {
  2399. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2400. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2401. }
  2402. : null;
  2403. // Fetch smart plug for this printer
  2404. const { data: smartPlug } = useQuery({
  2405. queryKey: ['smartPlugByPrinter', printer.id],
  2406. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2407. });
  2408. // Fetch script plugs for this printer (for multi-device control)
  2409. const { data: scriptPlugs } = useQuery({
  2410. queryKey: ['scriptPlugsByPrinter', printer.id],
  2411. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2412. });
  2413. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2414. const { data: plugStatus } = useQuery({
  2415. queryKey: ['smartPlugStatus', smartPlug?.id],
  2416. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2417. enabled: !!smartPlug,
  2418. refetchInterval: 10000, // 10 seconds for real-time power display
  2419. });
  2420. // Fetch queue count for this printer
  2421. const { data: queueItems } = useQuery({
  2422. queryKey: ['queue', printer.id, 'pending'],
  2423. queryFn: () => api.getQueue(printer.id, 'pending'),
  2424. });
  2425. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2426. // so the badge only shows on printers that can actually run the queued jobs.
  2427. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2428. const queueCount = useMemo(() => {
  2429. if (!queueItems?.length) return 0;
  2430. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2431. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2432. // Fetch currently printing queue item to show who started it (Issue #206)
  2433. const { data: printingQueueItems } = useQuery({
  2434. queryKey: ['queue', printer.id, 'printing'],
  2435. queryFn: () => api.getQueue(printer.id, 'printing'),
  2436. enabled: status?.state === 'RUNNING',
  2437. });
  2438. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2439. const { data: reprintUser } = useQuery({
  2440. queryKey: ['currentPrintUser', printer.id],
  2441. queryFn: () => api.getCurrentPrintUser(printer.id),
  2442. enabled: status?.state === 'RUNNING',
  2443. });
  2444. // Combine both sources: queue item user takes precedence, then reprint user
  2445. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2446. // Fetch last completed print for this printer
  2447. const { data: lastPrints } = useQuery({
  2448. queryKey: ['archives', printer.id, 'last'],
  2449. queryFn: () => api.getArchives(printer.id, 1, 0),
  2450. enabled: status?.connected && status?.state !== 'RUNNING',
  2451. });
  2452. const lastPrint = lastPrints?.[0];
  2453. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2454. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2455. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2456. const activePrintName = status?.current_print && isPrintingOrPaused
  2457. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2458. : null;
  2459. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2460. useEffect(() => {
  2461. if (activePrintName) {
  2462. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2463. } else if (!needsPlateClear) {
  2464. setRetainedPrintJob(null);
  2465. }
  2466. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2467. const plateStatus = (() => {
  2468. if (!requirePlateClear || !status?.connected) return null;
  2469. if (isPrintingOrPaused) {
  2470. return {
  2471. label: t('printers.plateStatus.inUse'),
  2472. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2473. };
  2474. }
  2475. if (status.awaiting_plate_clear) {
  2476. return {
  2477. label: t('printers.plateStatus.notCleared'),
  2478. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2479. };
  2480. }
  2481. return {
  2482. label: t('printers.plateStatus.cleared'),
  2483. className: 'bg-status-ok/20 text-status-ok',
  2484. };
  2485. })();
  2486. const plateStatusPill = plateStatus ? (
  2487. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[length:var(--pc-t10,10px)] font-medium ${plateStatus.className}`}>
  2488. {plateStatus.label}
  2489. </span>
  2490. ) : null;
  2491. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2492. const shouldHide = hideIfDisconnected && isConnected === false;
  2493. const deleteMutation = useMutation({
  2494. mutationFn: (options: { deleteArchives: boolean }) =>
  2495. api.deletePrinter(printer.id, options.deleteArchives),
  2496. onSuccess: () => {
  2497. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2498. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2499. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2500. },
  2501. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2502. });
  2503. const connectMutation = useMutation({
  2504. mutationFn: () => api.connectPrinter(printer.id),
  2505. onSuccess: () => {
  2506. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2507. },
  2508. });
  2509. const forceRefreshMutation = useMutation({
  2510. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2511. onSuccess: () => {
  2512. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2513. showToast(t('printers.forceRefreshSuccess'), 'success');
  2514. },
  2515. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2516. });
  2517. const unlinkSpoolMutation = useMutation({
  2518. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2519. onSuccess: (result) => {
  2520. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2521. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2522. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2523. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2524. },
  2525. onError: (error: Error) => {
  2526. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2527. },
  2528. });
  2529. // AMS drying mutations
  2530. const startDryingMutation = useMutation({
  2531. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2532. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2533. onSuccess: (_data, { amsId }) => {
  2534. setDryingPopoverAmsId(null);
  2535. setDryStartWatch({ amsId });
  2536. // "Command sent", not "drying started" — at this point the printer has only
  2537. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2538. // the cycle is genuinely live; the watcher below covers the case where it
  2539. // never appears.
  2540. showToast(t('printers.drying.toastCommandSent'), 'success');
  2541. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2542. },
  2543. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2544. });
  2545. // Scheduled (delayed / at-time) drying runs (#2638)
  2546. const scheduleDryingMutation = useMutation({
  2547. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2548. api.createScheduledDrying({
  2549. printer_id: printer.id,
  2550. ams_id: params.amsId,
  2551. temp: params.temp,
  2552. duration_hours: params.duration,
  2553. filament: params.filament,
  2554. rotate_tray: params.rotateTray,
  2555. start_after: params.startAfter,
  2556. }),
  2557. onSuccess: () => {
  2558. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2559. setDryingPopoverAmsId(null);
  2560. },
  2561. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2562. });
  2563. const stopDryingMutation = useMutation({
  2564. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2565. onSuccess: () => {
  2566. setDryStartWatch(null);
  2567. showToast(t('printers.drying.toastStopped'), 'success');
  2568. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2569. },
  2570. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2571. });
  2572. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2573. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2574. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2575. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2576. // showing the old backup state until the user reopens it.
  2577. const setAmsBackupMutation = useMutation({
  2578. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2579. onSuccess: (_data, enabled) => {
  2580. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2581. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2582. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2583. },
  2584. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2585. });
  2586. // Smart plug control mutations
  2587. const powerControlMutation = useMutation({
  2588. mutationFn: (action: 'on' | 'off') =>
  2589. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2590. onSuccess: () => {
  2591. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2592. },
  2593. });
  2594. const toggleAutoOffMutation = useMutation({
  2595. mutationFn: (enabled: boolean) =>
  2596. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2597. onSuccess: () => {
  2598. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2599. // Also invalidate the smart-plugs list to keep Settings page in sync
  2600. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2601. },
  2602. });
  2603. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2604. const runScriptMutation = useMutation({
  2605. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2606. onSuccess: () => {
  2607. showToast(t('printers.toast.scriptTriggered'));
  2608. },
  2609. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2610. });
  2611. // Print control mutations
  2612. const stopPrintMutation = useMutation({
  2613. mutationFn: () => api.stopPrint(printer.id),
  2614. onSuccess: () => {
  2615. showToast(t('printers.toast.printStopped'));
  2616. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2617. },
  2618. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2619. });
  2620. const pausePrintMutation = useMutation({
  2621. mutationFn: () => api.pausePrint(printer.id),
  2622. onSuccess: () => {
  2623. showToast(t('printers.toast.printPaused'));
  2624. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2625. },
  2626. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2627. });
  2628. const resumePrintMutation = useMutation({
  2629. mutationFn: () => api.resumePrint(printer.id),
  2630. onSuccess: () => {
  2631. showToast(t('printers.toast.printResumed'));
  2632. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2633. },
  2634. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2635. });
  2636. const clearPlateMutation = useMutation({
  2637. mutationFn: () => api.clearPlate(printer.id),
  2638. onSuccess: () => {
  2639. showToast(t('queue.clearPlateSuccess'));
  2640. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2641. old ? { ...old, awaiting_plate_clear: false } : old
  2642. );
  2643. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2644. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2645. },
  2646. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2647. });
  2648. const nozzleTemperatureMutation = useMutation({
  2649. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2650. api.setNozzleTemperature(printer.id, target, nozzle),
  2651. onSuccess: (result) => {
  2652. setStatusControlMenu(null);
  2653. showToast(result.message);
  2654. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2655. },
  2656. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2657. });
  2658. const bedTemperatureMutation = useMutation({
  2659. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2660. onSuccess: (result) => {
  2661. setStatusControlMenu(null);
  2662. showToast(result.message);
  2663. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2664. },
  2665. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2666. });
  2667. const chamberTemperatureMutation = useMutation({
  2668. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2669. onSuccess: (result) => {
  2670. setStatusControlMenu(null);
  2671. showToast(result.message);
  2672. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2673. },
  2674. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2675. });
  2676. const fanSpeedMutation = useMutation({
  2677. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2678. api.setFanSpeed(printer.id, fan, speed),
  2679. onMutate: async ({ fan, speed }) => {
  2680. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2681. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2682. const fanField = {
  2683. part: 'cooling_fan_speed',
  2684. aux: 'big_fan1_speed',
  2685. aux2: 'left_aux_fan_speed',
  2686. chamber: 'big_fan2_speed',
  2687. }[fan];
  2688. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2689. old ? { ...old, [fanField]: speed } : old
  2690. );
  2691. return { previousStatus };
  2692. },
  2693. onSuccess: (result) => {
  2694. setStatusControlMenu(null);
  2695. showToast(result.message);
  2696. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2697. },
  2698. onError: (error: Error, _variables, context) => {
  2699. if (context?.previousStatus) {
  2700. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2701. }
  2702. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2703. },
  2704. });
  2705. const selectExtruderMutation = useMutation({
  2706. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2707. onMutate: async (extruder) => {
  2708. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2709. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2710. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2711. old ? { ...old, active_extruder: extruder } : old
  2712. );
  2713. return { previousStatus };
  2714. },
  2715. onSuccess: (result) => {
  2716. setStatusControlMenu(null);
  2717. showToast(result.message);
  2718. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2719. },
  2720. onError: (error: Error, _extruder, context) => {
  2721. if (context?.previousStatus) {
  2722. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2723. }
  2724. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2725. },
  2726. });
  2727. // Chamber light mutation with optimistic update
  2728. const chamberLightMutation = useMutation({
  2729. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2730. onMutate: async (on) => {
  2731. // Cancel any outgoing refetches
  2732. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2733. // Snapshot the previous value
  2734. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2735. // Optimistically update
  2736. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2737. ...old,
  2738. chamber_light: on,
  2739. }));
  2740. return { previousStatus };
  2741. },
  2742. onSuccess: (_, on) => {
  2743. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2744. },
  2745. onError: (error: Error, _, context) => {
  2746. // Rollback on error
  2747. if (context?.previousStatus) {
  2748. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2749. }
  2750. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2751. },
  2752. });
  2753. // Print speed mutation with optimistic update
  2754. const printSpeedMutation = useMutation({
  2755. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2756. onMutate: async (mode) => {
  2757. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2758. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2759. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2760. ...old,
  2761. speed_level: mode,
  2762. }));
  2763. return { previousStatus };
  2764. },
  2765. onError: (error: Error, _, context) => {
  2766. if (context?.previousStatus) {
  2767. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2768. }
  2769. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2770. },
  2771. });
  2772. const airductMutation = useMutation({
  2773. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2774. onMutate: async (mode) => {
  2775. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2776. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2777. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2778. ...old,
  2779. airduct_mode: mode === 'cooling' ? 0 : 1,
  2780. }));
  2781. return { previousStatus };
  2782. },
  2783. onError: (error: Error, _, context) => {
  2784. if (context?.previousStatus) {
  2785. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2786. }
  2787. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2788. },
  2789. });
  2790. const bedJogMutation = useMutation({
  2791. mutationFn: ({ distance }: { distance: number }) =>
  2792. api.bedJog(printer.id, distance),
  2793. onError: (error: Error) =>
  2794. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2795. });
  2796. const xyJogMutation = useMutation({
  2797. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2798. api.xyJog(printer.id, x, y),
  2799. onError: (error: Error) =>
  2800. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2801. });
  2802. const extruderJogMutation = useMutation({
  2803. mutationFn: (distance: number) =>
  2804. api.extruderJog(printer.id, distance),
  2805. onError: (error: Error) =>
  2806. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2807. });
  2808. const homeAxesMutation = useMutation({
  2809. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2810. onSuccess: () => {
  2811. showToast(t('printers.bedJog.homingStarted'));
  2812. },
  2813. onError: (error: Error) =>
  2814. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2815. });
  2816. // Plate detection setting mutation
  2817. const plateDetectionMutation = useMutation({
  2818. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2819. onSuccess: () => {
  2820. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2821. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2822. },
  2823. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2824. });
  2825. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2826. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2827. // metrics, and the print picker — so flipping this flag puts the printer
  2828. // out of service across every consumer in one place. Used from the
  2829. // overflow menu and EditPrinterModal.
  2830. const maintenanceMutation = useMutation({
  2831. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2832. onSuccess: (_data, isActive) => {
  2833. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2834. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2835. showToast(
  2836. isActive
  2837. ? t('printers.maintenance.toastExited', { name: printer.name })
  2838. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2839. 'success',
  2840. );
  2841. },
  2842. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2843. });
  2844. // Confirm before entering maintenance on a printing printer (entering mode
  2845. // disconnects MQTT, which stops progress tracking + completion notifications
  2846. // for the in-flight job).
  2847. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2848. const handleEnterMaintenance = () => {
  2849. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2850. setConfirmMaintenanceEnter(true);
  2851. } else {
  2852. maintenanceMutation.mutate(false);
  2853. }
  2854. };
  2855. // Query for printable objects (for skip functionality)
  2856. // Fetch when printing with 2+ objects OR when modal is open
  2857. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2858. const { data: objectsData } = useQuery({
  2859. queryKey: ['printableObjects', printer.id],
  2860. queryFn: () => api.getPrintableObjects(printer.id),
  2861. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2862. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2863. });
  2864. // State for tracking which AMS slot is being refreshed
  2865. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2866. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2867. const seenBusyStateRef = useRef<boolean>(false);
  2868. // Fallback timeout ref
  2869. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2870. // Minimum display time passed
  2871. const minTimePassedRef = useRef<boolean>(false);
  2872. // AMS slot refresh mutation
  2873. const refreshAmsSlotMutation = useMutation({
  2874. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2875. api.refreshAmsSlot(printer.id, amsId, slotId),
  2876. onMutate: ({ amsId, slotId }) => {
  2877. // Clear any existing timeout
  2878. if (refreshTimeoutRef.current) {
  2879. clearTimeout(refreshTimeoutRef.current);
  2880. }
  2881. // Reset state
  2882. seenBusyStateRef.current = false;
  2883. minTimePassedRef.current = false;
  2884. setRefreshingSlot({ amsId, slotId });
  2885. // Minimum display time (2 seconds)
  2886. setTimeout(() => {
  2887. minTimePassedRef.current = true;
  2888. }, 2000);
  2889. // Fallback timeout (30 seconds max)
  2890. refreshTimeoutRef.current = setTimeout(() => {
  2891. setRefreshingSlot(null);
  2892. }, 30000);
  2893. },
  2894. onSuccess: (data) => {
  2895. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2896. },
  2897. onError: (error: Error) => {
  2898. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2899. if (refreshTimeoutRef.current) {
  2900. clearTimeout(refreshTimeoutRef.current);
  2901. }
  2902. setRefreshingSlot(null);
  2903. },
  2904. });
  2905. // AMS load/unload mutations (#891)
  2906. const loadAmsTrayMutation = useMutation({
  2907. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2908. onSuccess: (data) => {
  2909. showToast(data.message || t('printers.toast.loadInitiated'));
  2910. },
  2911. onError: (error: Error) => {
  2912. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2913. },
  2914. });
  2915. const unloadAmsMutation = useMutation({
  2916. mutationFn: () => api.unloadAms(printer.id),
  2917. onSuccess: (data) => {
  2918. showToast(data.message || t('printers.toast.unloadInitiated'));
  2919. },
  2920. onError: (error: Error) => {
  2921. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2922. },
  2923. });
  2924. // Plate references state
  2925. const [plateReferences, setPlateReferences] = useState<{
  2926. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2927. max_references: number;
  2928. } | null>(null);
  2929. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2930. // Fetch plate references
  2931. const fetchPlateReferences = async () => {
  2932. try {
  2933. const data = await api.getPlateReferences(printer.id);
  2934. setPlateReferences(data);
  2935. } catch {
  2936. // Ignore errors - references will show as empty
  2937. }
  2938. };
  2939. // Toggle plate detection enabled/disabled
  2940. const handleTogglePlateDetection = () => {
  2941. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2942. };
  2943. // Open plate detection management modal (for calibration/references)
  2944. const handleOpenPlateManagement = async () => {
  2945. setIsCheckingPlate(true);
  2946. setPlateCheckResult(null);
  2947. // Auto-turn on light if it's off
  2948. const lightWasOff = status?.chamber_light === false;
  2949. setPlateCheckLightWasOff(lightWasOff);
  2950. if (lightWasOff) {
  2951. await api.setChamberLight(printer.id, true);
  2952. // Wait for light to physically turn on and camera to adjust exposure
  2953. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2954. await new Promise(resolve => setTimeout(resolve, 2500));
  2955. }
  2956. try {
  2957. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2958. setPlateCheckResult(result);
  2959. fetchPlateReferences();
  2960. } catch (error) {
  2961. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2962. // Restore light if check failed
  2963. if (lightWasOff) {
  2964. await api.setChamberLight(printer.id, false);
  2965. setPlateCheckLightWasOff(false);
  2966. }
  2967. } finally {
  2968. setIsCheckingPlate(false);
  2969. }
  2970. };
  2971. // Close plate check modal and restore light state
  2972. const closePlateCheckModal = useCallback(async () => {
  2973. setPlateCheckResult(null);
  2974. // Restore light to original state if we turned it on
  2975. if (plateCheckLightWasOff) {
  2976. await api.setChamberLight(printer.id, false);
  2977. setPlateCheckLightWasOff(false);
  2978. }
  2979. }, [plateCheckLightWasOff, printer.id]);
  2980. // Calibrate plate detection handler
  2981. const handleCalibratePlate = async (label?: string) => {
  2982. setIsCalibrating(true);
  2983. try {
  2984. const result = await api.calibratePlateDetection(printer.id, { label });
  2985. if (result.success) {
  2986. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2987. // Refresh references and re-check
  2988. fetchPlateReferences();
  2989. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2990. setPlateCheckResult(checkResult);
  2991. } else {
  2992. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2993. }
  2994. } catch (error) {
  2995. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2996. } finally {
  2997. setIsCalibrating(false);
  2998. }
  2999. };
  3000. // Update reference label
  3001. const handleUpdateRefLabel = async (index: number, label: string) => {
  3002. try {
  3003. await api.updatePlateReferenceLabel(printer.id, index, label);
  3004. setEditingRefLabel(null);
  3005. fetchPlateReferences();
  3006. } catch (error) {
  3007. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3008. }
  3009. };
  3010. // Delete reference
  3011. const handleDeleteRef = async (index: number) => {
  3012. try {
  3013. await api.deletePlateReference(printer.id, index);
  3014. showToast(t('printers.toast.referenceDeleted'), 'success');
  3015. fetchPlateReferences();
  3016. // Re-check to update counts
  3017. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3018. setPlateCheckResult(checkResult);
  3019. } catch (error) {
  3020. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3021. }
  3022. };
  3023. // Save ROI settings
  3024. const handleSaveRoi = async () => {
  3025. if (!editingRoi) return;
  3026. setIsSavingRoi(true);
  3027. try {
  3028. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3029. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3030. setEditingRoi(null);
  3031. // Re-check to see new ROI in action
  3032. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3033. setPlateCheckResult(checkResult);
  3034. } catch (error) {
  3035. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3036. } finally {
  3037. setIsSavingRoi(false);
  3038. }
  3039. };
  3040. // Close plate check modal on Escape key
  3041. useEffect(() => {
  3042. const handleEscape = (e: KeyboardEvent) => {
  3043. if (e.key === 'Escape' && plateCheckResult) {
  3044. closePlateCheckModal();
  3045. }
  3046. };
  3047. window.addEventListener('keydown', handleEscape);
  3048. return () => window.removeEventListener('keydown', handleEscape);
  3049. }, [plateCheckResult, closePlateCheckModal]);
  3050. // Watch ams_status_main to detect when RFID read completes
  3051. // ams_status_main: 0=idle, 2=rfid_identifying
  3052. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3053. useEffect(() => {
  3054. if (!refreshingSlot) return;
  3055. const amsStatus = status?.ams_status_main ?? 0;
  3056. // Track when we see non-idle state (printer is working)
  3057. if (amsStatus !== 0) {
  3058. seenBusyStateRef.current = true;
  3059. // Cancel any deferred clear since we're back to busy
  3060. if (deferredClearRef.current) {
  3061. clearTimeout(deferredClearRef.current);
  3062. deferredClearRef.current = null;
  3063. }
  3064. }
  3065. // When we've seen busy and now idle, clear (with min time check)
  3066. if (seenBusyStateRef.current && amsStatus === 0) {
  3067. if (minTimePassedRef.current) {
  3068. // Min time passed - clear now
  3069. if (refreshTimeoutRef.current) {
  3070. clearTimeout(refreshTimeoutRef.current);
  3071. }
  3072. setRefreshingSlot(null);
  3073. } else {
  3074. // Schedule clear after min time (2 seconds from start)
  3075. if (!deferredClearRef.current) {
  3076. deferredClearRef.current = setTimeout(() => {
  3077. if (refreshTimeoutRef.current) {
  3078. clearTimeout(refreshTimeoutRef.current);
  3079. }
  3080. setRefreshingSlot(null);
  3081. }, 2000);
  3082. }
  3083. }
  3084. }
  3085. return () => {
  3086. if (deferredClearRef.current) {
  3087. clearTimeout(deferredClearRef.current);
  3088. }
  3089. };
  3090. }, [status?.ams_status_main, refreshingSlot]);
  3091. useEffect(() => {
  3092. if (!showMenu) return;
  3093. const handleClickOutside = (event: MouseEvent) => {
  3094. const target = event.target as Node;
  3095. if (!printerActionsMenuRef.current?.contains(target)) {
  3096. setShowMenu(false);
  3097. }
  3098. };
  3099. document.addEventListener('mousedown', handleClickOutside);
  3100. return () => document.removeEventListener('mousedown', handleClickOutside);
  3101. }, [showMenu]);
  3102. if (shouldHide) {
  3103. return null;
  3104. }
  3105. // Size-based styling helpers
  3106. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3107. // width, its thumbnail and the printer name, but every label inside the
  3108. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3109. // S one -- the disparity was worst exactly where someone asking for more
  3110. // room ends up. These custom properties carry the scaled sizes into the
  3111. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3112. // unless they reach for a size that is already asking for more space.
  3113. // Plain computation rather than useMemo: this sits after the card's early
  3114. // returns, where a hook would break the rules-of-hooks ordering, and
  3115. // building ten strings per render costs nothing.
  3116. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3117. const getImageSize = () => {
  3118. switch (cardSize) {
  3119. case 1: return 'w-10 h-10';
  3120. case 2: return 'w-14 h-14';
  3121. case 3: return 'w-16 h-16';
  3122. case 4: return 'w-20 h-20';
  3123. default: return 'w-14 h-14';
  3124. }
  3125. };
  3126. const getTitleSize = () => {
  3127. switch (cardSize) {
  3128. case 1: return 'text-base truncate';
  3129. case 2: return 'text-lg';
  3130. case 3: return 'text-xl';
  3131. case 4: return 'text-2xl';
  3132. default: return 'text-lg';
  3133. }
  3134. };
  3135. const getSpacing = () => {
  3136. switch (cardSize) {
  3137. case 1: return 'mb-2';
  3138. case 2: return 'mb-4';
  3139. case 3: return 'mb-5';
  3140. case 4: return 'mb-6';
  3141. default: return 'mb-4';
  3142. }
  3143. };
  3144. // A dropped file always becomes a queue item, so a printer that is busy,
  3145. // offline or mid-drying is no reason to refuse the drop — it only means the
  3146. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3147. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3148. // what this would have done for them.
  3149. //
  3150. // What remains is what the flow actually performs: upload the file, then
  3151. // create a queue item. It never touches printers:control, which is what this
  3152. // used to check — so someone holding that but neither of these had the file
  3153. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3154. // button below has always checked this pair.
  3155. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3156. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3157. // and the modal's own "will start later" toast cannot disagree.
  3158. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3159. const handleCardDragEnter = (e: React.DragEvent) => {
  3160. e.preventDefault();
  3161. dragCounterRef.current++;
  3162. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3163. };
  3164. const handleCardDragOver = (e: React.DragEvent) => {
  3165. e.preventDefault();
  3166. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3167. };
  3168. const handleCardDragLeave = (e: React.DragEvent) => {
  3169. e.preventDefault();
  3170. dragCounterRef.current--;
  3171. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3172. };
  3173. const handleCardDrop = async (e: React.DragEvent) => {
  3174. e.preventDefault();
  3175. dragCounterRef.current = 0;
  3176. setIsDraggingFile(false);
  3177. if (!canDrop) return;
  3178. const droppedFiles = Array.from(e.dataTransfer.files);
  3179. const file = droppedFiles[0];
  3180. if (!file) return;
  3181. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3182. const lower = file.name.toLowerCase();
  3183. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3184. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3185. return;
  3186. }
  3187. setIsDropUploading(true);
  3188. try {
  3189. const result = await api.uploadLibraryFile(file, null);
  3190. // Check printer compatibility if sliced_for_model is available in metadata
  3191. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3192. const printerModel = mapModelCode(printer.model);
  3193. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3194. await api.deleteLibraryFile(result.id).catch(() => {});
  3195. showToast(
  3196. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3197. 'error'
  3198. );
  3199. return;
  3200. }
  3201. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3202. } catch {
  3203. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3204. } finally {
  3205. setIsDropUploading(false);
  3206. }
  3207. };
  3208. const handleCardClick = (e: React.MouseEvent) => {
  3209. if (viewMode !== 'compact' || selectionMode) return;
  3210. const target = e.target as HTMLElement;
  3211. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3212. onOpenCompactCard?.(printer.id);
  3213. };
  3214. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3215. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3216. // Opening a camera in a given mode, without touching which mode is remembered
  3217. // -- the split button's two halves want the same action but disagree about
  3218. // whether the choice was deliberate enough to keep.
  3219. const openCameraIn = (mode: CameraViewMode) => {
  3220. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3221. onOpenEmbeddedCamera(printer.id, printer.name);
  3222. } else {
  3223. openCameraWindow(printer.id);
  3224. }
  3225. };
  3226. // Picking a mode both opens the camera that way and makes it the mode the
  3227. // plain icon uses from now on. A menu that only changed a preference would
  3228. // leave the user with a second click to do the thing they already asked for.
  3229. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3230. [
  3231. {
  3232. mode: 'window' as const,
  3233. icon: <ExternalLink className="w-4 h-4" />,
  3234. label: t('settings.newWindow'),
  3235. title: t('settings.cameraWindowDescription'),
  3236. },
  3237. {
  3238. mode: 'embedded' as const,
  3239. icon: <PictureInPicture2 className="w-4 h-4" />,
  3240. label: t('settings.embeddedOverlay'),
  3241. title: t('settings.cameraOverlayDescription'),
  3242. },
  3243. ]
  3244. ).map(({ mode, icon, label, title }) => ({
  3245. icon,
  3246. // The remembered mode is marked in the label itself: the icon slot already
  3247. // carries the mode's own icon, and a separate tick column would push both
  3248. // entries out of line with every other card menu.
  3249. label: mode === cameraViewMode ? `${label} ✓` : label,
  3250. title,
  3251. onClick: () => {
  3252. onSelectCameraViewMode?.(mode);
  3253. openCameraIn(mode);
  3254. },
  3255. }));
  3256. const renderAmsSlotActions = ({
  3257. amsId,
  3258. slotId,
  3259. loadTrayId,
  3260. isRefreshing,
  3261. includeRfid = true,
  3262. }: {
  3263. amsId: number;
  3264. slotId: number;
  3265. loadTrayId: number;
  3266. isRefreshing?: boolean;
  3267. includeRfid?: boolean;
  3268. }) => {
  3269. const printerBusy = status?.state === 'RUNNING';
  3270. return (
  3271. <>
  3272. {includeRfid && (
  3273. <button
  3274. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3275. hasPermission('printers:ams_rfid')
  3276. ? 'text-white hover:bg-bambu-dark-tertiary'
  3277. : 'text-bambu-gray/50 cursor-not-allowed'
  3278. }`}
  3279. onClick={(e) => {
  3280. e.stopPropagation();
  3281. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3282. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3283. }}
  3284. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3285. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3286. >
  3287. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3288. {t('printers.rfid.reread')}
  3289. </button>
  3290. )}
  3291. <button
  3292. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3293. hasPermission('printers:control')
  3294. ? 'text-white hover:bg-bambu-dark-tertiary'
  3295. : 'text-bambu-gray/50 cursor-not-allowed'
  3296. }`}
  3297. onClick={(e) => {
  3298. e.stopPropagation();
  3299. if (printerBusy || !hasPermission('printers:control')) return;
  3300. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  3301. }}
  3302. disabled={printerBusy || !hasPermission('printers:control')}
  3303. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3304. >
  3305. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3306. {t('printers.ams.load')}
  3307. </button>
  3308. <button
  3309. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3310. hasPermission('printers:control')
  3311. ? 'text-white hover:bg-bambu-dark-tertiary'
  3312. : 'text-bambu-gray/50 cursor-not-allowed'
  3313. }`}
  3314. onClick={(e) => {
  3315. e.stopPropagation();
  3316. if (printerBusy || !hasPermission('printers:control')) return;
  3317. unloadAmsMutation.mutate();
  3318. }}
  3319. disabled={printerBusy || !hasPermission('printers:control')}
  3320. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3321. >
  3322. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3323. {t('printers.ams.unload')}
  3324. </button>
  3325. </>
  3326. );
  3327. };
  3328. const printerActionsMenu = (
  3329. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3330. <Button
  3331. variant="secondary"
  3332. size="sm"
  3333. onClick={() => setShowMenu(!showMenu)}
  3334. title={t('common.more', 'More')}
  3335. className={footerIconButtonClass}
  3336. >
  3337. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3338. </Button>
  3339. {showMenu && (
  3340. <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">
  3341. <button
  3342. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3343. hasPermission('printers:update')
  3344. ? 'hover:bg-bambu-dark-tertiary'
  3345. : 'opacity-50 cursor-not-allowed'
  3346. }`}
  3347. onClick={() => {
  3348. if (!hasPermission('printers:update')) return;
  3349. setShowEditModal(true);
  3350. setShowMenu(false);
  3351. }}
  3352. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3353. >
  3354. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3355. {t('common.edit')}
  3356. </button>
  3357. <button
  3358. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3359. onClick={() => {
  3360. setShowPrinterInfo(true);
  3361. setShowMenu(false);
  3362. }}
  3363. >
  3364. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3365. {t('printers.printerInformation')}
  3366. </button>
  3367. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3368. <button
  3369. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3370. hasPermission('printers:update')
  3371. ? 'hover:bg-bambu-dark-tertiary'
  3372. : 'opacity-50 cursor-not-allowed'
  3373. }`}
  3374. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3375. onClick={() => {
  3376. if (!hasPermission('printers:update')) return;
  3377. setShowMenu(false);
  3378. if (printer.is_active !== false) {
  3379. handleEnterMaintenance();
  3380. } else {
  3381. maintenanceMutation.mutate(true);
  3382. }
  3383. }}
  3384. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3385. >
  3386. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3387. {printer.is_active !== false
  3388. ? t('printers.maintenance.menuEnter')
  3389. : t('printers.maintenance.menuExit')}
  3390. </button>
  3391. <button
  3392. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3393. onClick={() => {
  3394. connectMutation.mutate();
  3395. setShowMenu(false);
  3396. }}
  3397. >
  3398. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3399. {t('printers.reconnect')}
  3400. </button>
  3401. <button
  3402. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3403. disabled={forceRefreshMutation.isPending}
  3404. onClick={() => {
  3405. forceRefreshMutation.mutate();
  3406. setShowMenu(false);
  3407. }}
  3408. >
  3409. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3410. {t('printers.forceRefresh')}
  3411. </button>
  3412. <button
  3413. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3414. onClick={() => {
  3415. setShowMQTTDebug(true);
  3416. setShowMenu(false);
  3417. }}
  3418. >
  3419. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3420. {t('printers.mqttDebug')}
  3421. </button>
  3422. <button
  3423. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3424. onClick={() => {
  3425. setShowDiagnostic(true);
  3426. setShowMenu(false);
  3427. }}
  3428. >
  3429. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3430. {t('diagnostic.runButton')}
  3431. </button>
  3432. <button
  3433. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3434. hasPermission('printers:delete')
  3435. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3436. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3437. }`}
  3438. onClick={() => {
  3439. if (!hasPermission('printers:delete')) return;
  3440. setShowDeleteConfirm(true);
  3441. setShowMenu(false);
  3442. }}
  3443. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3444. >
  3445. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3446. {t('common.delete')}
  3447. </button>
  3448. </div>
  3449. )}
  3450. </div>
  3451. );
  3452. return (
  3453. <Card
  3454. id={`printer-card-${printer.id}`}
  3455. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3456. style={cardScaleStyle}
  3457. onClick={handleCardClick}
  3458. onDragEnter={handleCardDragEnter}
  3459. onDragOver={handleCardDragOver}
  3460. onDragLeave={handleCardDragLeave}
  3461. onDrop={handleCardDrop}
  3462. >
  3463. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3464. {selectionMode && (
  3465. <div
  3466. className="absolute inset-0 z-20 flex items-start p-2"
  3467. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3468. >
  3469. {isSelected ? (
  3470. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3471. ) : (
  3472. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3473. )}
  3474. </div>
  3475. )}
  3476. {/* Drop zone overlay */}
  3477. {(isDraggingFile || isDropUploading) && (
  3478. <div
  3479. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3480. isDropUploading
  3481. ? 'bg-bambu-green/10 border-bambu-green/50'
  3482. : canDrop
  3483. ? 'bg-bambu-green/10 border-bambu-green'
  3484. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3485. }`}
  3486. >
  3487. <div className="text-center">
  3488. {isDropUploading ? (
  3489. <>
  3490. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3491. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3492. </>
  3493. ) : canDrop ? (
  3494. <>
  3495. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3496. <p className="text-sm font-medium text-bambu-green">
  3497. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3498. </p>
  3499. </>
  3500. ) : (
  3501. <>
  3502. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3503. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3504. {!hasPermission('library:upload')
  3505. ? t('fileManager.noPermissionUpload')
  3506. : t('fileManager.noPermissionAddToQueue')}
  3507. </p>
  3508. </>
  3509. )}
  3510. </div>
  3511. </div>
  3512. )}
  3513. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3514. {/* Header */}
  3515. <div className={getSpacing()}>
  3516. {/* Top row: Image, Name, Menu */}
  3517. <div className="flex items-start justify-between gap-2">
  3518. <div className="flex items-center gap-3 min-w-0 flex-1">
  3519. {/* Printer Model Image */}
  3520. <img
  3521. src={getPrinterImage(printer.model)}
  3522. alt={printer.model || t('common.printer')}
  3523. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3524. />
  3525. <div className="min-w-0 flex-1">
  3526. <div className="flex items-center justify-between gap-2">
  3527. <div className="flex min-w-0 items-center gap-2">
  3528. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3529. {/* Connection indicator dot for compact mode */}
  3530. {viewMode === 'compact' && (() => {
  3531. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3532. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3533. const hasWarning = hmsErrors.length > 0;
  3534. const pipColor = !status?.connected
  3535. ? 'bg-status-error'
  3536. : hasSevere
  3537. ? 'bg-status-error'
  3538. : hasWarning
  3539. ? 'bg-status-warning'
  3540. : 'bg-status-ok';
  3541. const pipTitle = !status?.connected
  3542. ? t('printers.connection.offline')
  3543. : hasWarning
  3544. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3545. : t('printers.connection.connected');
  3546. return (
  3547. <div
  3548. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3549. title={pipTitle}
  3550. />
  3551. );
  3552. })()}
  3553. </div>
  3554. {viewMode === 'compact' && showClearPlateButton && (
  3555. <button
  3556. type="button"
  3557. onClick={() => clearPlateMutation.mutate()}
  3558. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3559. aria-label={t('printers.plateStatus.markCleared')}
  3560. 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"
  3561. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3562. >
  3563. {clearPlateMutation.isPending ? (
  3564. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3565. ) : (
  3566. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3567. )}
  3568. </button>
  3569. )}
  3570. </div>
  3571. <p className="text-sm text-bambu-gray">
  3572. {printer.model || 'Unknown Model'}
  3573. {/* Nozzle Info - only in expanded */}
  3574. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3575. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3576. • {status.nozzles[0].nozzle_diameter}mm
  3577. </span>
  3578. )}
  3579. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3580. <span className="ml-2 text-bambu-gray">
  3581. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3582. {Math.round(maintenanceInfo.total_print_hours)}h
  3583. </span>
  3584. )}
  3585. </p>
  3586. </div>
  3587. </div>
  3588. </div>
  3589. {/* Badges row - only in expanded mode */}
  3590. {viewMode === 'expanded' && (
  3591. <div className="mt-2">
  3592. <div className="flex flex-wrap items-center gap-2">
  3593. {/* Connection status badge (or Maintenance pill when out of service).
  3594. Defensive: only swap when is_active is EXPLICITLY false. An
  3595. undefined / missing field defaults to "active" so the regular
  3596. pill renders — matches the backend default and prevents test
  3597. fixtures (or stale clients) from accidentally tripping the
  3598. maintenance UI. */}
  3599. {printer.is_active === false ? (
  3600. <span
  3601. 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"
  3602. title={t('printers.maintenance.subtitle')}
  3603. >
  3604. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3605. {t('printers.maintenance.pillLabel')}
  3606. </span>
  3607. ) : (
  3608. <span
  3609. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3610. status?.connected
  3611. ? 'bg-status-ok/20 text-status-ok'
  3612. : 'bg-status-error/20 text-status-error'
  3613. }`}
  3614. >
  3615. {status?.connected ? (
  3616. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3617. ) : (
  3618. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3619. )}
  3620. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3621. </span>
  3622. )}
  3623. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3624. {printer.is_active !== false && !status?.connected && (
  3625. <button
  3626. onClick={() => setShowDiagnostic(true)}
  3627. 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"
  3628. title={t('diagnostic.runButton')}
  3629. >
  3630. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3631. {t('diagnostic.runButton')}
  3632. </button>
  3633. )}
  3634. {/* Network connection indicator */}
  3635. {status?.connected && status?.wired_network && (
  3636. <span
  3637. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3638. title={t('printers.connection.ethernet', 'Ethernet')}
  3639. >
  3640. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3641. {t('printers.connection.ethernet', 'Ethernet')}
  3642. </span>
  3643. )}
  3644. {/* WiFi signal indicator */}
  3645. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3646. <span
  3647. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3648. wifiSignal >= -50
  3649. ? 'bg-status-ok/20 text-status-ok'
  3650. : wifiSignal >= -60
  3651. ? 'bg-status-ok/20 text-status-ok'
  3652. : wifiSignal >= -70
  3653. ? 'bg-status-warning/20 text-status-warning'
  3654. : wifiSignal >= -80
  3655. ? 'bg-orange-500/20 text-orange-600'
  3656. : 'bg-status-error/20 text-status-error'
  3657. }`}
  3658. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3659. >
  3660. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3661. {wifiSignal}dBm
  3662. </span>
  3663. )}
  3664. {/* HMS Status Indicator */}
  3665. {status?.connected && (() => {
  3666. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3667. return (
  3668. <button
  3669. onClick={() => setShowHMSModal(true)}
  3670. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3671. knownErrors.length > 0
  3672. ? knownErrors.some(e => e.severity <= 2)
  3673. ? 'bg-status-error/20 text-status-error'
  3674. : 'bg-status-warning/20 text-status-warning'
  3675. : 'bg-status-ok/20 text-status-ok'
  3676. }`}
  3677. title={t('printers.clickToViewHmsErrors')}
  3678. >
  3679. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3680. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3681. </button>
  3682. );
  3683. })()}
  3684. {/* AI failure detection badge (#1546) — always shown while detection
  3685. is enabled for this printer, like the other health badges. Gray
  3686. "Idle" outside a monitored print, class-colored during one. */}
  3687. {aiDetectionEnabled && (() => {
  3688. const cls = aiDetection
  3689. ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
  3690. : 'idle';
  3691. const colorClass =
  3692. cls === 'failure'
  3693. ? 'bg-status-error/20 text-status-error'
  3694. : cls === 'warning'
  3695. ? 'bg-status-warning/20 text-status-warning'
  3696. : cls === 'safe'
  3697. ? 'bg-status-ok/20 text-status-ok'
  3698. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3699. return (
  3700. <button
  3701. onClick={() => setShowAiModal(true)}
  3702. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3703. title={
  3704. aiDetection
  3705. ? t('printers.aiDetection.tooltip', {
  3706. status: t(`printers.aiDetection.${cls}`),
  3707. score: aiDetection.score.toFixed(3),
  3708. })
  3709. : t('printers.aiDetection.tooltipIdle')
  3710. }
  3711. >
  3712. <ScanEye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3713. {t(`printers.aiDetection.${cls}`)}
  3714. </button>
  3715. );
  3716. })()}
  3717. {/* Maintenance Status Indicator */}
  3718. {maintenanceInfo && (
  3719. <button
  3720. onClick={() => navigate('/maintenance')}
  3721. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3722. maintenanceInfo.due_count > 0
  3723. ? 'bg-status-error/20 text-status-error'
  3724. : maintenanceInfo.warning_count > 0
  3725. ? 'bg-status-warning/20 text-status-warning'
  3726. : 'bg-status-ok/20 text-status-ok'
  3727. }`}
  3728. title={
  3729. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3730. ? `${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`
  3731. : t('printers.maintenanceUpToDate')
  3732. }
  3733. >
  3734. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3735. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3736. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3737. : 'OK'}
  3738. </button>
  3739. )}
  3740. {/* Queue Count Badge */}
  3741. {queueCount > 0 && (
  3742. <button
  3743. onClick={() => navigate('/queue')}
  3744. 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"
  3745. title={t('printers.queue.inQueue', { count: queueCount })}
  3746. >
  3747. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3748. {queueCount}
  3749. </button>
  3750. )}
  3751. {/* Firmware Version Badge */}
  3752. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3753. <button
  3754. onClick={() => setShowFirmwareModal(true)}
  3755. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3756. firmwareInfo.update_available
  3757. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3758. : 'bg-status-ok/20 text-status-ok'
  3759. }`}
  3760. title={
  3761. firmwareInfo.update_available
  3762. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3763. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3764. }
  3765. >
  3766. {firmwareInfo.update_available ? <Download className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <CheckCircle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3767. {firmwareInfo.current_version}
  3768. </button>
  3769. ) : status?.firmware_version ? (
  3770. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3771. {status.firmware_version}
  3772. </span>
  3773. ) : null}
  3774. {/* Enclosure Door Badge — models with an actual door sensor.
  3775. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3776. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3777. <span
  3778. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3779. status.door_open
  3780. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3781. : 'bg-status-ok/20 text-status-ok'
  3782. }`}
  3783. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3784. >
  3785. {status.door_open ? <DoorOpen className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <DoorClosed className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3786. </span>
  3787. )}
  3788. </div>
  3789. </div>
  3790. )}
  3791. </div>
  3792. {/* Delete Confirmation */}
  3793. {showDeleteConfirm && (
  3794. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3795. <Card className="w-full max-w-md mx-4">
  3796. <CardContent>
  3797. <div className="flex items-start gap-3 mb-4">
  3798. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3799. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3800. </div>
  3801. <div>
  3802. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3803. <p className="text-sm text-bambu-gray mt-1">
  3804. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3805. </p>
  3806. </div>
  3807. </div>
  3808. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3809. <label className="flex items-start gap-3 cursor-pointer">
  3810. <input
  3811. type="checkbox"
  3812. checked={deleteArchives}
  3813. onChange={(e) => setDeleteArchives(e.target.checked)}
  3814. className="mt-0.5 w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3815. />
  3816. <div>
  3817. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3818. <p className="text-xs text-bambu-gray mt-0.5">
  3819. {deleteArchives
  3820. ? t('printers.confirm.deleteArchivesNote')
  3821. : t('printers.confirm.keepArchivesNote')}
  3822. </p>
  3823. </div>
  3824. </label>
  3825. </div>
  3826. <div className="flex justify-end gap-2">
  3827. <Button
  3828. variant="secondary"
  3829. onClick={() => {
  3830. setShowDeleteConfirm(false);
  3831. setDeleteArchives(true);
  3832. }}
  3833. >
  3834. {t('common.cancel')}
  3835. </Button>
  3836. <Button
  3837. variant="danger"
  3838. onClick={() => {
  3839. deleteMutation.mutate({ deleteArchives });
  3840. setShowDeleteConfirm(false);
  3841. setDeleteArchives(true);
  3842. }}
  3843. >
  3844. Delete
  3845. </Button>
  3846. </div>
  3847. </CardContent>
  3848. </Card>
  3849. </div>
  3850. )}
  3851. {/* Status — see the equivalent defensive `=== false` check on the
  3852. header pill above for why this is not `!printer.is_active`. */}
  3853. {printer.is_active === false ? (
  3854. // Maintenance mode (#1476) — replaces the cover/progress container
  3855. // so the card keeps the same height. Renders for both compact and
  3856. // expanded view modes so the printer stays visible but plainly
  3857. // out-of-service.
  3858. <>
  3859. {viewMode === 'compact' ? (
  3860. <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">
  3861. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  3862. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  3863. {t('printers.maintenance.pillLabel')}
  3864. </span>
  3865. </div>
  3866. ) : (
  3867. <>
  3868. <div className="flex items-center gap-2 mb-2">
  3869. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  3870. {t('printers.status.title', 'Status')}
  3871. </span>
  3872. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3873. </div>
  3874. <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">
  3875. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3876. <div className="flex-1 min-w-0">
  3877. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3878. {t('printers.maintenance.title')}
  3879. </p>
  3880. <p className="text-xs text-bambu-gray mt-0.5">
  3881. {t('printers.maintenance.subtitle')}
  3882. </p>
  3883. </div>
  3884. <Button
  3885. variant="secondary"
  3886. size="sm"
  3887. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3888. onClick={() => maintenanceMutation.mutate(true)}
  3889. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3890. >
  3891. {t('printers.maintenance.exitButton')}
  3892. </Button>
  3893. </div>
  3894. </>
  3895. )}
  3896. </>
  3897. ) : status?.connected && (
  3898. <>
  3899. {/* Compact: Simple status bar */}
  3900. {viewMode === 'compact' ? (
  3901. (() => {
  3902. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3903. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3904. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3905. ? Math.max(0, Math.min(100, status.progress || 0))
  3906. : showClearPlateButton
  3907. ? 100
  3908. : hasProblem
  3909. ? 100
  3910. : 0;
  3911. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3912. const compactProgressClass = hasProblem
  3913. ? 'bg-status-error'
  3914. : status.state === 'PAUSE'
  3915. ? 'bg-status-warning'
  3916. : 'bg-bambu-green';
  3917. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  3918. const hasCompactLayers =
  3919. isActiveCompactPrint &&
  3920. status.layer_num != null &&
  3921. status.total_layers != null &&
  3922. status.total_layers > 0;
  3923. return (
  3924. <>
  3925. <div className="relative mt-2 flex items-center gap-2">
  3926. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3927. <div
  3928. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3929. style={{ width: `${compactProgress}%` }}
  3930. />
  3931. </div>
  3932. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3933. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3934. </span>
  3935. </div>
  3936. {/* #2674: size S showed only a name, a pip and a progress bar — not
  3937. enough to answer "which printer finishes first", which is what a
  3938. wall-mounted fleet view is for. One line of the metrics the
  3939. expanded card already renders, using the same formatters and the
  3940. same ETA styling so S and M read alike. The row keeps its height
  3941. when idle so cards don't shift as prints start and stop. */}
  3942. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[length:var(--pc-t11,11px)] leading-none text-bambu-gray">
  3943. {hasCompactEta && (
  3944. <>
  3945. <span className="flex shrink-0 items-center gap-1">
  3946. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3947. {formatDuration(status.remaining_time! * 60)}
  3948. </span>
  3949. <span
  3950. className="shrink-0 font-medium text-bambu-green"
  3951. title={t('printers.estimatedCompletion')}
  3952. >
  3953. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  3954. </span>
  3955. </>
  3956. )}
  3957. {hasCompactLayers && (
  3958. <span className="flex min-w-0 items-center gap-1 truncate">
  3959. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  3960. {status.layer_num}/{status.total_layers}
  3961. </span>
  3962. )}
  3963. </div>
  3964. </>
  3965. );
  3966. })()
  3967. ) : (
  3968. /* Expanded: Full status section */
  3969. <>
  3970. <div className="flex items-center gap-2 mb-2">
  3971. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  3972. {t('printers.status.title', 'Status')}
  3973. </span>
  3974. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3975. </div>
  3976. {/* Current Print or Idle Placeholder */}
  3977. {(() => {
  3978. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3979. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3980. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3981. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3982. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3983. return (
  3984. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3985. <button
  3986. onClick={() => setShowSkipObjectsModal(true)}
  3987. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3988. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3989. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3990. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3991. : 'text-bambu-gray/30 cursor-not-allowed'
  3992. }`}
  3993. title={
  3994. !hasPermission('printers:control')
  3995. ? t('printers.permission.noControl')
  3996. : !isActivePrint
  3997. ? t('printers.skipObjects.onlyWhilePrinting')
  3998. : (status.printable_objects_count ?? 0) >= 2
  3999. ? t('printers.skipObjects.tooltip')
  4000. : t('printers.skipObjects.requiresMultiple')
  4001. }
  4002. >
  4003. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4004. {objectsData && objectsData.skipped_count > 0 && (
  4005. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[length:var(--pc-t10,10px)] font-bold bg-red-500 text-white rounded-full">
  4006. {objectsData.skipped_count}
  4007. </span>
  4008. )}
  4009. </button>
  4010. <div className="flex items-stretch gap-2">
  4011. <CoverImage
  4012. url={coverUrl}
  4013. printName={printName || undefined}
  4014. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4015. />
  4016. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4017. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4018. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4019. {plateStatusPill}
  4020. </div>
  4021. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4022. {printName || t('printers.noActiveJob', 'No active job')}
  4023. </p>
  4024. <div className="flex h-3 items-center gap-2 text-sm">
  4025. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4026. <div
  4027. 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`}
  4028. style={{ width: `${progress}%` }}
  4029. />
  4030. </div>
  4031. <span className={`w-9 shrink-0 pr-1 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  4032. </div>
  4033. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4034. {isActivePrint ? (
  4035. <>
  4036. {status.remaining_time != null && status.remaining_time > 0 && (
  4037. <>
  4038. <span className="flex items-center gap-1">
  4039. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4040. {formatDuration(status.remaining_time * 60)}
  4041. </span>
  4042. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4043. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4044. </span>
  4045. </>
  4046. )}
  4047. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4048. <span className="flex items-center gap-1">
  4049. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4050. {status.layer_num}/{status.total_layers}
  4051. </span>
  4052. )}
  4053. {currentPrintUser && (
  4054. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4055. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4056. {currentPrintUser}
  4057. </span>
  4058. )}
  4059. </>
  4060. ) : lastPrint ? (
  4061. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4062. Last: {lastPrint.print_name || lastPrint.filename}
  4063. {lastPrint.completed_at && (
  4064. <span className="ml-1 text-bambu-gray/60">
  4065. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4066. </span>
  4067. )}
  4068. </p>
  4069. ) : (
  4070. <span>{t('printers.readyToPrint')}</span>
  4071. )}
  4072. </div>
  4073. </div>
  4074. </div>
  4075. <PrinterQueueWidget
  4076. printerId={printer.id}
  4077. printerModel={printer.model}
  4078. loadedFilamentTypes={loadedFilamentTypes}
  4079. loadedFilaments={loadedFilaments}
  4080. loadedVariants={loadedVariants}
  4081. variant="panelExtension"
  4082. />
  4083. </div>
  4084. );
  4085. })()}
  4086. </>
  4087. )}
  4088. {/* Temperatures */}
  4089. {status.temperatures && viewMode === 'expanded' && (() => {
  4090. // Use actual heater states from MQTT stream
  4091. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4092. const bedHeating = status.temperatures.bed_heating || false;
  4093. const chamberHeating = status.temperatures.chamber_heating || false;
  4094. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4095. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4096. const kinds: HeaterSensorKind[] = ['nozzle'];
  4097. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4098. kinds.push('bed');
  4099. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4100. return kinds;
  4101. })();
  4102. // active_extruder: 0=right, 1=left
  4103. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4104. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4105. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4106. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4107. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4108. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4109. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4110. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4111. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4112. 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 ${
  4113. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4114. }`;
  4115. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4116. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4117. // the widget there is at best dead UI and at worst suggests a
  4118. // control that does nothing. Mirrors the enclosure-door badge
  4119. // gate above.
  4120. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4121. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4122. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4123. // show it only when the printer actually reports it (airduct part id 3,
  4124. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4125. // have a built-in chamber fan that's always present, so they keep the
  4126. // existing model-list gate and the "Chamber Fan" label.
  4127. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4128. const chamberFanLabel = isExhaustModel
  4129. ? t('printers.fans.exhaust')
  4130. : t('printers.fans.chamber');
  4131. // Composed rather than either/or so both lists stay live for
  4132. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4133. // where that fan is an add-on kit — actually report it. Written
  4134. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4135. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4136. // which reads as if removing them were safe.
  4137. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4138. const fanItems: {
  4139. key: string;
  4140. label: string;
  4141. value: number;
  4142. Icon: typeof Fan;
  4143. activeClass: string;
  4144. }[] = [
  4145. {
  4146. key: 'part',
  4147. label: t('printers.fans.partCooling'),
  4148. value: status.cooling_fan_speed ?? 0,
  4149. Icon: Fan,
  4150. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4151. },
  4152. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4153. // Only reported (non-null) when the firmware lists airduct part
  4154. // id 10, i.e. when the fan is physically installed. Placed
  4155. // before the right-hand auxiliary fan so the two aux badges read
  4156. // left-to-right in the same order as the physical hardware.
  4157. ...(status.left_aux_fan_speed != null
  4158. ? [
  4159. {
  4160. key: 'aux2',
  4161. label: t('printers.fans.leftAuxiliary'),
  4162. value: status.left_aux_fan_speed,
  4163. Icon: Wind,
  4164. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4165. },
  4166. ]
  4167. : []),
  4168. {
  4169. key: 'aux',
  4170. label: t('printers.fans.auxiliary'),
  4171. value: status.big_fan1_speed ?? 0,
  4172. Icon: Wind,
  4173. activeClass: 'text-blue-600 dark:text-blue-400',
  4174. },
  4175. ...(showChamberFan
  4176. ? [
  4177. {
  4178. key: 'chamber',
  4179. label: chamberFanLabel,
  4180. value: status.big_fan2_speed ?? 0,
  4181. Icon: AirVent,
  4182. activeClass: 'text-green-600 dark:text-green-400',
  4183. },
  4184. ]
  4185. : []),
  4186. ];
  4187. return (
  4188. <>
  4189. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4190. {/* Nozzle temp - combined for dual nozzle */}
  4191. <div
  4192. className={statusControlClass}
  4193. title={statusControlTitle}
  4194. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4195. >
  4196. <button
  4197. type="button"
  4198. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4199. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4200. onClick={(e) => {
  4201. e.stopPropagation();
  4202. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4203. }}
  4204. >
  4205. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4206. </button>
  4207. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4208. {status.temperatures.nozzle_2 !== undefined ? (
  4209. <>
  4210. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4211. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4212. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4213. </p>
  4214. </>
  4215. ) : singleNozzleSlot ? (
  4216. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4217. <div className="cursor-default">
  4218. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4219. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4220. {Math.round(status.temperatures.nozzle || 0)}°C
  4221. </p>
  4222. </div>
  4223. </NozzleSlotHoverCard>
  4224. ) : (
  4225. <>
  4226. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4227. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4228. {Math.round(status.temperatures.nozzle || 0)}°C
  4229. </p>
  4230. </>
  4231. )}
  4232. {statusControlMenu === 'nozzle-temp' && (
  4233. isDualNozzle ? (
  4234. <IndicatorControlPopover
  4235. title="Set Nozzle Temperatures"
  4236. widthClass="w-[300px]"
  4237. popoverWidth={300}
  4238. popoverHeight={260}
  4239. isPending={nozzleTemperatureMutation.isPending}
  4240. onClose={() => setStatusControlMenu(null)}
  4241. >
  4242. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4243. <NozzleTemperatureControlBox
  4244. label="Left Temp"
  4245. current={status.temperatures.nozzle}
  4246. target={status.temperatures.nozzle_target}
  4247. isActive={activeNozzle === 'L'}
  4248. isPending={nozzleTemperatureMutation.isPending}
  4249. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4250. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4251. />
  4252. <NozzleTemperatureControlBox
  4253. label="Right Temp"
  4254. current={status.temperatures.nozzle_2}
  4255. target={status.temperatures.nozzle_2_target}
  4256. isActive={activeNozzle === 'R'}
  4257. isPending={nozzleTemperatureMutation.isPending}
  4258. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4259. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4260. />
  4261. </div>
  4262. </IndicatorControlPopover>
  4263. ) : (
  4264. <IndicatorControlPopover
  4265. title="Set Nozzle Temperature"
  4266. unit="°C"
  4267. customMin={0}
  4268. customMax={320}
  4269. isPending={nozzleTemperatureMutation.isPending}
  4270. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4271. onClose={() => setStatusControlMenu(null)}
  4272. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4273. />
  4274. )
  4275. )}
  4276. </div>
  4277. <div
  4278. className={statusControlClass}
  4279. title={statusControlTitle}
  4280. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4281. >
  4282. <button
  4283. type="button"
  4284. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4285. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4286. onClick={(e) => {
  4287. e.stopPropagation();
  4288. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4289. }}
  4290. >
  4291. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4292. </button>
  4293. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4294. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4295. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4296. {Math.round(status.temperatures.bed || 0)}°C
  4297. </p>
  4298. {statusControlMenu === 'bed-temp' && (
  4299. <IndicatorControlPopover
  4300. title="Set Bed Temperature"
  4301. unit="°C"
  4302. customMin={0}
  4303. customMax={140}
  4304. isPending={bedTemperatureMutation.isPending}
  4305. options={buildPresetOptions(bedTempPresets, 'C')}
  4306. onClose={() => setStatusControlMenu(null)}
  4307. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4308. />
  4309. )}
  4310. </div>
  4311. {status.temperatures.chamber !== undefined && (() => {
  4312. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4313. // but can't act on M141, so we keep the card read-only there.
  4314. const hasChamberHeater = status.supports_chamber_heater === true;
  4315. return (
  4316. <div
  4317. className={hasChamberHeater
  4318. ? statusControlClass
  4319. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4320. title={hasChamberHeater ? statusControlTitle : undefined}
  4321. onClick={hasChamberHeater
  4322. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4323. : undefined}
  4324. >
  4325. <button
  4326. type="button"
  4327. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4328. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4329. onClick={(e) => {
  4330. e.stopPropagation();
  4331. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4332. }}
  4333. >
  4334. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4335. </button>
  4336. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4337. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4338. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4339. {Math.round(status.temperatures.chamber || 0)}°C
  4340. </p>
  4341. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4342. <IndicatorControlPopover
  4343. title="Set Chamber Temperature"
  4344. unit="°C"
  4345. customMin={0}
  4346. customMax={MAX_CHAMBER_TEMP_C}
  4347. isPending={chamberTemperatureMutation.isPending}
  4348. options={buildPresetOptions(chamberTempPresets, 'C')}
  4349. onClose={() => setStatusControlMenu(null)}
  4350. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4351. />
  4352. )}
  4353. </div>
  4354. );
  4355. })()}
  4356. {/* Active nozzle indicator for dual-nozzle printers */}
  4357. {isDualNozzle && (
  4358. <DualNozzleHoverCard
  4359. leftSlot={leftNozzleSlot}
  4360. rightSlot={rightNozzleSlot}
  4361. activeNozzle={activeNozzle}
  4362. filamentInfo={filamentInfo}
  4363. >
  4364. <div
  4365. 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 ${
  4366. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4367. }`}
  4368. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4369. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4370. >
  4371. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4372. <div className="flex items-center gap-2">
  4373. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4374. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4375. </span>
  4376. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4377. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4378. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4379. </span>
  4380. </div>
  4381. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4382. {statusControlMenu === 'nozzle-select' && (
  4383. <IndicatorControlPopover
  4384. title="Set Nozzle Selection"
  4385. widthClass="w-[300px]"
  4386. popoverWidth={300}
  4387. popoverHeight={140}
  4388. isPending={selectExtruderMutation.isPending}
  4389. options={[
  4390. { label: 'Left', value: 1 },
  4391. { label: 'Right', value: 0 },
  4392. ]}
  4393. onClose={() => setStatusControlMenu(null)}
  4394. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4395. />
  4396. )}
  4397. </div>
  4398. </DualNozzleHoverCard>
  4399. )}
  4400. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4401. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4402. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4403. )}
  4404. </div>
  4405. <div className="mt-2 flex items-center gap-1.5">
  4406. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4407. const active = value > 0;
  4408. return (
  4409. <div
  4410. key={key}
  4411. 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 ${
  4412. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4413. }`}
  4414. title={canUseStatusControls ? label : statusControlTitle}
  4415. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4416. >
  4417. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4418. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4419. {value}%
  4420. </span>
  4421. {statusControlMenu === `fan-${key}` && (
  4422. <IndicatorControlPopover
  4423. title={`Set ${label} Speed`}
  4424. unit="%"
  4425. customMin={0}
  4426. customMax={100}
  4427. isPending={fanSpeedMutation.isPending}
  4428. options={buildPresetOptions(fanSpeedPresets, '%')}
  4429. onClose={() => setStatusControlMenu(null)}
  4430. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4431. />
  4432. )}
  4433. </div>
  4434. );
  4435. })}
  4436. </div>
  4437. </>
  4438. );
  4439. })()}
  4440. {viewMode === 'expanded' && showClearPlateButton && (
  4441. <button
  4442. type="button"
  4443. onClick={() => clearPlateMutation.mutate()}
  4444. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  4445. 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"
  4446. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  4447. >
  4448. {clearPlateMutation.isPending ? (
  4449. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  4450. ) : (
  4451. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4452. )}
  4453. {t('printers.plateStatus.markCleared')}
  4454. </button>
  4455. )}
  4456. {/* Controls */}
  4457. {viewMode === 'expanded' && (() => {
  4458. // Determine print state for control buttons
  4459. const isRunning = status.state === 'RUNNING';
  4460. const isPaused = status.state === 'PAUSE';
  4461. const isPrinting = isRunning || isPaused;
  4462. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4463. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4464. 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';
  4465. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4466. return (
  4467. <div className="mt-3">
  4468. {/* Section Header */}
  4469. <div className="flex items-center gap-2 mb-2">
  4470. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4471. {t('printers.controls')}
  4472. </span>
  4473. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4474. </div>
  4475. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4476. {/* Left: Secondary controls */}
  4477. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4478. <button
  4479. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4480. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4481. className={`${iconControlClass} ${
  4482. status.chamber_light
  4483. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4484. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4485. }`}
  4486. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4487. >
  4488. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4489. </button>
  4490. {/* Airduct Mode (P2S / X2D / H2*) */}
  4491. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4492. const isHeating = status.airduct_mode === 1;
  4493. const Icon = isHeating ? Flame : Snowflake;
  4494. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4495. 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';
  4496. return (
  4497. <div className="relative">
  4498. <button
  4499. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4500. disabled={!hasPermission('printers:control')}
  4501. className={`${iconControlClass} ${bg}`}
  4502. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4503. >
  4504. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4505. </button>
  4506. {showAirductMenu === printer.id && (
  4507. <>
  4508. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4509. <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]">
  4510. {([
  4511. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4512. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4513. ] as const).map(({ mode, label, modeId }) => (
  4514. <button
  4515. key={mode}
  4516. onClick={() => {
  4517. airductMutation.mutate(mode);
  4518. setShowAirductMenu(null);
  4519. }}
  4520. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4521. status.airduct_mode === modeId
  4522. ? 'text-bambu-green bg-bambu-green/10'
  4523. : 'text-white hover:bg-bambu-dark-tertiary'
  4524. }`}
  4525. >
  4526. {mode === 'heating' ? <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Snowflake className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4527. {label}
  4528. </button>
  4529. ))}
  4530. </div>
  4531. </>
  4532. )}
  4533. </div>
  4534. );
  4535. })()}
  4536. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4537. {(() => {
  4538. const canControl = hasPermission('printers:control');
  4539. const disabled = isPrinting || !canControl;
  4540. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  4541. 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';
  4542. const requestZJog = (direction: 1 | -1) => {
  4543. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  4544. // The jog never disables the soft endstops (#2579), so it's always
  4545. // safe: the firmware clamps the move at the travel limit, or refuses
  4546. // it if the printer isn't homed. No not-homed bypass to gate.
  4547. bedJogMutation.mutate({ distance: signed });
  4548. };
  4549. const requestXyJog = (x: number, y: number) => {
  4550. xyJogMutation.mutate({ x, y });
  4551. };
  4552. const requestExtruderJog = (distance: number) => {
  4553. extruderJogMutation.mutate(distance);
  4554. };
  4555. return (
  4556. <div className="relative">
  4557. <button
  4558. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4559. disabled={disabled}
  4560. className={`${iconControlClass} ${
  4561. disabled
  4562. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4563. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4564. }`}
  4565. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4566. >
  4567. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4568. </button>
  4569. {showBedJogMenu === printer.id && (
  4570. <>
  4571. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4572. <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">
  4573. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4574. {t('printers.bedJog.title')}
  4575. </div>
  4576. <div className="h-px bg-bambu-dark-tertiary" />
  4577. {/* #2579: Bambu firmware does not enforce soft endstops on
  4578. G-code sent over MQTT, so manual moves can drive past the
  4579. travel limits and cause a collision. Not fixable from our
  4580. side — warn prominently. */}
  4581. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[length:var(--pc-t11,11px)] leading-snug text-yellow-700 dark:text-yellow-400">
  4582. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4583. <span>{t('printers.bedJog.limitWarning')}</span>
  4584. </div>
  4585. <div className="h-px bg-bambu-dark-tertiary" />
  4586. <div className="flex justify-center px-3 py-2.5">
  4587. <div className="flex items-center justify-center gap-3">
  4588. <div className="grid grid-cols-3 gap-1">
  4589. <div />
  4590. <button
  4591. onClick={() => requestXyJog(0, bedJogStep)}
  4592. disabled={xyJogMutation.isPending}
  4593. className={jogButtonClass}
  4594. aria-label="Move Y forward"
  4595. >
  4596. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4597. </button>
  4598. <div />
  4599. <button
  4600. onClick={() => requestXyJog(-bedJogStep, 0)}
  4601. disabled={xyJogMutation.isPending}
  4602. className={jogButtonClass}
  4603. aria-label="Move X left"
  4604. >
  4605. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4606. </button>
  4607. <button
  4608. onClick={() => {
  4609. setShowBedJogMenu(null);
  4610. homeAxesMutation.mutate('all');
  4611. }}
  4612. disabled={homeAxesMutation.isPending}
  4613. className={jogButtonClass}
  4614. aria-label={t('printers.bedJog.homeZ')}
  4615. >
  4616. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4617. </button>
  4618. <button
  4619. onClick={() => requestXyJog(bedJogStep, 0)}
  4620. disabled={xyJogMutation.isPending}
  4621. className={jogButtonClass}
  4622. aria-label="Move X right"
  4623. >
  4624. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4625. </button>
  4626. <div />
  4627. <button
  4628. onClick={() => requestXyJog(0, -bedJogStep)}
  4629. disabled={xyJogMutation.isPending}
  4630. className={jogButtonClass}
  4631. aria-label="Move Y back"
  4632. >
  4633. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4634. </button>
  4635. <div />
  4636. </div>
  4637. <div className="flex flex-col items-center gap-1">
  4638. <button
  4639. onClick={() => requestZJog(-1)}
  4640. disabled={bedJogMutation.isPending}
  4641. className={jogButtonClass}
  4642. aria-label={t('printers.bedJog.up')}
  4643. >
  4644. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4645. </button>
  4646. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4647. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4648. </div>
  4649. <button
  4650. onClick={() => requestZJog(1)}
  4651. disabled={bedJogMutation.isPending}
  4652. className={jogButtonClass}
  4653. aria-label={t('printers.bedJog.down')}
  4654. >
  4655. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4656. </button>
  4657. </div>
  4658. <div className="flex flex-col items-center gap-1">
  4659. <button
  4660. onClick={() => requestExtruderJog(-bedJogStep)}
  4661. disabled={extruderJogMutation.isPending}
  4662. className={jogButtonClass}
  4663. aria-label="Retract filament"
  4664. >
  4665. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4666. </button>
  4667. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4668. <span className="text-sm font-semibold leading-none">E</span>
  4669. </div>
  4670. <button
  4671. onClick={() => requestExtruderJog(bedJogStep)}
  4672. disabled={extruderJogMutation.isPending}
  4673. className={jogButtonClass}
  4674. aria-label="Extrude filament"
  4675. >
  4676. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4677. </button>
  4678. </div>
  4679. </div>
  4680. </div>
  4681. <div className="h-px bg-bambu-dark-tertiary" />
  4682. <div className="px-3 pt-2.5 pb-3">
  4683. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4684. {t('printers.bedJog.step')}
  4685. </div>
  4686. <div className="flex gap-1">
  4687. {[1, 10, 50].map((step) => (
  4688. <button
  4689. key={step}
  4690. onClick={() => setBedJogStep(step)}
  4691. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4692. bedJogStep === step
  4693. ? 'bg-bambu-green/20 text-bambu-green'
  4694. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4695. }`}
  4696. >
  4697. {step}
  4698. </button>
  4699. ))}
  4700. </div>
  4701. </div>
  4702. </div>
  4703. </>
  4704. )}
  4705. </div>
  4706. );
  4707. })()}
  4708. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4709. <button
  4710. onClick={handleTogglePlateDetection}
  4711. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4712. className={`${iconControlClass} rounded-r-none ${
  4713. printer.plate_detection_enabled
  4714. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4715. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4716. }`}
  4717. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4718. >
  4719. {plateDetectionMutation.isPending ? (
  4720. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4721. ) : (
  4722. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4723. )}
  4724. </button>
  4725. <button
  4726. onClick={handleOpenPlateManagement}
  4727. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4728. 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 ${
  4729. printer.plate_detection_enabled
  4730. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4731. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4732. }`}
  4733. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4734. >
  4735. {isCheckingPlate ? (
  4736. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4737. ) : (
  4738. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4739. )}
  4740. </button>
  4741. </div>
  4742. {/* Print Speed */}
  4743. {(() => (
  4744. <div className="relative">
  4745. <button
  4746. data-testid="speed-control"
  4747. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4748. disabled={!isPrinting || !hasPermission('printers:control')}
  4749. className={`${iconControlClass} ${
  4750. isPrinting
  4751. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4752. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4753. }`}
  4754. title={isPrinting ? t('printers.speed.title') : undefined}
  4755. >
  4756. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4757. </button>
  4758. {showSpeedMenu === printer.id && (
  4759. <>
  4760. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4761. <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]">
  4762. {([
  4763. { mode: 1, label: t('printers.speed.silent') },
  4764. { mode: 2, label: t('printers.speed.standard') },
  4765. { mode: 3, label: t('printers.speed.sport') },
  4766. { mode: 4, label: t('printers.speed.ludicrous') },
  4767. ] as const).map(({ mode, label }) => (
  4768. <button
  4769. key={mode}
  4770. onClick={() => {
  4771. printSpeedMutation.mutate(mode);
  4772. setShowSpeedMenu(null);
  4773. }}
  4774. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4775. status.speed_level === mode
  4776. ? 'text-bambu-green bg-bambu-green/10'
  4777. : 'text-white hover:bg-bambu-dark-tertiary'
  4778. }`}
  4779. >
  4780. {label}
  4781. </button>
  4782. ))}
  4783. </div>
  4784. </>
  4785. )}
  4786. </div>
  4787. ))()}
  4788. </div>
  4789. {/* Right: Print Control Buttons */}
  4790. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4791. {/* Pause/Resume button */}
  4792. {(() => {
  4793. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4794. return (
  4795. <button
  4796. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4797. disabled={pauseUnavailable}
  4798. className={`
  4799. ${printControlClass}
  4800. ${pauseUnavailable
  4801. ? unavailablePrintActionClass
  4802. : isPaused
  4803. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4804. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4805. }
  4806. `}
  4807. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4808. >
  4809. {isPaused ? <Play className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Pause className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4810. {isPaused ? t('printers.resume') : t('printers.pause')}
  4811. </button>
  4812. );
  4813. })()}
  4814. {/* Stop button */}
  4815. {(() => {
  4816. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4817. return (
  4818. <button
  4819. onClick={() => setShowStopConfirm(true)}
  4820. disabled={stopUnavailable}
  4821. className={`
  4822. ${printControlClass}
  4823. ${stopUnavailable
  4824. ? unavailablePrintActionClass
  4825. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4826. }
  4827. `}
  4828. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4829. >
  4830. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4831. {t('printers.stop')}
  4832. </button>
  4833. );
  4834. })()}
  4835. </div>
  4836. </div>
  4837. </div>
  4838. );
  4839. })()}
  4840. {/* AMS Units - 2-Column Grid Layout */}
  4841. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4842. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4843. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4844. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4845. // The external spool can only be hidden while some AMS remains to
  4846. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  4847. // filament section, so the toggle is not offered there and a stored
  4848. // preference from a printer that later lost its AMS cannot blank the
  4849. // row either — both read through canHideExternalSpool.
  4850. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  4851. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  4852. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4853. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  4854. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  4855. // floating point, and that lands verbatim in the DOM.
  4856. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  4857. // Deliberately NOT scaled with the body (#1848). These AMS cards
  4858. // already grow to fill the row, so the 3.5rem is a floor they sit
  4859. // well above in practice -- raising it just costs a unit its place
  4860. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  4861. // its line, and flex-grow stretches its single slot across the whole
  4862. // card. The AMS-HT's own width does scale, below, because its
  4863. // readings sit beside the slot rather than under it.
  4864. const slotMinWidth = '3.5rem';
  4865. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  4866. // The AMS-HT holds a single spool, and its slot is the only thing
  4867. // on that row able to grow -- so it swallowed every spare pixel and
  4868. // shoved the temperature and humidity hard against the card's edge.
  4869. // Capping it at roughly two ordinary slots keeps the readings clear
  4870. // of the edge; the cap scales because the text inside the slot does.
  4871. const htSlotStyle: React.CSSProperties = {
  4872. minWidth: slotMinWidth,
  4873. maxWidth: scaledRem(7.25),
  4874. };
  4875. const slotGridStyle = (columns: number): React.CSSProperties => ({
  4876. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  4877. });
  4878. // #1762 (comment 2): while a print is running/paused, overlay a small
  4879. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4880. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4881. // staged to a printer with mismatched filament: the wrong-slot pill
  4882. // is visible the instant printing starts.
  4883. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4884. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4885. ? status.ams_mapping
  4886. : [];
  4887. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4888. const boundedSlotCount = Math.max(1, slotCount);
  4889. const gapCount = Math.max(0, boundedSlotCount - 1);
  4890. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  4891. return {
  4892. flex: `1 1 ${minWidth}`,
  4893. minWidth,
  4894. };
  4895. };
  4896. return (
  4897. <div className="mt-3">
  4898. {/* Section Header */}
  4899. <div className="flex items-center gap-2 mb-2">
  4900. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4901. {t('printers.filaments')}
  4902. </span>
  4903. <AmsBackupBadge
  4904. state={status.ams_filament_backup}
  4905. onClick={() => setAmsBackupModalOpen(true)}
  4906. />
  4907. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4908. {/* Offered only when an AMS is present: on a printer that
  4909. feeds from the external spool alone, hiding it would
  4910. empty the row entirely (#1782). */}
  4911. {canHideExternalSpool && (
  4912. <>
  4913. <ExternalSpoolToggle
  4914. hidden={externalSpoolHidden}
  4915. onClick={toggleExternalSpool}
  4916. />
  4917. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  4918. </>
  4919. )}
  4920. </div>
  4921. {/* AMS Content */}
  4922. <div className="flex flex-wrap gap-2">
  4923. {/* Regular AMS units */}
  4924. {regularAms.map((ams) => {
  4925. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  4926. return (
  4927. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4928. {/* Header: Label + Stats (no icon) */}
  4929. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4930. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4931. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4932. <AmsNameHoverCard
  4933. ams={ams}
  4934. printerId={printer.id}
  4935. label={getAmsLabel(ams.id, ams.tray.length)}
  4936. amsLabels={amsLabels}
  4937. canEdit={hasPermission('printers:update')}
  4938. onSaved={refetchAmsLabels}
  4939. >
  4940. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  4941. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4942. </span>
  4943. </AmsNameHoverCard>
  4944. {sideBadge?.kind === 'inlet' ? (
  4945. <InletBadge
  4946. inlet={sideBadge.inlet}
  4947. title={t('printers.amsSwitchInletTooltip', {
  4948. inlet: sideBadge.inlet,
  4949. side: FTS_INLET_SIDE[sideBadge.inlet],
  4950. })}
  4951. />
  4952. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  4953. <NozzleBadge side={sideBadge.side} />
  4954. ) : null}
  4955. </div>
  4956. {(ams.humidity != null || ams.temp != null) && (
  4957. <div className="flex shrink-0 items-center gap-1.5">
  4958. {ams.humidity != null && (
  4959. <HumidityIndicator
  4960. humidity={ams.humidity}
  4961. goodThreshold={amsThresholds?.humidityGood}
  4962. fairThreshold={amsThresholds?.humidityFair}
  4963. onClick={() => setAmsHistoryModal({
  4964. amsId: ams.id,
  4965. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4966. mode: 'humidity',
  4967. })}
  4968. compact
  4969. />
  4970. )}
  4971. {ams.temp != null && (
  4972. <div className="mr-1">
  4973. <TemperatureIndicator
  4974. temp={ams.temp}
  4975. goodThreshold={amsThresholds?.tempGood}
  4976. fairThreshold={amsThresholds?.tempFair}
  4977. onClick={() => setAmsHistoryModal({
  4978. amsId: ams.id,
  4979. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4980. mode: 'temperature',
  4981. })}
  4982. compact
  4983. />
  4984. </div>
  4985. )}
  4986. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4987. Screen-only models (P1 series) keep the control but can't
  4988. be commanded: it stays disabled and says why (#2533). */}
  4989. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4990. <button
  4991. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4992. onClick={(e) => {
  4993. if (ams.dry_time > 0) {
  4994. stopDryingMutation.mutate(ams.id);
  4995. } else if (dryingPopoverAmsId === ams.id) {
  4996. setDryingPopoverAmsId(null);
  4997. } else {
  4998. openDryingPopover(ams, e.currentTarget as HTMLElement);
  4999. }
  5000. }}
  5001. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5002. ams.dry_time > 0
  5003. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5004. : status.drying_screen_only || ams.dry_sf_reason?.length
  5005. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5006. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5007. }`}
  5008. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t(dryingBlockedKey(ams.dry_sf_reason)) : t('printers.drying.start')}
  5009. >
  5010. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5011. </button>
  5012. )}
  5013. </div>
  5014. )}
  5015. </div>
  5016. {/* Drying status bar */}
  5017. {ams.dry_time > 0 && (
  5018. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5019. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5020. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5021. {/* The temperature is only ever known from the target we
  5022. cached when sending the command — the filament can also
  5023. be read off a uniformly loaded unit, so it can outlive
  5024. the temperature (#2759). */}
  5025. {ams.dry_filament && (
  5026. <span className="text-amber-700/80 dark:text-amber-300/70">
  5027. {ams.dry_target_temp != null
  5028. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5029. : ams.dry_filament}
  5030. </span>
  5031. )}
  5032. <span className="text-amber-700/80 dark:text-amber-300/70">
  5033. {t('printers.drying.timeRemaining', {
  5034. time: ams.dry_time >= 60
  5035. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5036. : `${ams.dry_time}m`
  5037. })}
  5038. </span>
  5039. {/* A cycle on a screen-only model was started at the printer
  5040. and can only be stopped there (#2533). */}
  5041. {!status.drying_screen_only && (
  5042. <button
  5043. onClick={() => stopDryingMutation.mutate(ams.id)}
  5044. disabled={stopDryingMutation.isPending}
  5045. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5046. title={t('printers.drying.stop')}
  5047. >
  5048. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5049. </button>
  5050. )}
  5051. </div>
  5052. )}
  5053. {/* Slots grid: 4 columns - always render 4 slots */}
  5054. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5055. {[0, 1, 2, 3].map((slotIdx) => {
  5056. // Find tray data for this slot (may be undefined if data incomplete)
  5057. // Use array index if available, as tray.id may not always be set
  5058. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5059. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5060. const isEmpty = !tray?.tray_type;
  5061. const emptyKind = getEmptySlotKind(tray);
  5062. // Check if this is the currently loaded tray
  5063. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5064. const globalTrayId = ams.id * 4 + slotIdx;
  5065. const isActive = effectiveTrayNow === globalTrayId;
  5066. // Runout guidance (#2587): the slot the paused print now
  5067. // expects filament in, and the slot that ran out.
  5068. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5069. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5070. // Get cloud preset info if available
  5071. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5072. // Get saved slot preset mapping (for user-configured slots)
  5073. const slotPreset = slotPresets?.[globalTrayId];
  5074. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5075. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5076. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5077. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5078. // Slot-assigned-only spool fill (no tag link required)
  5079. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5080. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5081. : undefined;
  5082. const slotSpoolForFill = slotAssignmentForFill
  5083. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5084. : undefined;
  5085. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5086. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5087. : null;
  5088. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5089. const inventoryFill = (() => {
  5090. const sp = inventoryAssignment?.spool;
  5091. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5092. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5093. }
  5094. return null;
  5095. })();
  5096. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5097. // (inventory weight_used may be stale or over-counted — #676)
  5098. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5099. ? null : inventoryFill;
  5100. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5101. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5102. : resolvedInventoryFill !== null ? 'inventory' as const
  5103. : hasFillLevel ? 'ams' as const
  5104. : undefined;
  5105. // Build filament data for hover card
  5106. const filamentData = tray?.tray_type ? {
  5107. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5108. // Spoolman spool name wins over cloud lookup so a slot bound to
  5109. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5110. // Design PLA") instead of whatever the printer's filament_id
  5111. // resolves to in the cloud catalog (often "Generic PLA" for
  5112. // P-prefix local presets). Spoolman's filament.name is just the
  5113. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5114. // the hover card shows "Devil Design PLA Basic" rather than the
  5115. // vendor-less form. Strip the "@<printer>..." suffix that
  5116. // BambuStudio appends to user-preset names.
  5117. 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,
  5118. colorName: getColorName(tray.tray_color || ''),
  5119. colorHex: tray.tray_color || null,
  5120. kFactor: formatKValue(tray.k),
  5121. fillLevel: effectiveFill,
  5122. trayUuid: tray.tray_uuid || null,
  5123. tagUid: tray.tag_uid || null,
  5124. fillSource,
  5125. } : null;
  5126. // Check if this specific slot is being refreshed
  5127. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5128. refreshingSlot?.slotId === slotIdx;
  5129. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5130. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5131. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5132. ? `P${activePrintSlotIdx + 1}`
  5133. : null;
  5134. // Slot visual content (goes inside hover card)
  5135. const slotVisual = (
  5136. <div
  5137. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5138. isExpectedSlot
  5139. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5140. : isRanOutSlot
  5141. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5142. : isActive
  5143. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5144. : ''
  5145. }`}
  5146. >
  5147. {isExpectedSlot && (
  5148. <span
  5149. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5150. title={t('printers.expectedSlot.title')}
  5151. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5152. >
  5153. ↓
  5154. </span>
  5155. )}
  5156. {activePrintSlotLabel && (
  5157. <span
  5158. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5159. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5160. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5161. >
  5162. {activePrintSlotLabel}
  5163. </span>
  5164. )}
  5165. {/* Filament color circle with 1-based slot number centered inside */}
  5166. <FilamentSlotCircle
  5167. trayColor={tray?.tray_color}
  5168. trayType={tray?.tray_type}
  5169. isEmpty={isEmpty}
  5170. emptyKind={emptyKind}
  5171. slotNumber={slotIdx + 1}
  5172. />
  5173. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5174. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5175. </div>
  5176. {/* Fill bar */}
  5177. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5178. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5179. <div
  5180. className="h-full rounded-full transition-all"
  5181. style={{
  5182. width: `${effectiveFill}%`,
  5183. backgroundColor: getFillBarColor(effectiveFill),
  5184. }}
  5185. />
  5186. )}
  5187. </div>
  5188. </div>
  5189. );
  5190. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5191. return (
  5192. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5193. {/* Loading overlay during RFID re-read */}
  5194. {isRefreshing && (
  5195. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5196. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5197. </div>
  5198. )}
  5199. {/* Hover card wraps only the visual content */}
  5200. {filamentData ? (
  5201. <FilamentHoverCard
  5202. data={filamentData}
  5203. actions={renderAmsSlotActions({
  5204. amsId: ams.id,
  5205. slotId: slotIdx,
  5206. loadTrayId: ams.id * 4 + slotIdx,
  5207. isRefreshing,
  5208. })}
  5209. spoolman={{
  5210. enabled: spoolmanEnabled,
  5211. // #1457: slot assignment is the user's most explicit action — it must
  5212. // outrank the tag-link, which can be stale when a non-RFID slot's
  5213. // fallback tag is still attached to a previous spool in Spoolman.
  5214. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5215. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5216. spoolmanUrl,
  5217. syncMode: spoolmanSyncMode,
  5218. // Suppress Link button when slot is already occupied by ANY assignment
  5219. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5220. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5221. // still appearing on slots with a local Devil Design PLA assigned.
  5222. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5223. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5224. setLinkSpoolModal({
  5225. tagUid: filamentData.tagUid || linkTag,
  5226. trayUuid: filamentData.trayUuid || '',
  5227. printerId: printer.id,
  5228. amsId: ams.id,
  5229. trayId: slotIdx,
  5230. });
  5231. } : undefined,
  5232. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5233. }}
  5234. inventory={(() => {
  5235. if (spoolmanEnabled) {
  5236. if (spoolmanLoading) return undefined;
  5237. const slotAssignment = slotAssignmentForFill;
  5238. const spoolmanSpool = slotSpoolForFill;
  5239. return {
  5240. assignedSpool: spoolmanSpool ? {
  5241. id: spoolmanSpool.id,
  5242. material: spoolmanSpool.material,
  5243. brand: spoolmanSpool.brand ?? null,
  5244. color_name: spoolmanSpool.color_name ?? null,
  5245. remainingWeightGrams: spoolmanSpool.label_weight
  5246. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5247. : undefined,
  5248. } : null,
  5249. onAssignSpool: () => setAssignSpoolModal({
  5250. printerId: printer.id,
  5251. amsId: ams.id,
  5252. trayId: slotIdx,
  5253. trayInfo: {
  5254. type: tray?.tray_type || filamentData.profile,
  5255. material: tray?.tray_type ?? undefined,
  5256. profile: filamentData.profile,
  5257. color: filamentData.colorHex || '',
  5258. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5259. },
  5260. }),
  5261. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5262. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5263. };
  5264. }
  5265. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5266. return {
  5267. assignedSpool: assignment?.spool ? {
  5268. id: assignment.spool.id,
  5269. material: assignment.spool.material,
  5270. brand: assignment.spool.brand,
  5271. color_name: assignment.spool.color_name,
  5272. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5273. } : null,
  5274. onAssignSpool: () => setAssignSpoolModal({
  5275. printerId: printer.id,
  5276. amsId: ams.id,
  5277. trayId: slotIdx,
  5278. trayInfo: {
  5279. type: tray?.tray_type || filamentData.profile,
  5280. material: tray?.tray_type ?? undefined,
  5281. profile: filamentData.profile,
  5282. color: filamentData.colorHex || '',
  5283. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5284. },
  5285. }),
  5286. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5287. isAssigned: !!assignment || isBambuLabSpool(tray),
  5288. };
  5289. })()}
  5290. configureSlot={{
  5291. enabled: hasPermission('printers:control'),
  5292. onConfigure: () => setConfigureSlotModal({
  5293. amsId: ams.id,
  5294. trayId: slotIdx,
  5295. trayCount: ams.tray.length,
  5296. trayType: tray?.tray_type || undefined,
  5297. trayColor: tray?.tray_color || undefined,
  5298. traySubBrands: tray?.tray_sub_brands || undefined,
  5299. trayInfoIdx: tray?.tray_info_idx || undefined,
  5300. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5301. caliIdx: tray?.cali_idx,
  5302. savedPresetId: slotPreset?.preset_id,
  5303. }),
  5304. }}
  5305. >
  5306. {slotVisual}
  5307. </FilamentHoverCard>
  5308. ) : (
  5309. <EmptySlotHoverCard
  5310. kind={emptyKind ?? undefined}
  5311. actions={renderAmsSlotActions({
  5312. amsId: ams.id,
  5313. slotId: slotIdx,
  5314. loadTrayId: ams.id * 4 + slotIdx,
  5315. isRefreshing,
  5316. })}
  5317. configureSlot={{
  5318. enabled: hasPermission('printers:control'),
  5319. onConfigure: () => setConfigureSlotModal({
  5320. amsId: ams.id,
  5321. trayId: slotIdx,
  5322. trayCount: ams.tray.length,
  5323. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5324. }),
  5325. }}
  5326. onAssignSpool={() => setAssignSpoolModal({
  5327. printerId: printer.id,
  5328. amsId: ams.id,
  5329. trayId: slotIdx,
  5330. trayInfo: {
  5331. type: '',
  5332. material: undefined,
  5333. profile: '',
  5334. color: '',
  5335. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5336. },
  5337. })}
  5338. >
  5339. {slotVisual}
  5340. </EmptySlotHoverCard>
  5341. )}
  5342. </div>
  5343. );
  5344. })}
  5345. </div>
  5346. </div>
  5347. );
  5348. })}
  5349. {/* HT AMS units */}
  5350. {htAms.map((ams) => {
  5351. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5352. const tray = ams.tray[0];
  5353. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5354. const isEmpty = !tray?.tray_type;
  5355. const emptyKind = getEmptySlotKind(tray);
  5356. // Check if this is the currently loaded tray
  5357. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5358. const isActive = effectiveTrayNow === globalTrayId;
  5359. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5360. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5361. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5362. // Get cloud preset info if available
  5363. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5364. // Get saved slot preset mapping (for user-configured slots)
  5365. const slotPreset = slotPresets?.[globalTrayId];
  5366. const htSlotId = tray?.id ?? 0;
  5367. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5368. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5369. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5370. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5371. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5372. const htInventoryFill = (() => {
  5373. const sp = htInventoryAssignment?.spool;
  5374. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5375. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5376. }
  5377. return null;
  5378. })();
  5379. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5380. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5381. ? null : htInventoryFill;
  5382. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5383. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5384. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5385. : undefined;
  5386. const htSlotSpoolForFill = htSlotAssignmentForFill
  5387. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5388. : undefined;
  5389. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5390. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5391. : null;
  5392. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5393. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5394. : htResolvedInventoryFill !== null ? 'inventory' as const
  5395. : hasFillLevel ? 'ams' as const
  5396. : undefined;
  5397. // Build filament data for hover card
  5398. const filamentData = tray?.tray_type ? {
  5399. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5400. 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,
  5401. colorName: getColorName(tray.tray_color || ''),
  5402. colorHex: tray.tray_color || null,
  5403. kFactor: formatKValue(tray.k),
  5404. fillLevel: htEffectiveFill,
  5405. trayUuid: tray.tray_uuid || null,
  5406. tagUid: tray.tag_uid || null,
  5407. fillSource: htFillSource,
  5408. } : null;
  5409. // Check if this specific slot is being refreshed
  5410. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5411. refreshingSlot?.slotId === htSlotId;
  5412. // #1762 (comment 2): active print-slot index for this HT slot.
  5413. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5414. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5415. ? `P${htActivePrintSlotIdx + 1}`
  5416. : null;
  5417. // Slot visual content (goes inside hover card)
  5418. const slotVisual = (
  5419. <div
  5420. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5421. isExpectedSlot
  5422. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5423. : isRanOutSlot
  5424. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5425. : isActive
  5426. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5427. : ''
  5428. }`}
  5429. >
  5430. {isExpectedSlot && (
  5431. <span
  5432. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5433. title={t('printers.expectedSlot.title')}
  5434. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5435. >
  5436. ↓
  5437. </span>
  5438. )}
  5439. {htActivePrintSlotLabel && (
  5440. <span
  5441. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5442. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5443. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5444. >
  5445. {htActivePrintSlotLabel}
  5446. </span>
  5447. )}
  5448. {/* Filament color circle with 1-based slot number centered inside */}
  5449. <FilamentSlotCircle
  5450. trayColor={tray?.tray_color}
  5451. trayType={tray?.tray_type}
  5452. isEmpty={isEmpty}
  5453. emptyKind={emptyKind}
  5454. slotNumber={1}
  5455. />
  5456. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5457. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5458. </div>
  5459. {/* Fill bar */}
  5460. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5461. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5462. <div
  5463. className="h-full rounded-full transition-all"
  5464. style={{
  5465. width: `${htEffectiveFill}%`,
  5466. backgroundColor: getFillBarColor(htEffectiveFill),
  5467. }}
  5468. />
  5469. )}
  5470. </div>
  5471. </div>
  5472. );
  5473. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5474. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5475. // Without this override, the L view squishes HT into a sliver next to the
  5476. // 4-slot AMS neighbors.
  5477. // 11rem holds one slot plus the temperature/humidity
  5478. // column beside it; both grow with the body scale.
  5479. const htCardWidth = scaledRem(11);
  5480. const htCardStyle: React.CSSProperties = {
  5481. flex: `1 1 ${htCardWidth}`,
  5482. minWidth: htCardWidth,
  5483. // An AMS-HT is never wider than a full AMS. Without a
  5484. // ceiling, a unit that wraps onto a line of its own is
  5485. // the only flex item there and grow stretches its single
  5486. // slot across the entire card, leaving the readings
  5487. // stranded at the far edge.
  5488. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5489. };
  5490. return (
  5491. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5492. {/* Row 1: Label + Nozzle + Drying */}
  5493. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5494. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5495. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5496. <AmsNameHoverCard
  5497. ams={ams}
  5498. printerId={printer.id}
  5499. label={getAmsLabel(ams.id, ams.tray.length)}
  5500. amsLabels={amsLabels}
  5501. canEdit={hasPermission('printers:update')}
  5502. onSaved={refetchAmsLabels}
  5503. >
  5504. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5505. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5506. </span>
  5507. </AmsNameHoverCard>
  5508. {sideBadge?.kind === 'inlet' ? (
  5509. <InletBadge
  5510. inlet={sideBadge.inlet}
  5511. title={t('printers.amsSwitchInletTooltip', {
  5512. inlet: sideBadge.inlet,
  5513. side: FTS_INLET_SIDE[sideBadge.inlet],
  5514. })}
  5515. />
  5516. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5517. <NozzleBadge side={sideBadge.side} />
  5518. ) : null}
  5519. </div>
  5520. {/* Drying button for HT AMS */}
  5521. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5522. <div className="relative ml-auto">
  5523. <button
  5524. disabled={status.drying_screen_only}
  5525. onClick={(e) => {
  5526. if (ams.dry_time > 0) {
  5527. stopDryingMutation.mutate(ams.id);
  5528. } else if (dryingPopoverAmsId === ams.id) {
  5529. setDryingPopoverAmsId(null);
  5530. } else {
  5531. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5532. }
  5533. }}
  5534. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5535. ams.dry_time > 0
  5536. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5537. : status.drying_screen_only
  5538. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5539. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5540. }`}
  5541. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5542. >
  5543. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5544. </button>
  5545. </div>
  5546. )}
  5547. </div>
  5548. {/* HT AMS drying status bar */}
  5549. {ams.dry_time > 0 && (
  5550. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5551. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5552. {ams.dry_filament && (
  5553. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5554. {ams.dry_target_temp != null
  5555. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5556. : ams.dry_filament}
  5557. </span>
  5558. )}
  5559. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5560. {ams.dry_time >= 60
  5561. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5562. : `${ams.dry_time}m`}
  5563. </span>
  5564. {!status.drying_screen_only && (
  5565. <button
  5566. onClick={() => stopDryingMutation.mutate(ams.id)}
  5567. disabled={stopDryingMutation.isPending}
  5568. 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"
  5569. title={t('printers.drying.stop')}
  5570. >
  5571. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5572. </button>
  5573. )}
  5574. </div>
  5575. )}
  5576. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5577. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5578. {/* Slot wrapper with loading overlay */}
  5579. <div className="relative group flex-1" style={htSlotStyle}>
  5580. {/* Loading overlay during RFID re-read */}
  5581. {isHtRefreshing && (
  5582. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5583. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5584. </div>
  5585. )}
  5586. {/* Hover card wraps only the visual content */}
  5587. {filamentData ? (
  5588. <FilamentHoverCard
  5589. data={filamentData}
  5590. actions={renderAmsSlotActions({
  5591. amsId: ams.id,
  5592. slotId: htSlotId,
  5593. loadTrayId: ams.id * 4 + htSlotId,
  5594. isRefreshing: isHtRefreshing,
  5595. })}
  5596. spoolman={{
  5597. enabled: spoolmanEnabled,
  5598. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5599. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5600. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5601. spoolmanUrl,
  5602. syncMode: spoolmanSyncMode,
  5603. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5604. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5605. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5606. setLinkSpoolModal({
  5607. tagUid: filamentData.tagUid || linkTag,
  5608. trayUuid: filamentData.trayUuid || '',
  5609. printerId: printer.id,
  5610. amsId: ams.id,
  5611. trayId: htSlotId,
  5612. });
  5613. } : undefined,
  5614. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5615. }}
  5616. inventory={(() => {
  5617. if (spoolmanEnabled) {
  5618. if (spoolmanLoading) return undefined;
  5619. const slotAssignment = htSlotAssignmentForFill;
  5620. const spoolmanSpool = htSlotSpoolForFill;
  5621. return {
  5622. assignedSpool: spoolmanSpool ? {
  5623. id: spoolmanSpool.id,
  5624. material: spoolmanSpool.material,
  5625. brand: spoolmanSpool.brand ?? null,
  5626. color_name: spoolmanSpool.color_name ?? null,
  5627. remainingWeightGrams: spoolmanSpool.label_weight
  5628. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5629. : undefined,
  5630. } : null,
  5631. onAssignSpool: () => setAssignSpoolModal({
  5632. printerId: printer.id,
  5633. amsId: ams.id,
  5634. trayId: htSlotId,
  5635. trayInfo: {
  5636. type: tray?.tray_type || filamentData.profile,
  5637. material: tray?.tray_type ?? undefined,
  5638. profile: filamentData.profile,
  5639. color: filamentData.colorHex || '',
  5640. location: getAmsLabel(ams.id, ams.tray.length),
  5641. },
  5642. }),
  5643. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5644. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5645. };
  5646. }
  5647. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5648. return {
  5649. assignedSpool: assignment?.spool ? {
  5650. id: assignment.spool.id,
  5651. material: assignment.spool.material,
  5652. brand: assignment.spool.brand,
  5653. color_name: assignment.spool.color_name,
  5654. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5655. } : null,
  5656. onAssignSpool: () => setAssignSpoolModal({
  5657. printerId: printer.id,
  5658. amsId: ams.id,
  5659. trayId: htSlotId,
  5660. trayInfo: {
  5661. type: tray?.tray_type || filamentData.profile,
  5662. material: tray?.tray_type ?? undefined,
  5663. profile: filamentData.profile,
  5664. color: filamentData.colorHex || '',
  5665. location: getAmsLabel(ams.id, ams.tray.length),
  5666. },
  5667. }),
  5668. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5669. isAssigned: !!assignment || isBambuLabSpool(tray),
  5670. };
  5671. })()}
  5672. configureSlot={{
  5673. enabled: hasPermission('printers:control'),
  5674. onConfigure: () => setConfigureSlotModal({
  5675. amsId: ams.id,
  5676. trayId: htSlotId,
  5677. trayCount: ams.tray.length,
  5678. trayType: tray?.tray_type || undefined,
  5679. trayColor: tray?.tray_color || undefined,
  5680. traySubBrands: tray?.tray_sub_brands || undefined,
  5681. trayInfoIdx: tray?.tray_info_idx || undefined,
  5682. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5683. caliIdx: tray?.cali_idx,
  5684. savedPresetId: slotPreset?.preset_id,
  5685. }),
  5686. }}
  5687. >
  5688. {slotVisual}
  5689. </FilamentHoverCard>
  5690. ) : (
  5691. <EmptySlotHoverCard
  5692. kind={emptyKind ?? undefined}
  5693. actions={renderAmsSlotActions({
  5694. amsId: ams.id,
  5695. slotId: htSlotId,
  5696. loadTrayId: ams.id * 4 + htSlotId,
  5697. isRefreshing: isHtRefreshing,
  5698. })}
  5699. configureSlot={{
  5700. enabled: hasPermission('printers:control'),
  5701. onConfigure: () => setConfigureSlotModal({
  5702. amsId: ams.id,
  5703. trayId: htSlotId,
  5704. trayCount: ams.tray.length,
  5705. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5706. }),
  5707. }}
  5708. onAssignSpool={() => setAssignSpoolModal({
  5709. printerId: printer.id,
  5710. amsId: ams.id,
  5711. trayId: htSlotId,
  5712. trayInfo: {
  5713. type: '',
  5714. material: undefined,
  5715. profile: '',
  5716. color: '',
  5717. location: getAmsLabel(ams.id, ams.tray.length),
  5718. },
  5719. })}
  5720. >
  5721. {slotVisual}
  5722. </EmptySlotHoverCard>
  5723. )}
  5724. </div>
  5725. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5726. {(ams.humidity != null || ams.temp != null) && (
  5727. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5728. {ams.temp != null && (
  5729. <TemperatureIndicator
  5730. temp={ams.temp}
  5731. goodThreshold={amsThresholds?.tempGood}
  5732. fairThreshold={amsThresholds?.tempFair}
  5733. onClick={() => setAmsHistoryModal({
  5734. amsId: ams.id,
  5735. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5736. mode: 'temperature',
  5737. })}
  5738. compact
  5739. />
  5740. )}
  5741. {ams.humidity != null && (
  5742. <HumidityIndicator
  5743. humidity={ams.humidity}
  5744. goodThreshold={amsThresholds?.humidityGood}
  5745. fairThreshold={amsThresholds?.humidityFair}
  5746. onClick={() => setAmsHistoryModal({
  5747. amsId: ams.id,
  5748. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5749. mode: 'humidity',
  5750. })}
  5751. compact
  5752. />
  5753. )}
  5754. </div>
  5755. )}
  5756. </div>
  5757. </div>
  5758. );
  5759. })}
  5760. {/* External spool(s) - grouped in one card like regular AMS */}
  5761. {status.vt_tray.length > 0 && showExternalSpool && (
  5762. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5763. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5764. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  5765. </div>
  5766. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  5767. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5768. const extTrayId = extTray.id ?? 254;
  5769. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5770. // generically — use active_extruder to determine L vs R:
  5771. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5772. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5773. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5774. (extTrayId === 255 && status.active_extruder === 0)
  5775. : effectiveTrayNow === extTrayId;
  5776. const slotTrayId = extTrayId - 254; // 0 or 1
  5777. const extLabel = isDualNozzle
  5778. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5779. : '';
  5780. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5781. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5782. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5783. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5784. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5785. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5786. const extInventoryFill = (() => {
  5787. const sp = extInventoryAssignment?.spool;
  5788. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5789. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5790. }
  5791. return null;
  5792. })();
  5793. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5794. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5795. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5796. ? null : extInventoryFill;
  5797. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5798. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5799. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5800. : undefined;
  5801. const extSlotSpoolForFill = extSlotAssignmentForFill
  5802. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5803. : undefined;
  5804. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5805. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5806. : null;
  5807. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5808. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5809. : extResolvedInventoryFill !== null ? 'inventory' as const
  5810. : extHasFillLevel ? 'ams' as const
  5811. : undefined;
  5812. const extFilamentData = {
  5813. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5814. 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',
  5815. colorName: getColorName(extTray.tray_color || ''),
  5816. colorHex: extTray.tray_color || null,
  5817. kFactor: formatKValue(extTray.k),
  5818. fillLevel: extEffectiveFill,
  5819. trayUuid: extTray.tray_uuid || null,
  5820. tagUid: extTray.tag_uid || null,
  5821. fillSource: extFillSource,
  5822. };
  5823. const isEmpty = !extTray.tray_type;
  5824. const emptyKind = getEmptySlotKind(extTray);
  5825. const extSlotContent = (
  5826. <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' : ''}`}>
  5827. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5828. the separate Ext-L/Ext-R caption that made the row taller than
  5829. regular AMS slots), 1-based slot number on single-nozzle. */}
  5830. <FilamentSlotCircle
  5831. trayColor={extTray.tray_color}
  5832. trayType={extTray.tray_type}
  5833. isEmpty={isEmpty}
  5834. emptyKind={emptyKind}
  5835. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5836. />
  5837. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5838. {extTray.tray_type || t('ams.slotEmpty')}
  5839. </div>
  5840. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5841. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5842. <div
  5843. className="h-full rounded-full transition-all"
  5844. style={{
  5845. width: `${extEffectiveFill}%`,
  5846. backgroundColor: getFillBarColor(extEffectiveFill),
  5847. }}
  5848. />
  5849. )}
  5850. </div>
  5851. </div>
  5852. );
  5853. return (
  5854. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  5855. {!isEmpty ? (
  5856. <FilamentHoverCard
  5857. data={extFilamentData}
  5858. actions={renderAmsSlotActions({
  5859. amsId: 255,
  5860. slotId: slotTrayId,
  5861. loadTrayId: extTrayId,
  5862. includeRfid: false,
  5863. })}
  5864. spoolman={{
  5865. enabled: spoolmanEnabled,
  5866. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5867. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5868. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5869. spoolmanUrl,
  5870. syncMode: spoolmanSyncMode,
  5871. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5872. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5873. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5874. setLinkSpoolModal({
  5875. tagUid: extFilamentData.tagUid || linkTag,
  5876. trayUuid: extFilamentData.trayUuid || '',
  5877. printerId: printer.id,
  5878. amsId: 255,
  5879. trayId: slotTrayId,
  5880. });
  5881. } : undefined,
  5882. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5883. }}
  5884. inventory={(() => {
  5885. if (spoolmanEnabled) {
  5886. if (spoolmanLoading) return undefined;
  5887. const slotAssignment = extSlotAssignmentForFill;
  5888. const spoolmanSpool = extSlotSpoolForFill;
  5889. return {
  5890. assignedSpool: spoolmanSpool ? {
  5891. id: spoolmanSpool.id,
  5892. material: spoolmanSpool.material,
  5893. brand: spoolmanSpool.brand ?? null,
  5894. color_name: spoolmanSpool.color_name ?? null,
  5895. remainingWeightGrams: spoolmanSpool.label_weight
  5896. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5897. : undefined,
  5898. } : null,
  5899. onAssignSpool: () => setAssignSpoolModal({
  5900. printerId: printer.id,
  5901. amsId: 255,
  5902. trayId: slotTrayId,
  5903. trayInfo: {
  5904. type: extTray.tray_type || extFilamentData.profile,
  5905. material: extTray.tray_type ?? undefined,
  5906. profile: extFilamentData.profile,
  5907. color: extFilamentData.colorHex || '',
  5908. location: extLabel || t('printers.external'),
  5909. },
  5910. }),
  5911. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5912. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5913. };
  5914. }
  5915. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5916. return {
  5917. assignedSpool: assignment?.spool ? {
  5918. id: assignment.spool.id,
  5919. material: assignment.spool.material,
  5920. brand: assignment.spool.brand,
  5921. color_name: assignment.spool.color_name,
  5922. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5923. } : null,
  5924. onAssignSpool: () => setAssignSpoolModal({
  5925. printerId: printer.id,
  5926. amsId: 255,
  5927. trayId: slotTrayId,
  5928. trayInfo: {
  5929. type: extTray.tray_type || extFilamentData.profile,
  5930. material: extTray.tray_type ?? undefined,
  5931. profile: extFilamentData.profile,
  5932. color: extFilamentData.colorHex || '',
  5933. location: extLabel || t('printers.external'),
  5934. },
  5935. }),
  5936. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5937. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5938. };
  5939. })()}
  5940. configureSlot={{
  5941. enabled: hasPermission('printers:control'),
  5942. onConfigure: () => setConfigureSlotModal({
  5943. amsId: 255,
  5944. trayId: slotTrayId,
  5945. trayCount: 1,
  5946. trayType: extTray.tray_type || undefined,
  5947. trayColor: extTray.tray_color || undefined,
  5948. traySubBrands: extTray.tray_sub_brands || undefined,
  5949. trayInfoIdx: extTray.tray_info_idx || undefined,
  5950. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5951. caliIdx: extTray.cali_idx,
  5952. savedPresetId: extSlotPreset?.preset_id,
  5953. }),
  5954. }}
  5955. >
  5956. {extSlotContent}
  5957. </FilamentHoverCard>
  5958. ) : (
  5959. <EmptySlotHoverCard
  5960. kind={emptyKind ?? undefined}
  5961. actions={renderAmsSlotActions({
  5962. amsId: 255,
  5963. slotId: slotTrayId,
  5964. loadTrayId: extTrayId,
  5965. includeRfid: false,
  5966. })}
  5967. configureSlot={{
  5968. enabled: hasPermission('printers:control'),
  5969. onConfigure: () => setConfigureSlotModal({
  5970. amsId: 255,
  5971. trayId: slotTrayId,
  5972. trayCount: 1,
  5973. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5974. }),
  5975. }}
  5976. onAssignSpool={() => setAssignSpoolModal({
  5977. printerId: printer.id,
  5978. amsId: 255,
  5979. trayId: slotTrayId,
  5980. trayInfo: {
  5981. type: '',
  5982. material: undefined,
  5983. profile: '',
  5984. color: '',
  5985. location: `External Slot ${slotTrayId + 1}`,
  5986. },
  5987. })}
  5988. >
  5989. {extSlotContent}
  5990. </EmptySlotHoverCard>
  5991. )}
  5992. </div>
  5993. );
  5994. })}
  5995. </div>
  5996. </div>
  5997. )}
  5998. </div>
  5999. </div>
  6000. );
  6001. })()}
  6002. </>
  6003. )}
  6004. {/* Bottom block (power row + action bar). Wrapped together so the
  6005. power row hugs the action bar at the card bottom instead of
  6006. floating up when there's less filament content above. */}
  6007. {viewMode === 'expanded' && (
  6008. <div className="mt-auto">
  6009. {smartPlug && (
  6010. <div className="pt-3">
  6011. <div className="flex items-center gap-2 mb-2">
  6012. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6013. {t('printers.power', 'Power')}
  6014. </span>
  6015. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6016. </div>
  6017. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6018. {/* Plug name + current power */}
  6019. <div className="flex items-center gap-2 min-w-0 pl-1">
  6020. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6021. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6022. <span
  6023. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[length:var(--pc-t10,10px)] font-medium flex-shrink-0"
  6024. title={t('smartPlugs.power')}
  6025. >
  6026. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6027. </span>
  6028. </div>
  6029. {/* Spacer */}
  6030. <div className="flex-1" />
  6031. <div className="flex items-center gap-2">
  6032. {/* Auto-off */}
  6033. <button
  6034. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6035. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6036. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6037. 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 ${
  6038. !hasPermission('smart_plugs:control')
  6039. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6040. : smartPlug.auto_off || smartPlug.auto_off_executed
  6041. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6042. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6043. }`}
  6044. >
  6045. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6046. </button>
  6047. <button
  6048. onClick={() => {
  6049. if (plugStatus?.state === 'ON') {
  6050. setShowPowerOffConfirm(true);
  6051. } else {
  6052. setShowPowerOnConfirm(true);
  6053. }
  6054. }}
  6055. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6056. 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 ${
  6057. !hasPermission('smart_plugs:control')
  6058. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6059. : plugStatus?.state === 'ON'
  6060. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6061. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6062. }`}
  6063. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6064. >
  6065. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6066. </button>
  6067. </div>
  6068. </div>
  6069. {/* HA entity buttons row */}
  6070. {scriptPlugs && scriptPlugs.length > 0 && (
  6071. <div className="flex items-center gap-2 mt-2">
  6072. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6073. <span className="text-xs text-bambu-gray">HA:</span>
  6074. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6075. <div className="flex flex-wrap gap-1">
  6076. {scriptPlugs.map(script => {
  6077. const isScript = script.ha_entity_id?.startsWith('script.');
  6078. return (
  6079. <button
  6080. key={script.id}
  6081. onClick={() => {
  6082. if (isScript) {
  6083. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6084. } else {
  6085. setHaToggleConfirm(script);
  6086. }
  6087. }}
  6088. disabled={runScriptMutation.isPending}
  6089. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6090. 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"
  6091. >
  6092. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6093. {script.name}
  6094. </button>
  6095. );
  6096. })}
  6097. </div>
  6098. </div>
  6099. )}
  6100. </div>
  6101. )}
  6102. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6103. a printer can have an enclosure door contact without having a plug,
  6104. and nesting it there would hide the row on exactly those setups. */}
  6105. <PrinterHASensorRow printerId={printer.id} />
  6106. {/* Connection Info & Actions */}
  6107. <div className="pt-4">
  6108. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6109. <div className="flex items-center justify-between gap-2">
  6110. {printerActionsMenu}
  6111. <div className="flex items-center justify-end gap-2 flex-wrap">
  6112. {/* Camera split button: the icon opens whichever view was used
  6113. last, the caret picks between the two and remembers it.
  6114. Replaces the old Settings > General > Camera switch, which
  6115. made choosing between an overlay and a window a trip to
  6116. another page for something you decide per camera. */}
  6117. <div className="flex items-center flex-shrink-0">
  6118. <Button
  6119. variant="secondary"
  6120. size="sm"
  6121. onClick={() => openCameraIn(cameraViewMode)}
  6122. disabled={!status?.connected || !hasPermission('camera:view')}
  6123. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6124. className={`${footerIconButtonClass} !rounded-r-none`}
  6125. >
  6126. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6127. </Button>
  6128. <Button
  6129. variant="secondary"
  6130. size="sm"
  6131. onClick={(e) => {
  6132. // No open/close toggle: the menu's own outside-mousedown
  6133. // handler has already dismissed it by the time this lands.
  6134. const rect = e.currentTarget.getBoundingClientRect();
  6135. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6136. }}
  6137. disabled={!status?.connected || !hasPermission('camera:view')}
  6138. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6139. aria-label={t('settings.cameraViewMode')}
  6140. // Not footerIconButtonClass plus an override: both widths
  6141. // would carry !important and the stylesheet's own order,
  6142. // not this one, would decide which won.
  6143. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6144. >
  6145. <ChevronDown className="w-3 h-3" />
  6146. </Button>
  6147. </div>
  6148. {cameraMenuAnchor && (
  6149. <ContextMenu
  6150. x={cameraMenuAnchor.x}
  6151. y={cameraMenuAnchor.y}
  6152. items={cameraViewModeMenuItems}
  6153. onClose={() => setCameraMenuAnchor(null)}
  6154. />
  6155. )}
  6156. <Button
  6157. variant="secondary"
  6158. size="sm"
  6159. onClick={() => setShowFileManager(true)}
  6160. disabled={!isConnected || !hasPermission('printers:files')}
  6161. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6162. className={footerIconButtonClass}
  6163. >
  6164. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6165. </Button>
  6166. {/* Shown whatever the printer is doing (#2849): this uploads a
  6167. file and queues it, which a busy or offline printer is no
  6168. reason to refuse -- it only means the item waits. Hiding it
  6169. while the drop zone accepted the same file would have left
  6170. the two routes into this flow disagreeing. */}
  6171. <Button
  6172. size="sm"
  6173. onClick={() => setShowUploadForPrint(true)}
  6174. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6175. title={
  6176. !hasPermission('library:upload')
  6177. ? t('fileManager.noPermissionUpload')
  6178. : !hasPermission('queue:create')
  6179. ? t('fileManager.noPermissionAddToQueue')
  6180. : t('common.print')
  6181. }
  6182. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6183. >
  6184. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6185. {t('common.print')}
  6186. </Button>
  6187. </div>
  6188. </div>
  6189. </div>
  6190. </div>
  6191. )}
  6192. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6193. card's horizontal padding instead of running full-bleed into the
  6194. rounded bottom edge. */}
  6195. <ScheduledDryingBanner
  6196. printerId={printer.id}
  6197. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6198. timeFormat={timeFormat}
  6199. />
  6200. </CardContent>
  6201. {/* File Manager Modal */}
  6202. {showFileManager && (
  6203. <FileManagerModal
  6204. printerId={printer.id}
  6205. printerName={printer.name}
  6206. onClose={() => setShowFileManager(false)}
  6207. />
  6208. )}
  6209. {/* Upload for Print Modal */}
  6210. {showUploadForPrint && (
  6211. <FileUploadModal
  6212. folderId={null}
  6213. onClose={() => setShowUploadForPrint(false)}
  6214. onUploadComplete={() => {}}
  6215. autoUpload
  6216. accept=".gcode,.3mf"
  6217. validateFile={(file) => {
  6218. const lower = file.name.toLowerCase();
  6219. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6220. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6221. }
  6222. }}
  6223. onFileUploaded={(uploadedFile) => {
  6224. // Check printer compatibility if sliced_for_model is available in metadata
  6225. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6226. const printerModel = mapModelCode(printer.model);
  6227. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6228. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6229. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6230. }
  6231. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6232. }}
  6233. />
  6234. )}
  6235. {/* Print Modal (after upload) */}
  6236. {printAfterUpload && (
  6237. <PrintModal
  6238. mode="create"
  6239. libraryFileId={printAfterUpload.id}
  6240. archiveName={printAfterUpload.filename}
  6241. initialSelectedPrinterIds={[printer.id]}
  6242. onClose={() => setPrintAfterUpload(null)}
  6243. onSuccess={() => setPrintAfterUpload(null)}
  6244. cleanupLibraryAfterDispatch
  6245. />
  6246. )}
  6247. {/* MQTT Debug Modal */}
  6248. {showMQTTDebug && (
  6249. <MQTTDebugModal
  6250. printerId={printer.id}
  6251. printerName={printer.name}
  6252. onClose={() => setShowMQTTDebug(false)}
  6253. />
  6254. )}
  6255. {showDiagnostic && (
  6256. <ConnectionDiagnosticModal
  6257. printerId={printer.id}
  6258. printerName={printer.name}
  6259. onClose={() => setShowDiagnostic(false)}
  6260. />
  6261. )}
  6262. {showPrinterInfo && (
  6263. <PrinterInfoModal
  6264. printer={printer}
  6265. status={status}
  6266. totalPrintHours={maintenanceInfo?.total_print_hours}
  6267. onClose={closePrinterInfo}
  6268. />
  6269. )}
  6270. {/* Plate Check Result Modal */}
  6271. {plateCheckResult && (
  6272. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6273. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6274. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6275. <div className="flex items-center gap-2">
  6276. {plateCheckResult.needs_calibration ? (
  6277. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6278. ) : plateCheckResult.is_empty ? (
  6279. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6280. ) : (
  6281. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6282. )}
  6283. <h2 className="text-lg font-semibold text-white">
  6284. Build Plate Check
  6285. </h2>
  6286. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6287. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6288. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6289. </span>
  6290. )}
  6291. </div>
  6292. <button
  6293. onClick={() => closePlateCheckModal()}
  6294. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6295. >
  6296. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6297. </button>
  6298. </div>
  6299. <div className="p-4 space-y-4">
  6300. {plateCheckResult.needs_calibration ? (
  6301. <>
  6302. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6303. <p className="font-medium text-blue-700 dark:text-blue-400">
  6304. {t('printers.plateDetection.calibrationRequired')}
  6305. </p>
  6306. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6307. </div>
  6308. <div className="text-sm text-bambu-gray space-y-2">
  6309. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6310. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6311. </div>
  6312. </>
  6313. ) : (
  6314. <>
  6315. <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'}`}>
  6316. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6317. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6318. </p>
  6319. <p className="text-sm text-bambu-gray mt-1">
  6320. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6321. </p>
  6322. </div>
  6323. {plateCheckResult.debug_image_url && (
  6324. <div>
  6325. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6326. <img
  6327. src={plateCheckResult.debug_image_url}
  6328. alt={t('printers.plateDetection.analysisPreview')}
  6329. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6330. />
  6331. <p className="text-xs text-bambu-gray mt-2">
  6332. {t('printers.plateDetection.analysisLegend')}
  6333. </p>
  6334. </div>
  6335. )}
  6336. <p className="text-xs text-bambu-gray">
  6337. {plateCheckResult.message}
  6338. </p>
  6339. </>
  6340. )}
  6341. {/* Saved References Grid */}
  6342. {plateReferences && plateReferences.references.length > 0 && (
  6343. <div className="mt-4">
  6344. <div className="flex items-center gap-2 mb-2">
  6345. <p className="text-sm font-medium text-white shrink-0">
  6346. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6347. </p>
  6348. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6349. </div>
  6350. <div className="grid grid-cols-5 gap-2">
  6351. {plateReferences.references.map((ref) => (
  6352. <div key={ref.index} className="relative group">
  6353. <img
  6354. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6355. alt={ref.label || `Reference ${ref.index + 1}`}
  6356. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6357. />
  6358. {/* Delete button */}
  6359. <button
  6360. onClick={() => handleDeleteRef(ref.index)}
  6361. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  6362. title={t('printers.plateDetection.deleteReference')}
  6363. >
  6364. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6365. </button>
  6366. {/* Label */}
  6367. {editingRefLabel?.index === ref.index ? (
  6368. <input
  6369. type="text"
  6370. value={editingRefLabel.label}
  6371. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6372. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6373. onKeyDown={(e) => {
  6374. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6375. if (e.key === 'Escape') setEditingRefLabel(null);
  6376. }}
  6377. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6378. autoFocus
  6379. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6380. />
  6381. ) : (
  6382. <p
  6383. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6384. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6385. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6386. >
  6387. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6388. </p>
  6389. )}
  6390. {/* Timestamp */}
  6391. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6392. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6393. </p>
  6394. </div>
  6395. ))}
  6396. </div>
  6397. </div>
  6398. )}
  6399. {/* ROI Editor */}
  6400. {!plateCheckResult.needs_calibration && (
  6401. <div className="mt-4">
  6402. <div className="flex items-center justify-between mb-2">
  6403. <div className="flex min-w-0 flex-1 items-center gap-2">
  6404. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6405. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6406. </div>
  6407. {!editingRoi ? (
  6408. <Button
  6409. variant="ghost"
  6410. size="sm"
  6411. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6412. >
  6413. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6414. {t('common.edit')}
  6415. </Button>
  6416. ) : (
  6417. <div className="flex gap-1">
  6418. <Button
  6419. variant="ghost"
  6420. size="sm"
  6421. onClick={() => setEditingRoi(null)}
  6422. disabled={isSavingRoi}
  6423. >
  6424. {t('common.cancel')}
  6425. </Button>
  6426. <Button
  6427. size="sm"
  6428. onClick={handleSaveRoi}
  6429. disabled={isSavingRoi}
  6430. >
  6431. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6432. </Button>
  6433. </div>
  6434. )}
  6435. </div>
  6436. {editingRoi ? (
  6437. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6438. <div className="grid grid-cols-2 gap-3">
  6439. <div>
  6440. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6441. <input
  6442. type="range"
  6443. min="0"
  6444. max="0.9"
  6445. step="0.01"
  6446. value={editingRoi.x}
  6447. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6448. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6449. />
  6450. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6451. </div>
  6452. <div>
  6453. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6454. <input
  6455. type="range"
  6456. min="0"
  6457. max="0.9"
  6458. step="0.01"
  6459. value={editingRoi.y}
  6460. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6461. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6462. />
  6463. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6464. </div>
  6465. <div>
  6466. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6467. <input
  6468. type="range"
  6469. min="0.1"
  6470. max="1"
  6471. step="0.01"
  6472. value={editingRoi.w}
  6473. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6474. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6475. />
  6476. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6477. </div>
  6478. <div>
  6479. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6480. <input
  6481. type="range"
  6482. min="0.1"
  6483. max="1"
  6484. step="0.01"
  6485. value={editingRoi.h}
  6486. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6487. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6488. />
  6489. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6490. </div>
  6491. </div>
  6492. <p className="text-xs text-bambu-gray">
  6493. {t('printers.roi.instruction')}
  6494. </p>
  6495. </div>
  6496. ) : (
  6497. <p className="text-xs text-bambu-gray">
  6498. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6499. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6500. </p>
  6501. )}
  6502. </div>
  6503. )}
  6504. </div>
  6505. <div className="flex justify-end gap-2 p-4">
  6506. {plateCheckResult.needs_calibration ? (
  6507. <>
  6508. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6509. {t('common.cancel')}
  6510. </Button>
  6511. <Button
  6512. onClick={() => handleCalibratePlate()}
  6513. disabled={isCalibrating}
  6514. >
  6515. {isCalibrating ? (
  6516. <>
  6517. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6518. Calibrating...
  6519. </>
  6520. ) : (
  6521. 'Calibrate Empty Plate'
  6522. )}
  6523. </Button>
  6524. </>
  6525. ) : (
  6526. <>
  6527. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6528. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6529. </Button>
  6530. <Button onClick={() => closePlateCheckModal()}>
  6531. Close
  6532. </Button>
  6533. </>
  6534. )}
  6535. </div>
  6536. </div>
  6537. </div>
  6538. )}
  6539. {/* Power On Confirmation */}
  6540. {showPowerOnConfirm && smartPlug && (
  6541. <ConfirmModal
  6542. title={t('printers.confirm.powerOnTitle')}
  6543. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6544. confirmText={t('printers.confirm.powerOnButton')}
  6545. variant="default"
  6546. onConfirm={() => {
  6547. powerControlMutation.mutate('on');
  6548. setShowPowerOnConfirm(false);
  6549. }}
  6550. onCancel={() => setShowPowerOnConfirm(false)}
  6551. />
  6552. )}
  6553. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6554. disconnects MQTT, which stops progress tracking + completion
  6555. notifications for the in-flight job. Idle / FINISH / FAILED states
  6556. skip this dialog and toggle directly. */}
  6557. {confirmMaintenanceEnter && (
  6558. <ConfirmModal
  6559. title={t('printers.maintenance.confirmMidPrintTitle')}
  6560. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6561. confirmText={t('printers.maintenance.menuEnter')}
  6562. variant="danger"
  6563. onConfirm={() => {
  6564. maintenanceMutation.mutate(false);
  6565. setConfirmMaintenanceEnter(false);
  6566. }}
  6567. onCancel={() => setConfirmMaintenanceEnter(false)}
  6568. />
  6569. )}
  6570. {/* Power Off Confirmation */}
  6571. {showPowerOffConfirm && smartPlug && (
  6572. <ConfirmModal
  6573. title={t('printers.confirm.powerOffTitle')}
  6574. message={
  6575. status?.state === 'RUNNING'
  6576. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6577. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6578. }
  6579. confirmText={t('printers.confirm.powerOffButton')}
  6580. variant="danger"
  6581. onConfirm={() => {
  6582. powerControlMutation.mutate('off');
  6583. setShowPowerOffConfirm(false);
  6584. }}
  6585. onCancel={() => setShowPowerOffConfirm(false)}
  6586. />
  6587. )}
  6588. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6589. {haToggleConfirm && (
  6590. <ConfirmModal
  6591. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6592. message={
  6593. status?.state === 'RUNNING'
  6594. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6595. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6596. }
  6597. confirmText={t('printers.confirm.haToggleButton')}
  6598. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6599. onConfirm={() => {
  6600. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6601. setHaToggleConfirm(null);
  6602. }}
  6603. onCancel={() => setHaToggleConfirm(null)}
  6604. />
  6605. )}
  6606. {/* Stop Print Confirmation */}
  6607. {showStopConfirm && (
  6608. <ConfirmModal
  6609. title={t('printers.confirm.stopTitle')}
  6610. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6611. confirmText={t('printers.confirm.stopButton')}
  6612. variant="danger"
  6613. onConfirm={() => {
  6614. stopPrintMutation.mutate();
  6615. setShowStopConfirm(false);
  6616. }}
  6617. onCancel={() => setShowStopConfirm(false)}
  6618. />
  6619. )}
  6620. {/* Pause Print Confirmation */}
  6621. {showPauseConfirm && (
  6622. <ConfirmModal
  6623. title={t('printers.confirm.pauseTitle')}
  6624. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6625. confirmText={t('printers.confirm.pauseButton')}
  6626. variant="default"
  6627. onConfirm={() => {
  6628. pausePrintMutation.mutate();
  6629. setShowPauseConfirm(false);
  6630. }}
  6631. onCancel={() => setShowPauseConfirm(false)}
  6632. />
  6633. )}
  6634. {/* Resume Print Confirmation */}
  6635. {showResumeConfirm && (
  6636. <ConfirmModal
  6637. title={t('printers.confirm.resumeTitle')}
  6638. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6639. confirmText={t('printers.confirm.resumeButton')}
  6640. variant="default"
  6641. onConfirm={() => {
  6642. resumePrintMutation.mutate();
  6643. setShowResumeConfirm(false);
  6644. }}
  6645. onCancel={() => setShowResumeConfirm(false)}
  6646. />
  6647. )}
  6648. {/* Skip Objects Modal */}
  6649. <SkipObjectsModal
  6650. printerId={printer.id}
  6651. isOpen={showSkipObjectsModal}
  6652. onClose={() => setShowSkipObjectsModal(false)}
  6653. />
  6654. {/* HMS Error Modal */}
  6655. {showHMSModal && (
  6656. <HMSErrorModal
  6657. printerName={printer.name}
  6658. errors={status?.hms_errors || []}
  6659. onClose={() => setShowHMSModal(false)}
  6660. printerId={printer.id}
  6661. hasPermission={hasPermission}
  6662. runoutGuidance={runoutGuidance}
  6663. />
  6664. )}
  6665. {/* AI failure detection modal (#1546) */}
  6666. {showAiModal && (
  6667. <AiDetectionModal
  6668. printerName={printer.name}
  6669. detection={aiDetection}
  6670. lastError={aiLastError}
  6671. onClose={() => setShowAiModal(false)}
  6672. />
  6673. )}
  6674. {/* AMS Filament Backup status / control modal (#1762) */}
  6675. {amsBackupModalOpen && status && (
  6676. <AmsBackupModal
  6677. isOpen={amsBackupModalOpen}
  6678. state={status.ams_filament_backup}
  6679. amsUnits={status.ams}
  6680. amsExtruderMap={status.ams_extruder_map}
  6681. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6682. canToggle={hasPermission('printers:control')}
  6683. pending={setAmsBackupMutation.isPending}
  6684. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6685. onClose={() => setAmsBackupModalOpen(false)}
  6686. />
  6687. )}
  6688. {/* AMS History Modal */}
  6689. {amsHistoryModal && (
  6690. <AMSHistoryModal
  6691. isOpen={!!amsHistoryModal}
  6692. onClose={() => setAmsHistoryModal(null)}
  6693. printerId={printer.id}
  6694. printerName={printer.name}
  6695. amsId={amsHistoryModal.amsId}
  6696. amsLabel={amsHistoryModal.amsLabel}
  6697. initialMode={amsHistoryModal.mode}
  6698. thresholds={amsThresholds}
  6699. />
  6700. )}
  6701. {/* Heater History Modal (nozzle / bed / chamber) */}
  6702. {heaterHistoryModal && (
  6703. <HeaterHistoryModal
  6704. isOpen={!!heaterHistoryModal}
  6705. onClose={() => setHeaterHistoryModal(null)}
  6706. printerId={printer.id}
  6707. printerName={printer.name}
  6708. initialKind={heaterHistoryModal.initialKind}
  6709. availableKinds={heaterHistoryModal.availableKinds}
  6710. />
  6711. )}
  6712. {/* Link Spool Modal */}
  6713. {linkSpoolModal && (
  6714. <LinkSpoolModal
  6715. isOpen={!!linkSpoolModal}
  6716. onClose={() => setLinkSpoolModal(null)}
  6717. tagUid={linkSpoolModal.tagUid}
  6718. trayUuid={linkSpoolModal.trayUuid}
  6719. printerId={linkSpoolModal.printerId}
  6720. amsId={linkSpoolModal.amsId}
  6721. trayId={linkSpoolModal.trayId}
  6722. />
  6723. )}
  6724. {/* Assign Spool Modal */}
  6725. {assignSpoolModal && (
  6726. <AssignSpoolModal
  6727. isOpen={!!assignSpoolModal}
  6728. onClose={() => setAssignSpoolModal(null)}
  6729. printerId={assignSpoolModal.printerId}
  6730. amsId={assignSpoolModal.amsId}
  6731. trayId={assignSpoolModal.trayId}
  6732. trayInfo={assignSpoolModal.trayInfo}
  6733. spoolmanEnabled={!!spoolmanEnabled}
  6734. />
  6735. )}
  6736. {/* Configure AMS Slot Modal */}
  6737. {configureSlotModal && (
  6738. <ConfigureAmsSlotModal
  6739. isOpen={!!configureSlotModal}
  6740. onClose={() => setConfigureSlotModal(null)}
  6741. printerId={printer.id}
  6742. slotInfo={configureSlotModal}
  6743. printerModel={mapModelCode(printer.model) || undefined}
  6744. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6745. onSuccess={() => {
  6746. // Refresh slot presets to show updated profile name
  6747. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6748. // Printer status will update automatically via WebSocket when AMS data changes
  6749. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6750. }}
  6751. />
  6752. )}
  6753. {/* Edit Printer Modal */}
  6754. {showEditModal && (
  6755. <EditPrinterModal
  6756. printer={printer}
  6757. onClose={() => setShowEditModal(false)}
  6758. />
  6759. )}
  6760. {/* Firmware Update Modal */}
  6761. {showFirmwareModal && firmwareInfo && (
  6762. <FirmwareUpdateModal
  6763. printer={printer}
  6764. firmwareInfo={firmwareInfo}
  6765. onClose={() => setShowFirmwareModal(false)}
  6766. />
  6767. )}
  6768. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6769. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6770. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6771. const sliderMin = 35;
  6772. const sliderMax = maxTemp + 10;
  6773. return (
  6774. <>
  6775. {/* Backdrop */}
  6776. <div
  6777. className="fixed inset-0 z-[100]"
  6778. data-testid="drying-popover-backdrop"
  6779. onMouseDown={() => {
  6780. // The click that dismisses the native datetime picker lands
  6781. // here; it must not close the popover. The input is still
  6782. // focused at mousedown, so remember that and swallow the
  6783. // matching click.
  6784. dryingBackdropSkipCloseRef.current =
  6785. dryingAtTimeInputRef.current !== null &&
  6786. document.activeElement === dryingAtTimeInputRef.current;
  6787. }}
  6788. onClick={() => {
  6789. if (dryingBackdropSkipCloseRef.current) {
  6790. dryingBackdropSkipCloseRef.current = false;
  6791. return;
  6792. }
  6793. setDryingPopoverAmsId(null);
  6794. }}
  6795. />
  6796. {/* An 'above' popover is anchored by its bottom edge (CSS
  6797. bottom) so late-appearing content grows it upward, staying on
  6798. screen and glued to the trigger. maxHeight caps to the space
  6799. on the anchored side; when the viewport is too short the body
  6800. scrolls and the footer stays pinned. dvh so iOS Safari's
  6801. bottom toolbar doesn't clip the footer. */}
  6802. <div
  6803. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6804. style={{
  6805. left: dryingPopoverPos.left,
  6806. ...(dryingPopoverPos.placement === 'above'
  6807. ? {
  6808. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  6809. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  6810. }
  6811. : {
  6812. top: dryingPopoverPos.top,
  6813. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6814. }),
  6815. }}
  6816. onClick={e => e.stopPropagation()}
  6817. >
  6818. {/* Header */}
  6819. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6820. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  6821. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6822. </div>
  6823. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6824. {/* Body */}
  6825. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6826. {/* Filament type select */}
  6827. <div>
  6828. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6829. <ToolbarDropdown
  6830. value={dryingFilament}
  6831. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6832. onChange={fil => {
  6833. setDryingFilament(fil);
  6834. const preset = dryingPresets[fil];
  6835. if (preset) {
  6836. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6837. setDryingTemp(preset[key]);
  6838. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6839. }
  6840. }}
  6841. fullWidth
  6842. />
  6843. </div>
  6844. {/* Temperature */}
  6845. <div>
  6846. <div className="flex items-center justify-between mb-1">
  6847. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6848. <div className="flex items-center gap-1">
  6849. <input
  6850. type="number"
  6851. min={45}
  6852. max={maxTemp}
  6853. value={dryingTemp}
  6854. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6855. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6856. />
  6857. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  6858. </div>
  6859. </div>
  6860. <input
  6861. type="range"
  6862. min={sliderMin}
  6863. max={sliderMax}
  6864. value={dryingTemp}
  6865. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6866. className="w-full h-1 accent-bambu-green cursor-pointer"
  6867. />
  6868. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6869. <span>45°C</span>
  6870. <span>{maxTemp}°C</span>
  6871. </div>
  6872. </div>
  6873. {/* Duration */}
  6874. <div>
  6875. <div className="flex items-center justify-between mb-1">
  6876. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6877. <div className="flex items-center gap-1">
  6878. <input
  6879. type="number"
  6880. min={1}
  6881. max={24}
  6882. value={dryingDuration}
  6883. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6884. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6885. />
  6886. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  6887. </div>
  6888. </div>
  6889. <input
  6890. type="range"
  6891. min={1}
  6892. max={24}
  6893. value={dryingDuration}
  6894. onChange={e => setDryingDuration(Number(e.target.value))}
  6895. className="w-full h-1 accent-bambu-green cursor-pointer"
  6896. />
  6897. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6898. <span>1h</span>
  6899. <span>24h</span>
  6900. </div>
  6901. </div>
  6902. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6903. filament threaded out into the feed tube. The whole AMS
  6904. rotates as one mechanism (all 4 spools turn together), so a
  6905. single loaded slot locks the entire unit. Bambu per-tray
  6906. `state`: 9 = empty, 10 = spool present but not loaded
  6907. (rotation possible), 11 = loaded into tube (rotation impossible).
  6908. Catches both mid-print (active feed) AND idle-with-threaded-
  6909. filament — the H2D's post-print state leaves filament in the
  6910. tube but tray_now resets to 255, which a tray_now-only check
  6911. would silently miss. */}
  6912. {(() => {
  6913. const targetAms = dryingPopoverAmsId !== null
  6914. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6915. : undefined;
  6916. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6917. tray => tray.state === 11,
  6918. );
  6919. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6920. return (
  6921. <button
  6922. type="button"
  6923. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6924. aria-pressed={rotateChecked}
  6925. disabled={trayLoadedInThisAms}
  6926. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6927. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6928. rotateChecked
  6929. ? 'bg-bambu-green border-bambu-green text-white'
  6930. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6931. }`}
  6932. >
  6933. {t('printers.drying.rotateTray')}
  6934. </button>
  6935. );
  6936. })()}
  6937. {/* Start mode: now / after delay / at time (#2638) */}
  6938. <div>
  6939. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  6940. <div className="grid grid-cols-3 gap-1">
  6941. {(['now', 'delay', 'at_time'] as const).map(mode => (
  6942. <button
  6943. key={mode}
  6944. type="button"
  6945. onClick={() => setDryingStartMode(mode)}
  6946. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  6947. dryingStartMode === mode
  6948. ? 'bg-bambu-green border-bambu-green text-white'
  6949. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  6950. }`}
  6951. >
  6952. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  6953. </button>
  6954. ))}
  6955. </div>
  6956. {dryingStartMode === 'delay' && (
  6957. // Inline chips: a dropdown menu would be clipped by
  6958. // the popover's scrollable body.
  6959. <div className="mt-1.5 grid grid-cols-4 gap-1">
  6960. {DRYING_DELAY_OPTIONS.map(min => (
  6961. <button
  6962. key={min}
  6963. type="button"
  6964. aria-pressed={dryingDelayMinutes === min}
  6965. onClick={() => setDryingDelayMinutes(min)}
  6966. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  6967. dryingDelayMinutes === min
  6968. ? 'bg-bambu-green border-bambu-green text-white'
  6969. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  6970. }`}
  6971. >
  6972. {formatDurationFromHours(min / 60)}
  6973. </button>
  6974. ))}
  6975. </div>
  6976. )}
  6977. {dryingStartMode === 'at_time' && (
  6978. <input
  6979. ref={dryingAtTimeInputRef}
  6980. type="datetime-local"
  6981. data-testid="drying-start-at"
  6982. value={dryingStartAt}
  6983. onChange={e => setDryingStartAt(e.target.value)}
  6984. className="mt-1.5 w-full px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] focus:outline-none focus:border-bambu-green [color-scheme:dark]"
  6985. />
  6986. )}
  6987. </div>
  6988. </div>
  6989. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6990. {/* Footer */}
  6991. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6992. <button
  6993. onClick={() => {
  6994. if (dryingPopoverAmsId !== null) {
  6995. // Clamp rotateTray off when any tray in this AMS is loaded into
  6996. // the tube — the rotate UI is disabled there, but the state may
  6997. // linger as `true` from a previous AMS, or a print may have
  6998. // started while the popover was open. Without this clamp the
  6999. // Start payload would carry rotate_tray=true and firmware would
  7000. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7001. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7002. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7003. tray => tray.state === 11,
  7004. );
  7005. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7006. if (dryingStartMode === 'now') {
  7007. startDryingMutation.mutate({
  7008. amsId: dryingPopoverAmsId,
  7009. temp: dryingTemp,
  7010. duration: dryingDuration,
  7011. filament: dryingFilament,
  7012. rotateTray: rotate,
  7013. });
  7014. } else {
  7015. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7016. if (startAfter) {
  7017. scheduleDryingMutation.mutate({
  7018. amsId: dryingPopoverAmsId,
  7019. temp: dryingTemp,
  7020. duration: dryingDuration,
  7021. filament: dryingFilament,
  7022. rotateTray: rotate,
  7023. startAfter,
  7024. });
  7025. }
  7026. }
  7027. }
  7028. }}
  7029. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7030. data-testid="drying-start-confirm"
  7031. 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"
  7032. >
  7033. {dryingStartMode === 'now'
  7034. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7035. : t('printers.drying.schedule')}
  7036. </button>
  7037. </div>
  7038. </div>
  7039. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7040. since the popover clips its own overflow. */}
  7041. <div
  7042. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7043. style={{
  7044. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7045. top: dryingPopoverPos.anchorY - 5,
  7046. ...(dryingPopoverPos.placement === 'above'
  7047. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7048. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7049. }}
  7050. />
  7051. </>
  7052. );
  7053. })()}
  7054. </Card>
  7055. );
  7056. }
  7057. export function AddPrinterModal({
  7058. onClose,
  7059. onAdd,
  7060. existingSerials,
  7061. }: {
  7062. onClose: () => void;
  7063. onAdd: (data: PrinterCreate) => void;
  7064. existingSerials: string[];
  7065. }) {
  7066. const { t } = useTranslation();
  7067. const [form, setForm] = useState<PrinterCreate>({
  7068. name: '',
  7069. serial_number: '',
  7070. ip_address: '',
  7071. access_code: '',
  7072. model: '',
  7073. location: '',
  7074. auto_archive: true,
  7075. });
  7076. // Discovery state
  7077. const [discovering, setDiscovering] = useState(false);
  7078. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7079. const [discoveryError, setDiscoveryError] = useState('');
  7080. const [hasScanned, setHasScanned] = useState(false);
  7081. const [isDocker, setIsDocker] = useState(false);
  7082. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7083. const [subnet, setSubnet] = useState('');
  7084. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7085. // text input so users can scan a subnet Bambuddy isn't directly on
  7086. // (printer behind a router on a different L3 segment — SSDP multicast
  7087. // won't cross that boundary, only an active unicast scan will). #1564
  7088. const [customSubnet, setCustomSubnet] = useState('');
  7089. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7090. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7091. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7092. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7093. // (not block) when checks fail, so the user doesn't add a printer that
  7094. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7095. // failed result awaiting an explicit "save anyway".
  7096. const [checkingSave, setCheckingSave] = useState(false);
  7097. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7098. // Fetch discovery info on mount + restore the last custom CIDR the user
  7099. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7100. // time they open this modal).
  7101. useEffect(() => {
  7102. discoveryApi.getInfo().then(info => {
  7103. setIsDocker(info.is_docker);
  7104. if (info.subnets.length > 0) {
  7105. setDetectedSubnets(info.subnets);
  7106. setSubnet(info.subnets[0]);
  7107. }
  7108. }).catch(() => {
  7109. // Ignore errors, assume not Docker
  7110. });
  7111. try {
  7112. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7113. if (saved) setCustomSubnet(saved);
  7114. } catch {
  7115. // localStorage unavailable (private mode, quota); recall is opportunistic
  7116. }
  7117. }, []);
  7118. // Filter out already-added printers
  7119. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7120. const handleAddSubmit = async (e: React.FormEvent) => {
  7121. e.preventDefault();
  7122. setCheckingSave(true);
  7123. try {
  7124. const result = await api.diagnoseConnection({
  7125. ip_address: form.ip_address.trim(),
  7126. serial_number: form.serial_number.trim() || undefined,
  7127. access_code: form.access_code || undefined,
  7128. });
  7129. if (result.checks.some((c) => c.status === 'fail')) {
  7130. setSaveWarning(result);
  7131. return;
  7132. }
  7133. } catch {
  7134. // Diagnostic infrastructure failed — never block the save on it.
  7135. } finally {
  7136. setCheckingSave(false);
  7137. }
  7138. onAdd(form);
  7139. };
  7140. const startDiscovery = async () => {
  7141. setDiscoveryError('');
  7142. setDiscovered([]);
  7143. setDiscovering(true);
  7144. setHasScanned(false);
  7145. setScanProgress({ scanned: 0, total: 0 });
  7146. // Native installs fall back to subnet scanning when the user picks
  7147. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7148. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7149. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7150. const wantsSubnetScan = isDocker || useCustomSubnet;
  7151. if (wantsSubnetScan && useCustomSubnet) {
  7152. try {
  7153. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7154. } catch {
  7155. // localStorage write best-effort; user just retypes next time
  7156. }
  7157. }
  7158. try {
  7159. if (wantsSubnetScan) {
  7160. await discoveryApi.startSubnetScan(scanCidr);
  7161. // Poll for scan status and results
  7162. const pollInterval = setInterval(async () => {
  7163. try {
  7164. const status = await discoveryApi.getScanStatus();
  7165. setScanProgress({ scanned: status.scanned, total: status.total });
  7166. const printers = await discoveryApi.getDiscoveredPrinters();
  7167. setDiscovered(printers);
  7168. if (!status.running) {
  7169. clearInterval(pollInterval);
  7170. setDiscovering(false);
  7171. setHasScanned(true);
  7172. }
  7173. } catch (e) {
  7174. console.error('Failed to get scan status:', e);
  7175. }
  7176. }, 500);
  7177. } else {
  7178. // Use SSDP discovery for native installs
  7179. await discoveryApi.startDiscovery(10);
  7180. // Poll for discovered printers every second
  7181. const pollInterval = setInterval(async () => {
  7182. try {
  7183. const printers = await discoveryApi.getDiscoveredPrinters();
  7184. setDiscovered(printers);
  7185. } catch (e) {
  7186. console.error('Failed to get discovered printers:', e);
  7187. }
  7188. }, 1000);
  7189. // Stop after 10 seconds
  7190. setTimeout(async () => {
  7191. clearInterval(pollInterval);
  7192. try {
  7193. await discoveryApi.stopDiscovery();
  7194. } catch {
  7195. // Ignore stop errors
  7196. }
  7197. setDiscovering(false);
  7198. setHasScanned(true);
  7199. // Final fetch
  7200. try {
  7201. const printers = await discoveryApi.getDiscoveredPrinters();
  7202. setDiscovered(printers);
  7203. } catch (e) {
  7204. console.error('Failed to get final discovered printers:', e);
  7205. }
  7206. }, 10000);
  7207. }
  7208. } catch (e) {
  7209. console.error('Failed to start discovery:', e);
  7210. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7211. setDiscovering(false);
  7212. setHasScanned(true);
  7213. }
  7214. };
  7215. // Reuse module-level mapModelCode
  7216. const selectPrinter = (printer: DiscoveredPrinter) => {
  7217. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7218. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7219. setForm({
  7220. ...form,
  7221. name: printer.name || '',
  7222. serial_number: serialNumber,
  7223. ip_address: printer.ip_address,
  7224. model: mapModelCode(printer.model),
  7225. });
  7226. // Clear discovery results after selection
  7227. setDiscovered([]);
  7228. };
  7229. // Cleanup discovery on unmount
  7230. useEffect(() => {
  7231. return () => {
  7232. discoveryApi.stopDiscovery().catch(() => {});
  7233. discoveryApi.stopSubnetScan().catch(() => {});
  7234. };
  7235. }, []);
  7236. // Close on Escape key
  7237. useEffect(() => {
  7238. const handleKeyDown = (e: KeyboardEvent) => {
  7239. if (e.key === 'Escape') onClose();
  7240. };
  7241. window.addEventListener('keydown', handleKeyDown);
  7242. return () => window.removeEventListener('keydown', handleKeyDown);
  7243. }, [onClose]);
  7244. return (
  7245. <>
  7246. <div
  7247. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7248. onClick={onClose}
  7249. >
  7250. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7251. <CardContent>
  7252. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7253. {/* Discovery Section */}
  7254. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7255. {/* Subnet picker — always visible. The dropdown lists detected
  7256. interface subnets and a "Custom..." sentinel that reveals
  7257. a CIDR text input for printers on a different L3 segment
  7258. (router, VLAN, etc.). #1564 */}
  7259. <div className="mb-3">
  7260. <label className="block text-sm text-bambu-gray mb-1">
  7261. {t('printers.discovery.subnetToScan')}
  7262. </label>
  7263. {detectedSubnets.length > 0 ? (
  7264. <select
  7265. 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"
  7266. value={useCustomSubnet ? '__custom__' : subnet}
  7267. onChange={(e) => {
  7268. if (e.target.value === '__custom__') {
  7269. setUseCustomSubnet(true);
  7270. } else {
  7271. setUseCustomSubnet(false);
  7272. setSubnet(e.target.value);
  7273. }
  7274. }}
  7275. disabled={discovering}
  7276. >
  7277. {detectedSubnets.map(s => (
  7278. <option key={s} value={s}>{s}</option>
  7279. ))}
  7280. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7281. </select>
  7282. ) : (
  7283. <input
  7284. type="text"
  7285. 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"
  7286. value={subnet}
  7287. onChange={(e) => setSubnet(e.target.value)}
  7288. placeholder="192.168.1.0/24"
  7289. disabled={discovering}
  7290. />
  7291. )}
  7292. {useCustomSubnet && (
  7293. <input
  7294. type="text"
  7295. aria-label={t('printers.discovery.customSubnetLabel')}
  7296. 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"
  7297. value={customSubnet}
  7298. onChange={(e) => setCustomSubnet(e.target.value)}
  7299. placeholder="10.1.1.0/24"
  7300. disabled={discovering}
  7301. />
  7302. )}
  7303. <p className="mt-1 text-xs text-bambu-gray">
  7304. {isDocker
  7305. ? t('printers.discovery.dockerNote')
  7306. : t('printers.discovery.customSubnetNote')}
  7307. </p>
  7308. </div>
  7309. <Button
  7310. type="button"
  7311. variant="secondary"
  7312. onClick={startDiscovery}
  7313. disabled={discovering}
  7314. className="w-full"
  7315. >
  7316. {discovering ? (
  7317. <>
  7318. <Loader2 className="w-4 h-4 animate-spin" />
  7319. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7320. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7321. : t('printers.discovery.scanning')}
  7322. </>
  7323. ) : (
  7324. <>
  7325. <Search className="w-4 h-4" />
  7326. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7327. </>
  7328. )}
  7329. </Button>
  7330. {discoveryError && (
  7331. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7332. )}
  7333. {newPrinters.length > 0 && (
  7334. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7335. {newPrinters.map((printer) => (
  7336. <div
  7337. key={printer.serial}
  7338. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7339. onClick={() => selectPrinter(printer)}
  7340. >
  7341. <div className="min-w-0 flex-1">
  7342. <p className="font-medium text-white text-sm truncate">
  7343. {printer.name || printer.serial}
  7344. </p>
  7345. <p className="text-xs text-bambu-gray truncate">
  7346. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7347. {printer.serial.startsWith('unknown-') && (
  7348. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7349. )}
  7350. </p>
  7351. </div>
  7352. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7353. </div>
  7354. ))}
  7355. </div>
  7356. )}
  7357. {discovering && (
  7358. <p className="mt-2 text-sm text-bambu-gray text-center">
  7359. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7360. </p>
  7361. )}
  7362. {hasScanned && !discovering && discovered.length === 0 && (
  7363. <p className="mt-2 text-sm text-bambu-gray text-center">
  7364. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7365. </p>
  7366. )}
  7367. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7368. <p className="mt-2 text-sm text-bambu-gray text-center">
  7369. {t('printers.discovery.allConfigured')}
  7370. </p>
  7371. )}
  7372. </div>
  7373. <form onSubmit={handleAddSubmit} className="space-y-4">
  7374. <div>
  7375. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7376. <input
  7377. type="text"
  7378. required
  7379. 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"
  7380. value={form.name}
  7381. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7382. placeholder={t('printers.modal.myPrinter')}
  7383. />
  7384. </div>
  7385. <div>
  7386. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7387. <input
  7388. type="text"
  7389. required
  7390. 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])?)*)"
  7391. 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"
  7392. value={form.ip_address}
  7393. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7394. placeholder="192.168.1.100 or printer.local"
  7395. />
  7396. </div>
  7397. <div>
  7398. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7399. <input
  7400. type="text"
  7401. required
  7402. 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"
  7403. value={form.serial_number}
  7404. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7405. placeholder="01P00A000000000"
  7406. />
  7407. </div>
  7408. <div>
  7409. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7410. <input
  7411. type="password"
  7412. required
  7413. 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"
  7414. value={form.access_code}
  7415. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7416. placeholder={t('printers.modal.fromPrinterSettings')}
  7417. />
  7418. </div>
  7419. <div>
  7420. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7421. <select
  7422. 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"
  7423. value={form.model || ''}
  7424. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7425. >
  7426. <option value="">{t('printers.modal.selectModel')}</option>
  7427. <optgroup label="A1 Series">
  7428. <option value="A1">A1</option>
  7429. <option value="A1 Mini">A1 Mini</option>
  7430. </optgroup>
  7431. <optgroup label="A2 Series">
  7432. <option value="A2L">A2L</option>
  7433. </optgroup>
  7434. <optgroup label="H2 Series">
  7435. <option value="H2C">H2C</option>
  7436. <option value="H2D">H2D</option>
  7437. <option value="H2D Pro">H2D Pro</option>
  7438. <option value="H2S">H2S</option>
  7439. </optgroup>
  7440. <optgroup label="P Series">
  7441. <option value="P1P">P1P</option>
  7442. <option value="P1S">P1S</option>
  7443. <option value="P2S">P2S</option>
  7444. </optgroup>
  7445. <optgroup label="X1 Series">
  7446. <option value="X1">X1</option>
  7447. <option value="X1C">X1 Carbon</option>
  7448. <option value="X1E">X1E</option>
  7449. </optgroup>
  7450. <optgroup label="X2 Series">
  7451. <option value="X2D">X2D</option>
  7452. </optgroup>
  7453. </select>
  7454. </div>
  7455. <div>
  7456. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7457. <input
  7458. type="text"
  7459. 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"
  7460. value={form.location || ''}
  7461. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7462. placeholder={t('printers.modal.locationPlaceholder')}
  7463. />
  7464. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7465. </div>
  7466. <div className="flex items-center gap-2">
  7467. <input
  7468. type="checkbox"
  7469. id="auto_archive"
  7470. checked={form.auto_archive}
  7471. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7472. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7473. />
  7474. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7475. {t('printers.modal.autoArchiveLabel')}
  7476. </label>
  7477. </div>
  7478. <button
  7479. type="button"
  7480. onClick={() => setShowDiagnostic(true)}
  7481. disabled={!form.ip_address.trim()}
  7482. 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"
  7483. >
  7484. <Stethoscope className="w-4 h-4" />
  7485. {t('diagnostic.runButton')}
  7486. </button>
  7487. {saveWarning ? (
  7488. <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">
  7489. <div className="flex items-start gap-2">
  7490. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7491. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7492. </div>
  7493. <DiagnosticChecklist result={saveWarning} />
  7494. <div className="flex gap-3">
  7495. <Button
  7496. type="button"
  7497. variant="secondary"
  7498. onClick={() => setSaveWarning(null)}
  7499. className="flex-1"
  7500. >
  7501. {t('printers.addPreflight.back')}
  7502. </Button>
  7503. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7504. {t('printers.addPreflight.saveAnyway')}
  7505. </Button>
  7506. </div>
  7507. </div>
  7508. ) : (
  7509. <div className="flex gap-3 pt-2">
  7510. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7511. {t('common.cancel')}
  7512. </Button>
  7513. <Button type="submit" disabled={checkingSave} className="flex-1">
  7514. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7515. </Button>
  7516. </div>
  7517. )}
  7518. </form>
  7519. </CardContent>
  7520. </Card>
  7521. </div>
  7522. {showDiagnostic && (
  7523. <ConnectionDiagnosticModal
  7524. connection={{
  7525. ip_address: form.ip_address.trim(),
  7526. serial_number: form.serial_number.trim() || undefined,
  7527. access_code: form.access_code || undefined,
  7528. }}
  7529. printerName={form.name || null}
  7530. onClose={() => setShowDiagnostic(false)}
  7531. />
  7532. )}
  7533. </>
  7534. );
  7535. }
  7536. function FirmwareUpdateModal({
  7537. printer,
  7538. firmwareInfo,
  7539. onClose,
  7540. }: {
  7541. printer: Printer;
  7542. firmwareInfo: FirmwareUpdateInfo;
  7543. onClose: () => void;
  7544. }) {
  7545. const { t } = useTranslation();
  7546. const queryClient = useQueryClient();
  7547. const { showToast } = useToast();
  7548. const { hasPermission } = useAuth();
  7549. const canUpdate = hasPermission('firmware:update');
  7550. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7551. const [isUploading, setIsUploading] = useState(false);
  7552. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7553. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7554. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7555. );
  7556. // Prepare check query — runs when a version is selected and user can update
  7557. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7558. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7559. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7560. staleTime: 30000,
  7561. enabled: !!selectedVersion && canUpdate && !isUploading,
  7562. });
  7563. // Start upload mutation
  7564. const uploadMutation = useMutation({
  7565. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7566. onSuccess: () => {
  7567. setIsUploading(true);
  7568. // Start polling for status
  7569. const interval = setInterval(async () => {
  7570. try {
  7571. const status = await firmwareApi.getUploadStatus(printer.id);
  7572. setUploadStatus(status);
  7573. if (status.status === 'complete' || status.status === 'error') {
  7574. clearInterval(interval);
  7575. setPollInterval(null);
  7576. setIsUploading(false);
  7577. if (status.status === 'complete') {
  7578. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7579. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7580. }
  7581. }
  7582. } catch {
  7583. // Ignore errors during polling
  7584. }
  7585. }, 2000);
  7586. setPollInterval(interval);
  7587. },
  7588. onError: (error: Error) => {
  7589. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7590. setIsUploading(false);
  7591. },
  7592. });
  7593. // Cleanup on unmount
  7594. useEffect(() => {
  7595. return () => {
  7596. if (pollInterval) clearInterval(pollInterval);
  7597. };
  7598. }, [pollInterval]);
  7599. const handleStartUpload = () => {
  7600. setUploadStatus(null);
  7601. uploadMutation.mutate();
  7602. };
  7603. return (
  7604. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7605. <Card className="w-full max-w-md mx-4">
  7606. <CardContent>
  7607. <div className="flex items-start gap-3 mb-4">
  7608. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7609. {firmwareInfo.update_available
  7610. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7611. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7612. </div>
  7613. <div className="flex-1">
  7614. <h3 className="text-lg font-semibold text-white">
  7615. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7616. </h3>
  7617. <p className="text-sm text-bambu-gray mt-1">
  7618. {printer.name}
  7619. </p>
  7620. </div>
  7621. </div>
  7622. {/* Version Info */}
  7623. {(() => {
  7624. const selectedEntry = selectedVersion
  7625. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7626. : null;
  7627. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7628. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7629. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7630. return (
  7631. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7632. <div className="flex justify-between items-center text-sm">
  7633. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7634. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7635. {firmwareInfo.current_version || t('common.unknown')}
  7636. </span>
  7637. </div>
  7638. {showSecondLine && (
  7639. <div className="flex justify-between items-center text-sm mt-1">
  7640. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7641. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7642. </div>
  7643. )}
  7644. {displayNotes && (
  7645. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7646. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7647. {t('printers.firmwareModal.releaseNotes')}
  7648. </summary>
  7649. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7650. {displayNotes}
  7651. </div>
  7652. </details>
  7653. )}
  7654. </div>
  7655. );
  7656. })()}
  7657. {/* Available versions list */}
  7658. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7659. <div className="mb-4">
  7660. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7661. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7662. {firmwareInfo.available_versions.map((v) => {
  7663. const isCurrent = firmwareInfo.current_version === v.version;
  7664. const isSelected = selectedVersion === v.version;
  7665. const cmp = firmwareInfo.current_version
  7666. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7667. : 0;
  7668. const relLabel = isCurrent
  7669. ? t('printers.firmwareModal.currentBadge')
  7670. : cmp > 0
  7671. ? t('printers.firmwareModal.newerBadge')
  7672. : t('printers.firmwareModal.olderBadge');
  7673. const relClass = isCurrent
  7674. ? 'text-bambu-gray'
  7675. : cmp > 0
  7676. ? 'text-orange-700 dark:text-orange-400'
  7677. : 'text-blue-700 dark:text-blue-400';
  7678. return (
  7679. <button
  7680. key={v.version}
  7681. type="button"
  7682. disabled={!v.file_available || !canUpdate || isCurrent}
  7683. onClick={() => setSelectedVersion(v.version)}
  7684. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7685. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7686. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7687. >
  7688. <div className="flex items-center gap-2 min-w-0">
  7689. <span className="font-mono text-white">{v.version}</span>
  7690. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7691. </div>
  7692. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7693. isCurrent
  7694. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7695. : v.file_available
  7696. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7697. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7698. }`}>
  7699. {isCurrent
  7700. ? t('printers.firmwareModal.installed')
  7701. : v.file_available
  7702. ? t('printers.firmwareModal.usable')
  7703. : t('printers.firmwareModal.unavailable')}
  7704. </span>
  7705. </button>
  7706. );
  7707. })}
  7708. </div>
  7709. </div>
  7710. )}
  7711. {/* Status / Progress (only when a version is selected) */}
  7712. {!selectedVersion ? null : isPreparing ? (
  7713. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7714. <Loader2 className="w-4 h-4 animate-spin" />
  7715. {t('printers.firmwareModal.checkingPrereqs')}
  7716. </div>
  7717. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7718. <div className="mb-4">
  7719. {prepareInfo.can_proceed ? (
  7720. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7721. <Box className="w-4 h-4" />
  7722. {t('printers.firmwareModal.sdCardReady')}
  7723. </div>
  7724. ) : (
  7725. <div className="space-y-1">
  7726. {prepareInfo.errors.map((error, i) => (
  7727. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7728. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7729. {error}
  7730. </div>
  7731. ))}
  7732. </div>
  7733. )}
  7734. </div>
  7735. ) : null}
  7736. {/* Upload Progress */}
  7737. {(isUploading || uploadStatus) && uploadStatus && (
  7738. <div className="mb-4">
  7739. <div className="flex items-center justify-between text-sm mb-1">
  7740. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  7741. <span className="text-white">{uploadStatus.progress}%</span>
  7742. </div>
  7743. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  7744. <div
  7745. className={`h-2 rounded-full transition-all ${
  7746. uploadStatus.status === 'error' ? 'bg-status-error' :
  7747. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  7748. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  7749. style={{ width: `${uploadStatus.progress}%` }}
  7750. />
  7751. </div>
  7752. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  7753. {uploadStatus.error && (
  7754. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  7755. )}
  7756. </div>
  7757. )}
  7758. {/* Success Message */}
  7759. {uploadStatus?.status === 'complete' && (
  7760. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  7761. <p className="text-sm text-bambu-green font-medium mb-2">
  7762. {t('printers.firmwareModal.uploadedSuccess')}
  7763. </p>
  7764. <p className="text-xs text-bambu-gray">
  7765. {t('printers.firmwareModal.applyInstructions')}
  7766. </p>
  7767. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  7768. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  7769. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  7770. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  7771. <li>{t('printers.firmwareModal.step4')}</li>
  7772. </ol>
  7773. </div>
  7774. )}
  7775. {/* Buttons */}
  7776. <div className="flex gap-2 justify-end">
  7777. <Button variant="secondary" onClick={onClose}>
  7778. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  7779. </Button>
  7780. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  7781. <Button
  7782. onClick={handleStartUpload}
  7783. disabled={uploadMutation.isPending}
  7784. >
  7785. {uploadMutation.isPending ? (
  7786. <>
  7787. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  7788. {t('printers.firmwareModal.starting')}
  7789. </>
  7790. ) : (
  7791. <>
  7792. <Download className="w-4 h-4 mr-2" />
  7793. {t('printers.firmwareModal.uploadFirmware')}
  7794. </>
  7795. )}
  7796. </Button>
  7797. )}
  7798. </div>
  7799. </CardContent>
  7800. </Card>
  7801. </div>
  7802. );
  7803. }
  7804. function EditPrinterModal({
  7805. printer,
  7806. onClose,
  7807. }: {
  7808. printer: Printer;
  7809. onClose: () => void;
  7810. }) {
  7811. const { t } = useTranslation();
  7812. const queryClient = useQueryClient();
  7813. const { showToast } = useToast();
  7814. const [form, setForm] = useState({
  7815. name: printer.name,
  7816. ip_address: printer.ip_address,
  7817. access_code: '',
  7818. model: printer.model || '',
  7819. location: printer.location || '',
  7820. auto_archive: printer.auto_archive,
  7821. is_active: printer.is_active,
  7822. });
  7823. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7824. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7825. const [checkingSave, setCheckingSave] = useState(false);
  7826. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7827. const updateMutation = useMutation({
  7828. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7829. onSuccess: () => {
  7830. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7831. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7832. onClose();
  7833. },
  7834. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7835. });
  7836. // Close on Escape key
  7837. useEffect(() => {
  7838. const handleKeyDown = (e: KeyboardEvent) => {
  7839. if (e.key === 'Escape') onClose();
  7840. };
  7841. window.addEventListener('keydown', handleKeyDown);
  7842. return () => window.removeEventListener('keydown', handleKeyDown);
  7843. }, [onClose]);
  7844. const doSave = () => {
  7845. const data: Partial<PrinterCreate> = {
  7846. name: form.name,
  7847. ip_address: form.ip_address,
  7848. model: form.model || undefined,
  7849. location: form.location || undefined,
  7850. auto_archive: form.auto_archive,
  7851. is_active: form.is_active,
  7852. };
  7853. // Only include access_code if it was changed
  7854. if (form.access_code) {
  7855. data.access_code = form.access_code;
  7856. }
  7857. updateMutation.mutate(data);
  7858. };
  7859. const handleSubmit = async (e: React.FormEvent) => {
  7860. e.preventDefault();
  7861. setCheckingSave(true);
  7862. try {
  7863. const result = await api.diagnoseConnection({
  7864. ip_address: form.ip_address.trim(),
  7865. serial_number: printer.serial_number,
  7866. access_code: form.access_code || undefined,
  7867. });
  7868. if (result.checks.some((c) => c.status === 'fail')) {
  7869. setSaveWarning(result);
  7870. return;
  7871. }
  7872. } catch {
  7873. // Diagnostic infrastructure failed — never block the save on it.
  7874. } finally {
  7875. setCheckingSave(false);
  7876. }
  7877. doSave();
  7878. };
  7879. return (
  7880. <div
  7881. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7882. onClick={onClose}
  7883. >
  7884. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7885. <CardContent>
  7886. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7887. <form onSubmit={handleSubmit} className="space-y-4">
  7888. <div>
  7889. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7890. <input
  7891. type="text"
  7892. required
  7893. 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"
  7894. value={form.name}
  7895. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7896. placeholder={t('printers.modal.myPrinter')}
  7897. />
  7898. </div>
  7899. <div>
  7900. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7901. <input
  7902. type="text"
  7903. required
  7904. 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])?)*)"
  7905. 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"
  7906. value={form.ip_address}
  7907. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7908. placeholder="192.168.1.100 or printer.local"
  7909. />
  7910. </div>
  7911. <div>
  7912. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7913. <input
  7914. type="text"
  7915. disabled
  7916. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7917. value={printer.serial_number}
  7918. />
  7919. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7920. </div>
  7921. <div>
  7922. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7923. <input
  7924. type="password"
  7925. 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"
  7926. value={form.access_code}
  7927. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7928. placeholder={t('printers.accessCodePlaceholder')}
  7929. />
  7930. </div>
  7931. <div>
  7932. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7933. <select
  7934. 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"
  7935. value={form.model}
  7936. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7937. >
  7938. <option value="">{t('printers.modal.selectModel')}</option>
  7939. <optgroup label="A1 Series">
  7940. <option value="A1">A1</option>
  7941. <option value="A1 Mini">A1 Mini</option>
  7942. </optgroup>
  7943. <optgroup label="A2 Series">
  7944. <option value="A2L">A2L</option>
  7945. </optgroup>
  7946. <optgroup label="H2 Series">
  7947. <option value="H2C">H2C</option>
  7948. <option value="H2D">H2D</option>
  7949. <option value="H2D Pro">H2D Pro</option>
  7950. <option value="H2S">H2S</option>
  7951. </optgroup>
  7952. <optgroup label="P Series">
  7953. <option value="P1P">P1P</option>
  7954. <option value="P1S">P1S</option>
  7955. <option value="P2S">P2S</option>
  7956. </optgroup>
  7957. <optgroup label="X1 Series">
  7958. <option value="X1">X1</option>
  7959. <option value="X1C">X1 Carbon</option>
  7960. <option value="X1E">X1E</option>
  7961. </optgroup>
  7962. <optgroup label="X2 Series">
  7963. <option value="X2D">X2D</option>
  7964. </optgroup>
  7965. </select>
  7966. </div>
  7967. <div>
  7968. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7969. <input
  7970. type="text"
  7971. 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"
  7972. value={form.location}
  7973. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7974. placeholder={t('printers.modal.locationPlaceholder')}
  7975. />
  7976. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7977. </div>
  7978. <div className="flex items-center gap-2">
  7979. <input
  7980. type="checkbox"
  7981. id="edit_auto_archive"
  7982. checked={form.auto_archive}
  7983. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7984. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7985. />
  7986. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7987. {t('printers.modal.autoArchiveLabel')}
  7988. </label>
  7989. </div>
  7990. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7991. is_active because the user-facing concept is "is this printer
  7992. in maintenance" not "is it active". */}
  7993. <div>
  7994. <div className="flex items-center gap-2">
  7995. <input
  7996. type="checkbox"
  7997. id="edit_maintenance_mode"
  7998. checked={!form.is_active}
  7999. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8000. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8001. />
  8002. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8003. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8004. {t('printers.maintenance.editFieldLabel')}
  8005. </label>
  8006. </div>
  8007. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8008. {t('printers.maintenance.editFieldHelp')}
  8009. </p>
  8010. </div>
  8011. {saveWarning ? (
  8012. <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">
  8013. <div className="flex items-start gap-2">
  8014. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8015. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8016. </div>
  8017. <DiagnosticChecklist result={saveWarning} />
  8018. <div className="flex gap-3">
  8019. <Button
  8020. type="button"
  8021. variant="secondary"
  8022. onClick={() => setSaveWarning(null)}
  8023. className="flex-1"
  8024. >
  8025. {t('printers.addPreflight.back')}
  8026. </Button>
  8027. <Button
  8028. type="button"
  8029. onClick={doSave}
  8030. className="flex-1"
  8031. disabled={updateMutation.isPending}
  8032. >
  8033. {t('printers.addPreflight.saveAnyway')}
  8034. </Button>
  8035. </div>
  8036. </div>
  8037. ) : (
  8038. <div className="flex gap-3 pt-4">
  8039. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8040. {t('common.cancel')}
  8041. </Button>
  8042. <Button
  8043. type="submit"
  8044. className="flex-1"
  8045. disabled={updateMutation.isPending || checkingSave}
  8046. >
  8047. {checkingSave
  8048. ? t('printers.addPreflight.checking')
  8049. : updateMutation.isPending
  8050. ? t('common.saving')
  8051. : t('printers.modal.saveChanges')}
  8052. </Button>
  8053. </div>
  8054. )}
  8055. </form>
  8056. </CardContent>
  8057. </Card>
  8058. </div>
  8059. );
  8060. }
  8061. // Component to check if a printer is offline (for power dropdown)
  8062. function usePrinterOfflineStatus(printerId: number) {
  8063. const { data: status } = useQuery({
  8064. queryKey: ['printerStatus', printerId],
  8065. queryFn: () => api.getPrinterStatus(printerId),
  8066. refetchInterval: 30000,
  8067. });
  8068. return !status?.connected;
  8069. }
  8070. // Power dropdown item for an offline printer
  8071. function PowerDropdownItem({
  8072. printer,
  8073. plug,
  8074. onPowerOn,
  8075. isPowering,
  8076. }: {
  8077. printer: Printer;
  8078. plug: { id: number; name: string };
  8079. onPowerOn: (plugId: number) => void;
  8080. isPowering: boolean;
  8081. }) {
  8082. const isOffline = usePrinterOfflineStatus(printer.id);
  8083. // Fetch plug status
  8084. const { data: plugStatus } = useQuery({
  8085. queryKey: ['smartPlugStatus', plug.id],
  8086. queryFn: () => api.getSmartPlugStatus(plug.id),
  8087. refetchInterval: 10000,
  8088. });
  8089. // Only show if printer is offline
  8090. if (!isOffline) {
  8091. return null;
  8092. }
  8093. return (
  8094. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8095. <div className="flex items-center gap-2 min-w-0">
  8096. <span className="text-sm text-white truncate">{printer.name}</span>
  8097. {plugStatus && (
  8098. <span
  8099. className={`text-xs px-1.5 py-0.5 rounded ${
  8100. plugStatus.state === 'ON'
  8101. ? 'bg-bambu-green/20 text-bambu-green'
  8102. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8103. }`}
  8104. >
  8105. {plugStatus.state || '?'}
  8106. </span>
  8107. )}
  8108. </div>
  8109. <button
  8110. onClick={() => onPowerOn(plug.id)}
  8111. disabled={isPowering || plugStatus?.state === 'ON'}
  8112. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8113. plugStatus?.state === 'ON'
  8114. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8115. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8116. }`}
  8117. >
  8118. <Power className="w-3 h-3" />
  8119. {isPowering ? '...' : 'On'}
  8120. </button>
  8121. </div>
  8122. );
  8123. }
  8124. export function PrintersPage() {
  8125. const { t } = useTranslation();
  8126. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8127. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8128. const accentButtonClass = {
  8129. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8130. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8131. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8132. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8133. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8134. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8135. }[activeAccent];
  8136. const [showAddModal, setShowAddModal] = useState(false);
  8137. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8138. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8139. });
  8140. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8141. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8142. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8143. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8144. });
  8145. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8146. return localStorage.getItem('printerSortAsc') !== 'false';
  8147. });
  8148. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8149. const [cardSize, setCardSize] = useState<number>(() => {
  8150. const saved = localStorage.getItem('printerCardSize');
  8151. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8152. });
  8153. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8154. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8155. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8156. });
  8157. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8158. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8159. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8160. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8161. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8162. });
  8163. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8164. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8165. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8166. });
  8167. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8168. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8169. // Defaulting to 'full' because the cards already show this info — users who
  8170. // pick cam-wall view still want to glance the same details without flipping.
  8171. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8172. const saved = localStorage.getItem('camWallStatusMode');
  8173. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8174. });
  8175. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8176. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8177. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8178. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8179. requestAnimationFrame(() => {
  8180. requestAnimationFrame(() => {
  8181. const card = document.getElementById(`printer-card-${printerId}`);
  8182. if (!card) return;
  8183. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8184. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8185. window.scrollTo({
  8186. top: Math.max(0, top),
  8187. behavior: 'smooth',
  8188. });
  8189. });
  8190. });
  8191. }, []);
  8192. const openCompactCard = useCallback((printerId: number) => {
  8193. setCompactDrilldownPrinterId(printerId);
  8194. setCardSize(2);
  8195. localStorage.setItem('printerCardSize', '2');
  8196. scrollPrinterIntoView(printerId);
  8197. }, [scrollPrinterIntoView]);
  8198. const returnToCompactCards = useCallback(() => {
  8199. const printerId = compactDrilldownPrinterId;
  8200. setCompactDrilldownPrinterId(null);
  8201. setCardSize(1);
  8202. localStorage.setItem('printerCardSize', '1');
  8203. if (printerId != null) {
  8204. scrollPrinterIntoView(printerId);
  8205. }
  8206. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8207. const [search, setSearch] = useState('');
  8208. // Both filters persist like every other preference on this page (#2833).
  8209. // `search` deliberately does not: a box that silently refills itself on
  8210. // return is more surprising than a dropdown that remembers.
  8211. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8212. // Validated on read: a value the dropdown no longer offers would filter
  8213. // every printer out, and nothing would explain why.
  8214. const saved = localStorage.getItem('printerStatusFilter');
  8215. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8216. });
  8217. const [locationFilter, setLocationFilter] = useState<string>(
  8218. () => localStorage.getItem('printerLocationFilter') || 'all'
  8219. );
  8220. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8221. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8222. try {
  8223. const saved = localStorage.getItem('printerCollapsedSections');
  8224. return saved ? JSON.parse(saved) : {};
  8225. } catch { return {}; }
  8226. });
  8227. const queryClient = useQueryClient();
  8228. const { showToast } = useToast();
  8229. const { hasPermission } = useAuth();
  8230. // Which way the camera buttons open a stream. Chosen per click from the
  8231. // button's own menu; null until this browser has made a choice, so the
  8232. // stored setting below can act as the default a fresh browser starts from.
  8233. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8234. () => readStoredCameraViewMode()
  8235. );
  8236. // Embedded camera viewer state - supports multiple simultaneous viewers
  8237. // Persisted to localStorage so cameras reopen after navigation
  8238. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8239. const saved = localStorage.getItem('openEmbeddedCameras');
  8240. if (saved) {
  8241. try {
  8242. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8243. return new Map(cameras.map(c => [c.id, c]));
  8244. } catch {
  8245. return new Map();
  8246. }
  8247. }
  8248. return new Map();
  8249. });
  8250. // Persist open cameras to localStorage when they change
  8251. useEffect(() => {
  8252. const cameras = Array.from(embeddedCameraPrinters.values());
  8253. if (cameras.length > 0) {
  8254. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8255. } else {
  8256. localStorage.removeItem('openEmbeddedCameras');
  8257. }
  8258. }, [embeddedCameraPrinters]);
  8259. const { data: printers, isLoading } = useQuery({
  8260. queryKey: ['printers'],
  8261. queryFn: api.getPrinters,
  8262. });
  8263. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8264. // so users with printers:read but no settings:read still get the values needed
  8265. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8266. const { data: settings } = useQuery({
  8267. queryKey: ['ui-preferences'],
  8268. queryFn: api.getUiPreferences,
  8269. });
  8270. // Parse user-configured temperature/fan presets once, with defensive fallback
  8271. // to built-in defaults on parse failure (validators on the backend already
  8272. // reject malformed writes, so this is just forward-compat).
  8273. const effectiveNozzleTempPresets = useMemo(
  8274. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8275. [settings?.nozzle_temp_presets],
  8276. );
  8277. const effectiveBedTempPresets = useMemo(
  8278. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8279. [settings?.bed_temp_presets],
  8280. );
  8281. const effectiveChamberTempPresets = useMemo(
  8282. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8283. [settings?.chamber_temp_presets],
  8284. );
  8285. const effectiveFanSpeedPresets = useMemo(
  8286. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8287. [settings?.fan_speed_presets],
  8288. );
  8289. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8290. const effectiveDryingPresets = useMemo(() => {
  8291. if (settings?.drying_presets) {
  8292. try {
  8293. const userPresets = JSON.parse(settings.drying_presets);
  8294. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8295. return { ...DRYING_PRESETS, ...userPresets };
  8296. }
  8297. } catch { /* ignore parse errors, use defaults */ }
  8298. }
  8299. return DRYING_PRESETS;
  8300. }, [settings?.drying_presets]);
  8301. // The local choice wins over the stored one: someone without settings:update
  8302. // cannot write their pick back, and a preference that silently reverted on
  8303. // the next render would be worse than none at all.
  8304. const cameraViewMode: CameraViewMode =
  8305. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8306. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8307. storeCameraViewMode(mode);
  8308. setChosenCameraViewMode(mode);
  8309. // Best effort, and only a default for other browsers -- the choice is
  8310. // already in effect here. Users below settings:update simply keep theirs
  8311. // locally, which is why the failure is logged rather than surfaced.
  8312. if (hasPermission('settings:update')) {
  8313. api.updateSettings({ camera_view_mode: mode })
  8314. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8315. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8316. }
  8317. }, [hasPermission, queryClient]);
  8318. // Fetch all smart plugs to know which printers have them
  8319. const { data: smartPlugs } = useQuery({
  8320. queryKey: ['smart-plugs'],
  8321. queryFn: api.getSmartPlugs,
  8322. });
  8323. // Fetch maintenance overview for all printers to show badges
  8324. const { data: maintenanceOverview } = useQuery({
  8325. queryKey: ['maintenanceOverview'],
  8326. queryFn: api.getMaintenanceOverview,
  8327. staleTime: 60 * 1000, // 1 minute
  8328. });
  8329. // Live AI failure detection state for the card badges (#1546). Matches the
  8330. // 10s refetch of the Failure Detection settings panel.
  8331. const { data: obicoPrinterStatus } = useQuery({
  8332. queryKey: ['obico-printer-status'],
  8333. queryFn: api.getObicoPrinterStatus,
  8334. refetchInterval: 10000,
  8335. });
  8336. // Badge visibility: detection enabled AND this printer in the monitored set
  8337. // (monitored_printers null = all). Live per-print state is passed separately.
  8338. const isAiMonitored = useCallback(
  8339. (printerId: number) =>
  8340. obicoPrinterStatus?.enabled === true &&
  8341. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8342. [obicoPrinterStatus],
  8343. );
  8344. // Fetch Spoolman status to enable link spool feature
  8345. const { data: spoolmanStatus } = useQuery({
  8346. queryKey: ['spoolman-status'],
  8347. queryFn: api.getSpoolmanStatus,
  8348. staleTime: 60 * 1000, // 1 minute
  8349. });
  8350. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8351. // Fetch Spoolman settings to get sync mode
  8352. const { data: spoolmanSettings } = useQuery({
  8353. queryKey: ['spoolman-settings'],
  8354. queryFn: api.getSpoolmanSettings,
  8355. enabled: !!spoolmanEnabled,
  8356. staleTime: 60 * 1000, // 1 minute
  8357. });
  8358. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8359. // Fetch unlinked spools to know if link button should be enabled
  8360. const { data: unlinkedSpools } = useQuery({
  8361. queryKey: ['unlinked-spools'],
  8362. queryFn: api.getUnlinkedSpools,
  8363. enabled: !!spoolmanEnabled,
  8364. staleTime: 30 * 1000, // 30 seconds
  8365. });
  8366. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8367. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8368. const { data: linkedSpoolsData } = useQuery({
  8369. queryKey: ['linked-spools'],
  8370. queryFn: api.getLinkedSpools,
  8371. enabled: !!spoolmanEnabled,
  8372. staleTime: 30 * 1000, // 30 seconds
  8373. });
  8374. const linkedSpools = linkedSpoolsData?.linked;
  8375. // Fetch spool assignments for inventory feature
  8376. const { data: spoolAssignments } = useQuery({
  8377. queryKey: ['spool-assignments'],
  8378. queryFn: () => api.getAssignments(),
  8379. enabled: hasPermission('inventory:view_assignments'),
  8380. staleTime: 30 * 1000,
  8381. });
  8382. const unassignMutation = useMutation({
  8383. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8384. api.unassignSpool(printerId, amsId, trayId),
  8385. onSuccess: () => {
  8386. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8387. },
  8388. });
  8389. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8390. queryKey: ['spoolman-inventory-spools'],
  8391. queryFn: () => api.getSpoolmanInventorySpools(false),
  8392. enabled: !!spoolmanEnabled,
  8393. staleTime: 30 * 1000,
  8394. });
  8395. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8396. queryKey: ['spoolman-slot-assignments'],
  8397. queryFn: () => api.getSpoolmanSlotAssignments(),
  8398. enabled: !!spoolmanEnabled,
  8399. staleTime: 30 * 1000,
  8400. });
  8401. const unassignSpoolmanMutation = useMutation({
  8402. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8403. onSuccess: () => {
  8404. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8405. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8406. },
  8407. });
  8408. // Helper to find assignment for a specific slot
  8409. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8410. return spoolAssignments?.find(
  8411. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8412. );
  8413. };
  8414. // Create a map of printer_id -> maintenance info for quick lookup
  8415. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8416. (acc, overview) => {
  8417. acc[overview.printer_id] = {
  8418. due_count: overview.due_count,
  8419. warning_count: overview.warning_count,
  8420. total_print_hours: overview.total_print_hours,
  8421. };
  8422. return acc;
  8423. },
  8424. {} as Record<number, PrinterMaintenanceInfo>
  8425. ) || {};
  8426. // Create a map of printer_id -> smart plug
  8427. const smartPlugByPrinter = smartPlugs?.reduce(
  8428. (acc, plug) => {
  8429. if (plug.printer_id) {
  8430. acc[plug.printer_id] = plug;
  8431. }
  8432. return acc;
  8433. },
  8434. {} as Record<number, typeof smartPlugs[0]>
  8435. ) || {};
  8436. const addMutation = useMutation({
  8437. mutationFn: api.createPrinter,
  8438. onSuccess: () => {
  8439. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8440. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8441. setShowAddModal(false);
  8442. },
  8443. onError: (error: Error) => {
  8444. // Localized message when the backend returns a stable error code;
  8445. // the raw message is an English fallback for non-UI clients.
  8446. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8447. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8448. return;
  8449. }
  8450. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8451. },
  8452. });
  8453. const powerOnMutation = useMutation({
  8454. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8455. onSuccess: () => {
  8456. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8457. setPoweringOn(null);
  8458. },
  8459. onError: () => {
  8460. setPoweringOn(null);
  8461. },
  8462. });
  8463. // Bulk selection state
  8464. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8465. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8466. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8467. const [bulkActionPending, setBulkActionPending] = useState(false);
  8468. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8469. const toggleSelect = useCallback((id: number) => {
  8470. setSelectedPrinterIds(prev => {
  8471. const next = new Set(prev);
  8472. if (next.has(id)) next.delete(id);
  8473. else next.add(id);
  8474. return next;
  8475. });
  8476. }, []);
  8477. const clearSelection = useCallback(() => {
  8478. setSelectedPrinterIds(new Set());
  8479. setIsSelectionMode(false);
  8480. }, []);
  8481. // Escape key exits selection mode
  8482. useEffect(() => {
  8483. const handleKeyDown = (e: KeyboardEvent) => {
  8484. if (e.key === 'Escape' && selectionMode) {
  8485. clearSelection();
  8486. }
  8487. };
  8488. window.addEventListener('keydown', handleKeyDown);
  8489. return () => window.removeEventListener('keydown', handleKeyDown);
  8490. }, [selectionMode, clearSelection]);
  8491. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8492. setBulkActionPending(true);
  8493. const ids = Array.from(selectedPrinterIds);
  8494. // Filter to only applicable printers based on cached state
  8495. const applicableIds = ids.filter(id => {
  8496. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8497. if (!status?.connected) return false;
  8498. switch (action) {
  8499. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8500. case 'pause': return status.state === 'RUNNING';
  8501. case 'resume': return status.state === 'PAUSE';
  8502. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  8503. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8504. default: return false;
  8505. }
  8506. });
  8507. if (applicableIds.length === 0) {
  8508. showToast(t('printers.bulk.noneApplicable'), 'error');
  8509. setBulkActionPending(false);
  8510. setBulkConfirmAction(null);
  8511. return;
  8512. }
  8513. const apiCall = {
  8514. stop: api.stopPrint,
  8515. pause: api.pausePrint,
  8516. resume: api.resumePrint,
  8517. clearPlate: api.clearPlate,
  8518. clearHMS: api.clearHMSErrors,
  8519. }[action];
  8520. const results = await Promise.allSettled(
  8521. applicableIds.map(id => apiCall(id))
  8522. );
  8523. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8524. const failed = results.filter(r => r.status === 'rejected').length;
  8525. if (failed === 0) {
  8526. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8527. } else {
  8528. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8529. }
  8530. // Invalidate status queries for affected printers
  8531. applicableIds.forEach(id => {
  8532. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8533. });
  8534. setBulkActionPending(false);
  8535. setBulkConfirmAction(null);
  8536. }, [selectedPrinterIds, queryClient, showToast, t]);
  8537. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8538. // Actions that need confirmation
  8539. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8540. setBulkConfirmAction(action);
  8541. } else {
  8542. executeBulkAction(action);
  8543. }
  8544. }, [executeBulkAction]);
  8545. const toggleHideDisconnected = () => {
  8546. const newValue = !hideDisconnected;
  8547. setHideDisconnected(newValue);
  8548. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8549. };
  8550. const handleSortChange = (newSort: SortOption) => {
  8551. setSortBy(newSort);
  8552. localStorage.setItem('printerSortBy', newSort);
  8553. };
  8554. const handleStatusFilterChange = (value: string) => {
  8555. setStatusFilter(value);
  8556. localStorage.setItem('printerStatusFilter', value);
  8557. };
  8558. const handleLocationFilterChange = (value: string) => {
  8559. setLocationFilter(value);
  8560. localStorage.setItem('printerLocationFilter', value);
  8561. };
  8562. const toggleSortDirection = () => {
  8563. const newAsc = !sortAsc;
  8564. setSortAsc(newAsc);
  8565. localStorage.setItem('printerSortAsc', String(newAsc));
  8566. };
  8567. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8568. const getGridClasses = () => {
  8569. switch (cardSize) {
  8570. 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
  8571. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8572. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8573. case 4: return 'grid-cols-1'; // XL: single column, full width
  8574. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8575. }
  8576. };
  8577. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8578. // Increment version counter whenever a printer status cache entry is updated so
  8579. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8580. useEffect(() => {
  8581. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8582. if (
  8583. event.type === 'updated' &&
  8584. Array.isArray(event.query.queryKey) &&
  8585. event.query.queryKey[0] === 'printerStatus'
  8586. ) {
  8587. setStatusCacheVersion(v => v + 1);
  8588. }
  8589. });
  8590. return unsubscribe;
  8591. }, [queryClient]);
  8592. // Filter printers by search term, status, and location
  8593. const filteredPrinters = useMemo(() => {
  8594. if (!printers) return [];
  8595. let result = printers;
  8596. // Text search
  8597. if (search.trim()) {
  8598. const q = search.trim().toLowerCase();
  8599. result = result.filter(p =>
  8600. p.name.toLowerCase().includes(q) ||
  8601. (p.model || '').toLowerCase().includes(q) ||
  8602. (p.location || '').toLowerCase().includes(q) ||
  8603. (p.serial_number || '').toLowerCase().includes(q)
  8604. );
  8605. }
  8606. // Location filter
  8607. if (locationFilter !== 'all') {
  8608. result = result.filter(p => (p.location || '') === locationFilter);
  8609. }
  8610. // Status filter
  8611. if (statusFilter !== 'all') {
  8612. result = result.filter(p => {
  8613. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8614. if (!status?.connected) return statusFilter === 'offline';
  8615. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8616. switch (statusFilter) {
  8617. case 'printing': return status.state === 'RUNNING';
  8618. case 'paused': return status.state === 'PAUSE';
  8619. case 'finished': return status.state === 'FINISH';
  8620. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8621. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8622. case 'offline': return false; // Connected printers are never offline
  8623. default: return true;
  8624. }
  8625. });
  8626. }
  8627. return result;
  8628. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8629. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8630. // Derive unique locations for the location filter dropdown
  8631. const availableLocations = useMemo(() => {
  8632. if (!printers) return [];
  8633. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8634. }, [printers]);
  8635. // A saved location can outlive what it matched -- renamed, cleared, or the
  8636. // only printer that had it deleted. The dropdown is rendered only while some
  8637. // printer has a location, so a stale one would hide every printer *and* the
  8638. // control to undo it, leaving an empty page and no way back (#2833).
  8639. // Deliberately waits for `printers`: it is undefined while the query is in
  8640. // flight, and acting on the empty list that produces would throw the saved
  8641. // filter away every time the page loads.
  8642. useEffect(() => {
  8643. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8644. setLocationFilter('all');
  8645. localStorage.setItem('printerLocationFilter', 'all');
  8646. }, [printers, availableLocations, locationFilter]);
  8647. // Sort printers based on selected option
  8648. const sortedPrinters = useMemo(() => {
  8649. const sorted = [...filteredPrinters];
  8650. switch (sortBy) {
  8651. case 'name':
  8652. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8653. break;
  8654. case 'model':
  8655. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8656. break;
  8657. case 'location':
  8658. // Sort by location, with ungrouped printers last
  8659. sorted.sort((a, b) => {
  8660. const locA = a.location || '';
  8661. const locB = b.location || '';
  8662. if (!locA && locB) return 1;
  8663. if (locA && !locB) return -1;
  8664. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8665. });
  8666. break;
  8667. case 'status':
  8668. // Sort by status: HMS errors > printing > idle > offline
  8669. sorted.sort((a, b) => {
  8670. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8671. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8672. const getPriority = (s: typeof statusA) => {
  8673. if (!s?.connected) return 3; // offline
  8674. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8675. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8676. if (s.state === 'RUNNING') return 1; // printing
  8677. return 2; // idle
  8678. };
  8679. return getPriority(statusA) - getPriority(statusB);
  8680. });
  8681. break;
  8682. case 'eta':
  8683. sorted.sort((a, b) => {
  8684. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8685. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8686. const tier = (s: typeof statusA) => {
  8687. if (!s?.connected) return 3; // offline last
  8688. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8689. if (s.state === 'RUNNING') return 1; // printing without ETA
  8690. return 2; // idle
  8691. };
  8692. const ta = tier(statusA);
  8693. const tb = tier(statusB);
  8694. if (ta !== tb) return ta - tb;
  8695. if (ta === 0) {
  8696. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8697. if (diff !== 0) return diff;
  8698. }
  8699. return a.name.localeCompare(b.name);
  8700. });
  8701. break;
  8702. }
  8703. // Apply ascending/descending
  8704. if (!sortAsc) {
  8705. sorted.reverse();
  8706. }
  8707. return sorted;
  8708. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8709. const selectAll = useCallback(() => {
  8710. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8711. setIsSelectionMode(true);
  8712. }, [sortedPrinters]);
  8713. const selectByState = useCallback((state: PrinterState) => {
  8714. setSelectedPrinterIds(prev => {
  8715. const next = new Set(prev);
  8716. sortedPrinters.forEach(p => {
  8717. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8718. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8719. });
  8720. return next;
  8721. });
  8722. setIsSelectionMode(true);
  8723. }, [sortedPrinters, queryClient]);
  8724. const selectByLocation = useCallback((location: string) => {
  8725. setSelectedPrinterIds(prev => {
  8726. const next = new Set(prev);
  8727. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  8728. return next;
  8729. });
  8730. setIsSelectionMode(true);
  8731. }, [sortedPrinters]);
  8732. const selectByModel = useCallback((model: string) => {
  8733. setSelectedPrinterIds(prev => {
  8734. const next = new Set(prev);
  8735. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  8736. return next;
  8737. });
  8738. setIsSelectionMode(true);
  8739. }, [sortedPrinters]);
  8740. const toggleSectionCollapse = useCallback((key: string) => {
  8741. setCollapsedSections(prev => {
  8742. const next = { ...prev, [key]: !prev[key] };
  8743. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  8744. return next;
  8745. });
  8746. }, []);
  8747. // Group printers when sorted by location, status, or model
  8748. const groupedPrinters = useMemo(() => {
  8749. if (sortBy === 'name' || sortBy === 'eta') return null;
  8750. const groups: Record<string, typeof sortedPrinters> = {};
  8751. if (sortBy === 'location') {
  8752. sortedPrinters.forEach(printer => {
  8753. const location = printer.location || 'Ungrouped';
  8754. if (!groups[location]) groups[location] = [];
  8755. groups[location].push(printer);
  8756. });
  8757. } else if (sortBy === 'model') {
  8758. sortedPrinters.forEach(printer => {
  8759. const model = printer.model || 'Unknown';
  8760. if (!groups[model]) groups[model] = [];
  8761. groups[model].push(printer);
  8762. });
  8763. } else if (sortBy === 'status') {
  8764. sortedPrinters.forEach(printer => {
  8765. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  8766. const group = classifyPrinterStatus(status);
  8767. if (!groups[group]) groups[group] = [];
  8768. groups[group].push(printer);
  8769. });
  8770. }
  8771. return groups;
  8772. // 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
  8773. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  8774. const toolbarRef = useRef<HTMLDivElement>(null);
  8775. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  8776. const expandedToolbarWidthRef = useRef(0);
  8777. const [compactToolbar, setCompactToolbar] = useState(false);
  8778. const measureToolbar = useCallback(() => {
  8779. const toolbar = toolbarRef.current;
  8780. if (!toolbar) return;
  8781. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  8782. if (measuredControlsWidth) {
  8783. expandedToolbarWidthRef.current = measuredControlsWidth;
  8784. }
  8785. const searchMinimumWidth = 220;
  8786. const gapWidth = 8;
  8787. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  8788. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  8789. }, []);
  8790. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  8791. useLayoutEffect(() => {
  8792. measureToolbar();
  8793. const toolbar = toolbarRef.current;
  8794. if (!toolbar) return;
  8795. if (typeof ResizeObserver === 'undefined') {
  8796. window.addEventListener('resize', measureToolbar);
  8797. return () => window.removeEventListener('resize', measureToolbar);
  8798. }
  8799. const resizeObserver = new ResizeObserver(() => measureToolbar());
  8800. resizeObserver.observe(toolbar);
  8801. window.addEventListener('resize', measureToolbar);
  8802. return () => {
  8803. resizeObserver.disconnect();
  8804. window.removeEventListener('resize', measureToolbar);
  8805. };
  8806. }, [
  8807. measureToolbar,
  8808. printers?.length,
  8809. availableLocations.length,
  8810. hideDisconnected,
  8811. smartPlugCount,
  8812. ]);
  8813. const renderFilterControls = (inMenu = false) => (
  8814. <>
  8815. {/* Status filter */}
  8816. {printers && printers.length > 0 && (
  8817. <ToolbarDropdown
  8818. value={statusFilter}
  8819. onChange={handleStatusFilterChange}
  8820. fullWidth={inMenu}
  8821. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  8822. />
  8823. )}
  8824. {/* Location filter — only shown when at least one printer has a location */}
  8825. {printers && printers.length > 0 && availableLocations.length > 0 && (
  8826. <ToolbarDropdown
  8827. value={locationFilter}
  8828. onChange={handleLocationFilterChange}
  8829. fullWidth={inMenu}
  8830. options={[
  8831. { value: 'all', label: t('printers.filter.allLocations') },
  8832. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  8833. ]}
  8834. />
  8835. )}
  8836. <button
  8837. type="button"
  8838. onClick={toggleHideDisconnected}
  8839. aria-pressed={hideDisconnected}
  8840. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  8841. hideDisconnected
  8842. ? 'bg-bambu-green border-bambu-green text-white'
  8843. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8844. }`}
  8845. >
  8846. {t('printers.hideOffline')}
  8847. </button>
  8848. </>
  8849. );
  8850. const renderViewControls = (inMenu = false) => (
  8851. <>
  8852. {/* Sort dropdown */}
  8853. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8854. <ToolbarDropdown<SortOption>
  8855. value={sortBy}
  8856. onChange={handleSortChange}
  8857. fullWidth={inMenu}
  8858. options={[
  8859. { value: 'name', label: t('printers.sort.name') },
  8860. { value: 'status', label: t('printers.sort.status') },
  8861. { value: 'model', label: t('printers.sort.model') },
  8862. { value: 'location', label: t('printers.sort.location') },
  8863. { value: 'eta', label: t('printers.sort.eta') },
  8864. ]}
  8865. />
  8866. <button
  8867. onClick={toggleSortDirection}
  8868. 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"
  8869. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8870. >
  8871. {sortAsc ? (
  8872. <ArrowUp className="w-4 h-4 text-white" />
  8873. ) : (
  8874. <ArrowDown className="w-4 h-4 text-white" />
  8875. )}
  8876. </button>
  8877. </div>
  8878. {/* Page view toggle: Cards / Cam Wall */}
  8879. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8880. <button
  8881. type="button"
  8882. onClick={() => {
  8883. setPageView('cards');
  8884. localStorage.setItem('printerPageView', 'cards');
  8885. }}
  8886. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8887. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8888. }`}
  8889. title={t('printers.pageView.cards')}
  8890. aria-pressed={pageView === 'cards'}
  8891. >
  8892. <LayoutGrid className="w-3.5 h-3.5" />
  8893. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8894. </button>
  8895. <button
  8896. type="button"
  8897. onClick={() => {
  8898. setPageView('camwall');
  8899. localStorage.setItem('printerPageView', 'camwall');
  8900. }}
  8901. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8902. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8903. }`}
  8904. title={t('printers.pageView.camWall')}
  8905. aria-pressed={pageView === 'camwall'}
  8906. disabled={!hasPermission('camera:view')}
  8907. >
  8908. <MonitorPlay className="w-3.5 h-3.5" />
  8909. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8910. </button>
  8911. </div>
  8912. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8913. view, and the page a kiosk token points at. Only offered once the wall
  8914. is the active view, so it doesn't compete with the toggle above. */}
  8915. {pageView === 'camwall' && hasPermission('camera:view') && (
  8916. <RouterLink
  8917. to="/camwall"
  8918. 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' : ''}`}
  8919. title={t('printers.pageView.openCamWallPage')}
  8920. >
  8921. <ExternalLink className="w-3.5 h-3.5" />
  8922. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8923. </RouterLink>
  8924. )}
  8925. {/* Card size selector */}
  8926. <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' : ''}`}>
  8927. {cardSizeLabels.map((label, index) => {
  8928. const size = index + 1;
  8929. const isSelected = cardSize === size;
  8930. return (
  8931. <button
  8932. key={label}
  8933. onClick={() => {
  8934. setCompactDrilldownPrinterId(null);
  8935. setCardSize(size);
  8936. localStorage.setItem('printerCardSize', String(size));
  8937. }}
  8938. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8939. index === 0 ? 'rounded-l-lg' : ''
  8940. } ${
  8941. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8942. } ${
  8943. isSelected
  8944. ? 'bg-bambu-green text-white'
  8945. : 'text-white hover:bg-bambu-dark-tertiary'
  8946. }`}
  8947. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8948. >
  8949. {label}
  8950. </button>
  8951. );
  8952. })}
  8953. </div>
  8954. </>
  8955. );
  8956. const renderActionControls = (inMenu = false) => (
  8957. <>
  8958. {/* Bulk select toggle */}
  8959. <button
  8960. onClick={() => {
  8961. if (selectionMode) clearSelection();
  8962. else setIsSelectionMode(true);
  8963. }}
  8964. 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' : ''} ${
  8965. selectionMode
  8966. ? 'bg-bambu-green border-bambu-green text-white'
  8967. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8968. }`}
  8969. title={t('printers.bulk.select')}
  8970. disabled={!hasPermission('printers:control')}
  8971. >
  8972. <CheckSquare className="w-4 h-4" />
  8973. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8974. </button>
  8975. {/* Power dropdown for offline printers with smart plugs */}
  8976. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8977. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8978. <button
  8979. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8980. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8981. inMenu
  8982. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8983. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8984. }`}
  8985. >
  8986. <span className="flex items-center gap-1.5">
  8987. <Power className="w-4 h-4" />
  8988. {t('printers.powerOn')}
  8989. </span>
  8990. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8991. </button>
  8992. {showPowerDropdown && (
  8993. <>
  8994. {/* Backdrop to close dropdown */}
  8995. <div
  8996. className="fixed inset-0 z-10"
  8997. onClick={() => setShowPowerDropdown(false)}
  8998. />
  8999. <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">
  9000. <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">
  9001. {t('printers.offlinePrintersWithPlugs')}
  9002. </div>
  9003. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9004. <PowerDropdownItem
  9005. key={printer.id}
  9006. printer={printer}
  9007. plug={smartPlugByPrinter[printer.id]}
  9008. onPowerOn={(plugId) => {
  9009. setPoweringOn(plugId);
  9010. powerOnMutation.mutate(plugId);
  9011. }}
  9012. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9013. />
  9014. ))}
  9015. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9016. <div className="px-3 py-2 text-sm text-bambu-gray">
  9017. No printers with smart plugs
  9018. </div>
  9019. )}
  9020. </div>
  9021. </>
  9022. )}
  9023. </div>
  9024. )}
  9025. <Button
  9026. onClick={() => setShowAddModal(true)}
  9027. disabled={!hasPermission('printers:create')}
  9028. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9029. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9030. >
  9031. <Plus className="w-4 h-4" />
  9032. {t('printers.addPrinter')}
  9033. </Button>
  9034. </>
  9035. );
  9036. return (
  9037. <div className="p-4 md:p-8">
  9038. <div className="space-y-3 mb-6">
  9039. <div>
  9040. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9041. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9042. {t('printers.title')}
  9043. </h1>
  9044. <StatusSummaryBar printers={printers} />
  9045. </div>
  9046. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9047. {/* Only show search bar when printers exist */}
  9048. {printers && printers.length > 0 && (
  9049. <div className="relative min-w-0 flex-1">
  9050. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9051. <input
  9052. type="search"
  9053. name="printer-search"
  9054. autoComplete="off"
  9055. data-1p-ignore
  9056. data-lpignore="true"
  9057. value={search}
  9058. onChange={(e) => setSearch(e.target.value)}
  9059. placeholder={t('printers.search')}
  9060. aria-label={t('printers.search')}
  9061. 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"
  9062. />
  9063. {search && (
  9064. <button
  9065. type="button"
  9066. aria-label={t('common.clear')}
  9067. onClick={() => setSearch('')}
  9068. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9069. >
  9070. <X className="w-4 h-4" />
  9071. </button>
  9072. )}
  9073. </div>
  9074. )}
  9075. <div
  9076. ref={expandedToolbarControlsRef}
  9077. aria-hidden={compactToolbar}
  9078. inert={compactToolbar}
  9079. 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`}
  9080. >
  9081. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9082. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9083. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9084. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9085. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9086. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9087. </div>
  9088. {compactToolbar && (
  9089. <div className="ml-auto flex items-center justify-end gap-1">
  9090. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9091. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9092. </ToolbarMenu>
  9093. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9094. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9095. </ToolbarMenu>
  9096. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9097. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9098. </ToolbarMenu>
  9099. </div>
  9100. )}
  9101. </div>
  9102. </div>
  9103. {isLoading ? (
  9104. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9105. ) : printers?.length === 0 ? (
  9106. <Card>
  9107. <CardContent className="text-center py-12">
  9108. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9109. <Button
  9110. onClick={() => setShowAddModal(true)}
  9111. disabled={!hasPermission('printers:create')}
  9112. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9113. >
  9114. <Plus className="w-4 h-4" />
  9115. {t('printers.addPrinter')}
  9116. </Button>
  9117. </CardContent>
  9118. </Card>
  9119. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9120. <Card>
  9121. <CardContent className="text-center py-12">
  9122. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9123. </CardContent>
  9124. </Card>
  9125. ) : pageView === 'camwall' ? (
  9126. <CameraWall
  9127. printers={sortedPrinters}
  9128. maxLive={camWallMaxLive}
  9129. snapshotIntervalSec={camWallSnapshotSec}
  9130. onTileClick={(id, name) => {
  9131. // A wall tile has no room for a split button, so it follows the
  9132. // mode the card buttons last chose.
  9133. if (cameraViewMode === 'embedded') {
  9134. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9135. } else {
  9136. openCameraWindow(id);
  9137. }
  9138. }}
  9139. statusMode={camWallStatusMode}
  9140. onChangeMaxLive={(next) => {
  9141. setCamWallMaxLive(next);
  9142. localStorage.setItem('camWallMaxLive', String(next));
  9143. }}
  9144. onChangeSnapshotIntervalSec={(next) => {
  9145. setCamWallSnapshotSec(next);
  9146. localStorage.setItem('camWallSnapshotSec', String(next));
  9147. }}
  9148. onChangeStatusMode={(next) => {
  9149. setCamWallStatusMode(next);
  9150. localStorage.setItem('camWallStatusMode', next);
  9151. }}
  9152. />
  9153. ) : groupedPrinters ? (
  9154. /* Grouped view (location, status, or model) */
  9155. <div className="space-y-6">
  9156. {(() => {
  9157. const keys = sortBy === 'status'
  9158. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9159. : Object.keys(groupedPrinters);
  9160. // For status grouping, asc/desc flips the fixed priority order
  9161. // (asc = error→offline, desc = offline→error). This matches the
  9162. // sort-toggle behaviour for other groupings.
  9163. return (sortAsc ? keys : [...keys].reverse());
  9164. })().map((groupKey) => {
  9165. const groupPrinters = groupedPrinters[groupKey];
  9166. const collapseKey = `${sortBy}:${groupKey}`;
  9167. const isOpen = !collapsedSections[collapseKey];
  9168. const dot = sortBy === 'status'
  9169. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9170. : 'bg-bambu-green';
  9171. const label = sortBy === 'status'
  9172. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9173. : groupKey;
  9174. return (
  9175. <Collapsible
  9176. key={groupKey}
  9177. open={isOpen}
  9178. onToggle={() => toggleSectionCollapse(collapseKey)}
  9179. summaryClassName="py-1"
  9180. summary={
  9181. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9182. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9183. {label}
  9184. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9185. {selectionMode && (
  9186. <button
  9187. onClick={(e) => {
  9188. e.stopPropagation();
  9189. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9190. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9191. else if (sortBy === 'model') selectByModel(groupKey);
  9192. }}
  9193. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9194. >
  9195. {t('printers.bulk.selectAll')}
  9196. </button>
  9197. )}
  9198. </h2>
  9199. }
  9200. >
  9201. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9202. {groupPrinters.map((printer) => (
  9203. <PrinterCard
  9204. key={printer.id}
  9205. printer={printer}
  9206. hideIfDisconnected={hideDisconnected}
  9207. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9208. viewMode={viewMode}
  9209. cardSize={cardSize}
  9210. amsThresholds={settings ? {
  9211. humidityGood: Number(settings.ams_humidity_good) || 40,
  9212. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9213. tempGood: Number(settings.ams_temp_good) || 28,
  9214. tempFair: Number(settings.ams_temp_fair) || 35,
  9215. } : undefined}
  9216. spoolmanEnabled={spoolmanEnabled}
  9217. hasUnlinkedSpools={hasUnlinkedSpools}
  9218. linkedSpools={linkedSpools}
  9219. spoolmanUrl={spoolmanStatus?.url}
  9220. spoolmanSyncMode={spoolmanSyncMode}
  9221. onGetAssignment={getAssignment}
  9222. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9223. spoolmanSpools={spoolmanSpools}
  9224. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9225. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9226. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9227. timeFormat={settings?.time_format || 'system'}
  9228. cameraViewMode={cameraViewMode}
  9229. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9230. onSelectCameraViewMode={selectCameraViewMode}
  9231. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9232. dryingPresets={effectiveDryingPresets}
  9233. nozzleTempPresets={effectiveNozzleTempPresets}
  9234. bedTempPresets={effectiveBedTempPresets}
  9235. chamberTempPresets={effectiveChamberTempPresets}
  9236. fanSpeedPresets={effectiveFanSpeedPresets}
  9237. requirePlateClear={settings?.require_plate_clear === true}
  9238. selectionMode={selectionMode}
  9239. isSelected={selectedPrinterIds.has(printer.id)}
  9240. onToggleSelect={toggleSelect}
  9241. onOpenCompactCard={openCompactCard}
  9242. aiDetectionEnabled={isAiMonitored(printer.id)}
  9243. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9244. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9245. />
  9246. ))}
  9247. </div>
  9248. </Collapsible>
  9249. );
  9250. })}
  9251. </div>
  9252. ) : (
  9253. /* Regular grid view */
  9254. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9255. {sortedPrinters.map((printer) => (
  9256. <PrinterCard
  9257. key={printer.id}
  9258. printer={printer}
  9259. hideIfDisconnected={hideDisconnected}
  9260. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9261. viewMode={viewMode}
  9262. cardSize={cardSize}
  9263. spoolmanEnabled={spoolmanEnabled}
  9264. hasUnlinkedSpools={hasUnlinkedSpools}
  9265. linkedSpools={linkedSpools}
  9266. spoolmanUrl={spoolmanStatus?.url}
  9267. spoolmanSyncMode={spoolmanSyncMode}
  9268. onGetAssignment={getAssignment}
  9269. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9270. spoolmanSpools={spoolmanSpools}
  9271. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9272. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9273. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9274. amsThresholds={settings ? {
  9275. humidityGood: Number(settings.ams_humidity_good) || 40,
  9276. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9277. tempGood: Number(settings.ams_temp_good) || 28,
  9278. tempFair: Number(settings.ams_temp_fair) || 35,
  9279. } : undefined}
  9280. timeFormat={settings?.time_format || 'system'}
  9281. cameraViewMode={cameraViewMode}
  9282. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9283. onSelectCameraViewMode={selectCameraViewMode}
  9284. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9285. dryingPresets={effectiveDryingPresets}
  9286. nozzleTempPresets={effectiveNozzleTempPresets}
  9287. bedTempPresets={effectiveBedTempPresets}
  9288. chamberTempPresets={effectiveChamberTempPresets}
  9289. fanSpeedPresets={effectiveFanSpeedPresets}
  9290. requirePlateClear={settings?.require_plate_clear === true}
  9291. selectionMode={selectionMode}
  9292. isSelected={selectedPrinterIds.has(printer.id)}
  9293. onToggleSelect={toggleSelect}
  9294. onOpenCompactCard={openCompactCard}
  9295. aiDetectionEnabled={isAiMonitored(printer.id)}
  9296. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9297. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9298. />
  9299. ))}
  9300. </div>
  9301. )}
  9302. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9303. <button
  9304. type="button"
  9305. onClick={returnToCompactCards}
  9306. 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}`}
  9307. title={t('common.back', 'Back')}
  9308. >
  9309. <ArrowLeft className="w-4 h-4" />
  9310. {t('common.back', 'Back')}
  9311. </button>
  9312. )}
  9313. {showAddModal && (
  9314. <AddPrinterModal
  9315. onClose={() => setShowAddModal(false)}
  9316. onAdd={(data) => addMutation.mutate(data)}
  9317. existingSerials={printers?.map(p => p.serial_number) || []}
  9318. />
  9319. )}
  9320. {/* Bulk selection toolbar */}
  9321. {selectionMode && printers && (
  9322. <BulkPrinterToolbar
  9323. selectedIds={selectedPrinterIds}
  9324. printers={printers}
  9325. onClose={clearSelection}
  9326. onSelectAll={selectAll}
  9327. onSelectByLocation={selectByLocation}
  9328. onSelectByState={selectByState}
  9329. onAction={handleBulkAction}
  9330. actionPending={bulkActionPending}
  9331. />
  9332. )}
  9333. {/* Bulk action confirmation modals */}
  9334. {bulkConfirmAction === 'stop' && (
  9335. <ConfirmModal
  9336. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9337. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9338. confirmText={t('printers.bulk.confirm.stopButton')}
  9339. variant="danger"
  9340. isLoading={bulkActionPending}
  9341. onConfirm={() => executeBulkAction('stop')}
  9342. onCancel={() => setBulkConfirmAction(null)}
  9343. />
  9344. )}
  9345. {bulkConfirmAction === 'pause' && (
  9346. <ConfirmModal
  9347. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9348. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9349. confirmText={t('printers.bulk.confirm.pauseButton')}
  9350. isLoading={bulkActionPending}
  9351. onConfirm={() => executeBulkAction('pause')}
  9352. onCancel={() => setBulkConfirmAction(null)}
  9353. />
  9354. )}
  9355. {bulkConfirmAction === 'clearPlate' && (
  9356. <ConfirmModal
  9357. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9358. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9359. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9360. isLoading={bulkActionPending}
  9361. onConfirm={() => executeBulkAction('clearPlate')}
  9362. onCancel={() => setBulkConfirmAction(null)}
  9363. />
  9364. )}
  9365. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9366. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9367. <EmbeddedCameraViewer
  9368. key={camera.id}
  9369. printerId={camera.id}
  9370. printerName={camera.name}
  9371. viewerIndex={index}
  9372. onClose={() => setEmbeddedCameraPrinters(prev => {
  9373. const next = new Map(prev);
  9374. next.delete(camera.id);
  9375. return next;
  9376. })}
  9377. />
  9378. ))}
  9379. </div>
  9380. );
  9381. }