PrintersPage.tsx 480 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922
  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. // K-profile value shown on the slot card itself (#2532) rather than only inside
  206. // the hover popup, the way BambuStudio shows it per slot.
  207. //
  208. // `k` arrives already gated on the slot being loaded; falsy means the printer
  209. // never reported a calibration for it. formatKValue() substitutes 0.020 for a
  210. // missing value, which is captioned inside the hover card but would read as a
  211. // real measurement on this permanent, uncaptioned line -- so an uncalibrated
  212. // slot gets no value at all. A ternary rather than `k && <div/>`: a firmware-
  213. // reported 0 makes that expression evaluate to the number 0, and React renders
  214. // numbers, putting a bare "0" under the material name.
  215. //
  216. // `reserve` holds the row's height open on the slots without a value whenever
  217. // some other slot on the same card has one, so every fill bar stays on one line.
  218. function KValueLine({ k, reserve }: { k: number | null | undefined; reserve: boolean }) {
  219. const { t } = useTranslation();
  220. const className = 'text-[length:var(--pc-t8,8px)] text-bambu-gray tabular-nums leading-none truncate';
  221. if (!k) {
  222. return reserve ? <div className={className} aria-hidden="true">&nbsp;</div> : null;
  223. }
  224. // Short label, full localized name on the title: "K Factor" / "K-Faktor" /
  225. // "Facteur K" clipped the value itself below ~70px, and the slot grid floor is
  226. // 3.5rem. tabular-nums rather than font-mono, which resolved to a different
  227. // family per browser and so measured differently in Safari.
  228. return (
  229. <div className={className} title={t('ams.kFactor')}>
  230. {t('ams.kFactorShort')} {formatKValue(k)}
  231. </div>
  232. );
  233. }
  234. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  235. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  236. const { mode } = useTheme();
  237. const { t } = useTranslation();
  238. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  239. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  240. return (
  241. <span
  242. 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"
  243. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  244. title={side === 'L' ? t('common.left') : t('common.right')}
  245. >
  246. {side}
  247. </span>
  248. );
  249. }
  250. // Filament Track Switch inlet indicator. Same L/R lettering as NozzleBadge but
  251. // deliberately a different colour, because it means something different: this
  252. // AMS is plumbed into one switch inlet and reaches BOTH nozzles through it.
  253. function InletBadge({ inlet, title }: { inlet: 'A' | 'B'; title: string }) {
  254. const { mode } = useTheme();
  255. const bgColor = mode === 'dark' ? '#1e3a5f' : '#e3f0fb';
  256. return (
  257. <span
  258. 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"
  259. style={{ backgroundColor: bgColor, color: '#3b82f6' }}
  260. title={title}
  261. >
  262. {FTS_INLET_SIDE[inlet]}
  263. </span>
  264. );
  265. }
  266. /**
  267. * Which side indicator, if any, belongs on an AMS card header.
  268. *
  269. * Three sources, in descending authority:
  270. * 1. A Filament Track Switch inlet binding — the AMS feeds both nozzles
  271. * through the switch, so the inlet is the only meaningful label.
  272. * 2. A real extruder id from ams_extruder_map.
  273. * 3. The AMS unit id, as a last-resort guess for dual-nozzle printers that
  274. * never reported a map. This one is only a guess, and it is suppressed
  275. * when a switch is installed: with an FTS every unit reports extruder
  276. * 0xE, so the fallback would silently label AMS 0 "R" and AMS 1 "L" from
  277. * nothing but their unit numbers.
  278. */
  279. function amsSideBadge(
  280. amsId: number,
  281. amsExtruderMap: Record<string, number>,
  282. amsSwitchInlet: Record<string, 'A' | 'B'>,
  283. ftsInstalled: boolean
  284. ): { kind: 'inlet'; inlet: 'A' | 'B' } | { kind: 'nozzle'; side: 'L' | 'R' } | null {
  285. const inlet = amsSwitchInlet[String(amsId)];
  286. if (inlet) return { kind: 'inlet', inlet };
  287. const mapped = amsExtruderMap[String(amsId)];
  288. const extruderId = mapped !== undefined ? mapped : ftsInstalled ? undefined : amsId >= 128 ? amsId - 128 : amsId;
  289. if (extruderId === 1) return { kind: 'nozzle', side: 'L' };
  290. if (extruderId === 0) return { kind: 'nozzle', side: 'R' };
  291. return null;
  292. }
  293. // Expand nozzle type codes to material names
  294. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  295. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  296. function nozzleTypeName(type: string, t: (key: string) => string): string {
  297. if (!type) return '';
  298. // Full text names (from main nozzle info)
  299. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  300. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  301. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  302. // 4-char codes (e.g. "HS01"): last 2 digits = material
  303. if (type.length >= 4) {
  304. const material = type.slice(2, 4);
  305. if (material === '00') return t('printers.nozzleStainlessSteel');
  306. if (material === '01') return t('printers.nozzleHardenedSteel');
  307. if (material === '05') return t('printers.nozzleTungstenCarbide');
  308. }
  309. // 2-digit numeric codes
  310. if (type === '00') return t('printers.nozzleStainlessSteel');
  311. if (type === '01') return t('printers.nozzleHardenedSteel');
  312. if (type === '05') return t('printers.nozzleTungstenCarbide');
  313. // 2-char alpha codes: H prefix = hardened steel
  314. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  315. return type;
  316. }
  317. // Parse flow type from nozzle type code
  318. // HH = high flow, HS = standard/normal
  319. function nozzleFlowName(type: string, t: (key: string) => string): string {
  320. if (!type) return '';
  321. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  322. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  323. return '';
  324. }
  325. // Per-slot hover card for nozzle rack
  326. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  327. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  328. slot: import('../api/client').NozzleRackSlot;
  329. index: number;
  330. activeStatus?: boolean;
  331. filamentName?: string;
  332. children: React.ReactNode;
  333. }) {
  334. const { t } = useTranslation();
  335. const [isVisible, setIsVisible] = useState(false);
  336. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  337. const triggerRef = useRef<HTMLDivElement>(null);
  338. const cardRef = useRef<HTMLDivElement>(null);
  339. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  340. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  341. const isMounted = slot.stat === 1;
  342. useEffect(() => {
  343. if (isVisible && triggerRef.current && cardRef.current) {
  344. const triggerRect = triggerRef.current.getBoundingClientRect();
  345. const cardHeight = cardRef.current.offsetHeight;
  346. const headerHeight = 56;
  347. const spaceAbove = triggerRect.top - headerHeight;
  348. const spaceBelow = window.innerHeight - triggerRect.bottom;
  349. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  350. setPosition('bottom');
  351. } else {
  352. setPosition('top');
  353. }
  354. }
  355. }, [isVisible]);
  356. const handleMouseEnter = () => {
  357. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  358. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  359. };
  360. const handleMouseLeave = () => {
  361. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  362. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  363. };
  364. useEffect(() => {
  365. return () => {
  366. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  367. };
  368. }, []);
  369. const filamentCss = parseFilamentColor(slot.filament_color);
  370. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  371. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  372. return (
  373. <div
  374. ref={triggerRef}
  375. className="relative"
  376. onMouseEnter={handleMouseEnter}
  377. onMouseLeave={handleMouseLeave}
  378. >
  379. {children}
  380. {isVisible && (
  381. <div
  382. ref={cardRef}
  383. className={`
  384. absolute left-1/2 -translate-x-1/2 z-50
  385. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  386. animate-in fade-in-0 zoom-in-95 duration-150
  387. `}
  388. style={{ maxWidth: 'calc(100vw - 24px)' }}
  389. >
  390. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  391. {isEmpty ? (
  392. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  393. Slot {index + 1} — Empty
  394. </div>
  395. ) : (
  396. <div className="p-2.5 space-y-1.5">
  397. {/* Diameter */}
  398. <div className="flex items-center justify-between">
  399. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  400. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  401. </div>
  402. {/* Type */}
  403. {typeFull && (
  404. <div className="flex items-center justify-between">
  405. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  406. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  407. </div>
  408. )}
  409. {/* Flow (hide if empty) */}
  410. {flowFull && (
  411. <div className="flex items-center justify-between">
  412. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  413. <span className="text-xs text-white font-semibold">{flowFull}</span>
  414. </div>
  415. )}
  416. {/* Status badge */}
  417. <div className="flex items-center justify-between">
  418. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  419. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  420. activeStatus || isMounted
  421. ? 'bg-green-900/50 text-green-400'
  422. : 'bg-bambu-dark-tertiary text-bambu-gray'
  423. }`}>
  424. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  425. </span>
  426. </div>
  427. {/* Wear (hide if null) */}
  428. {slot.wear != null && (
  429. <div className="flex items-center justify-between">
  430. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  431. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  432. </div>
  433. )}
  434. {/* Max Temp (hide if 0) */}
  435. {slot.max_temp > 0 && (
  436. <div className="flex items-center justify-between">
  437. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  438. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  439. </div>
  440. )}
  441. {/* Serial (hide if empty) */}
  442. {slot.serial_number && (
  443. <div className="flex items-center justify-between">
  444. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  445. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  446. </div>
  447. )}
  448. {/* Filament: material type + color swatch (hide if no color) */}
  449. {(filamentCss || slot.filament_type) && (
  450. <div className="flex items-center justify-between">
  451. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  452. <div className="flex items-center gap-1">
  453. {filamentCss && (
  454. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  455. )}
  456. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  457. </div>
  458. </div>
  459. )}
  460. </div>
  461. )}
  462. </div>
  463. {/* Arrow pointer */}
  464. <div
  465. className={`
  466. absolute left-1/2 -translate-x-1/2 w-0 h-0
  467. border-l-[6px] border-l-transparent
  468. border-r-[6px] border-r-transparent
  469. ${position === 'top'
  470. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  471. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  472. `}
  473. />
  474. </div>
  475. )}
  476. </div>
  477. );
  478. }
  479. // Dual-nozzle hover card showing L and R nozzle details side by side
  480. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  481. leftSlot?: import('../api/client').NozzleRackSlot;
  482. rightSlot?: import('../api/client').NozzleRackSlot;
  483. activeNozzle: 'L' | 'R';
  484. filamentInfo?: Record<string, { name: string; k: number | null }>;
  485. children: React.ReactNode;
  486. }) {
  487. const { t } = useTranslation();
  488. const [isVisible, setIsVisible] = useState(false);
  489. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  490. const triggerRef = useRef<HTMLDivElement>(null);
  491. const cardRef = useRef<HTMLDivElement>(null);
  492. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  493. useEffect(() => {
  494. if (isVisible && triggerRef.current && cardRef.current) {
  495. const triggerRect = triggerRef.current.getBoundingClientRect();
  496. const cardHeight = cardRef.current.offsetHeight;
  497. const headerHeight = 56;
  498. const spaceAbove = triggerRect.top - headerHeight;
  499. const spaceBelow = window.innerHeight - triggerRect.bottom;
  500. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  501. setPosition('bottom');
  502. } else {
  503. setPosition('top');
  504. }
  505. }
  506. }, [isVisible]);
  507. const handleMouseEnter = () => {
  508. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  509. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  510. };
  511. const handleMouseLeave = () => {
  512. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  513. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  514. };
  515. useEffect(() => {
  516. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  517. }, []);
  518. if (!leftSlot && !rightSlot) return <>{children}</>;
  519. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  520. const isActive = activeNozzle === side;
  521. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  522. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  523. const filamentCss = parseFilamentColor(slot.filament_color);
  524. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  525. return (
  526. <div className="flex-1 space-y-1.5">
  527. <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'}`}>
  528. {side === 'L' ? t('common.left') : t('common.right')}
  529. </div>
  530. {slot.nozzle_diameter && (
  531. <div className="flex items-center justify-between">
  532. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  533. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  534. </div>
  535. )}
  536. {typeFull && (
  537. <div className="flex items-center justify-between">
  538. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  539. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  540. </div>
  541. )}
  542. {flowFull && (
  543. <div className="flex items-center justify-between">
  544. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  545. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  546. </div>
  547. )}
  548. <div className="flex items-center justify-between">
  549. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  550. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  551. isActive
  552. ? 'bg-green-900/50 text-green-400'
  553. : 'bg-bambu-dark-tertiary text-bambu-gray'
  554. }`}>
  555. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  556. </span>
  557. </div>
  558. {slot.wear != null && (
  559. <div className="flex items-center justify-between">
  560. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  561. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  562. </div>
  563. )}
  564. {/* Serial and max temp only available on the right (removable) nozzle */}
  565. {side === 'R' && slot.max_temp > 0 && (
  566. <div className="flex items-center justify-between">
  567. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  568. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  569. </div>
  570. )}
  571. {side === 'R' && slot.serial_number && (
  572. <div className="flex items-center justify-between">
  573. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  574. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  575. </div>
  576. )}
  577. {(filamentCss || slot.filament_type || slot.filament_id) && (
  578. <div className="flex items-center justify-between">
  579. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  580. <div className="flex items-center gap-1">
  581. {filamentCss && (
  582. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  583. )}
  584. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  585. {filamentName || slot.filament_type || slot.filament_id || ''}
  586. </span>
  587. </div>
  588. </div>
  589. )}
  590. </div>
  591. );
  592. };
  593. return (
  594. <div
  595. ref={triggerRef}
  596. className="relative flex-1"
  597. onMouseEnter={handleMouseEnter}
  598. onMouseLeave={handleMouseLeave}
  599. >
  600. {children}
  601. {isVisible && (
  602. <div
  603. ref={cardRef}
  604. className={`
  605. absolute left-1/2 -translate-x-1/2 z-50
  606. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  607. animate-in fade-in-0 zoom-in-95 duration-150
  608. `}
  609. style={{ maxWidth: 'calc(100vw - 24px)' }}
  610. >
  611. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  612. <div className="p-2.5 flex gap-3">
  613. {leftSlot && renderColumn(leftSlot, 'L')}
  614. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  615. {rightSlot && renderColumn(rightSlot, 'R')}
  616. </div>
  617. </div>
  618. {/* Arrow pointer */}
  619. <div
  620. className={`
  621. absolute left-1/2 -translate-x-1/2 w-0 h-0
  622. border-l-[6px] border-l-transparent
  623. border-r-[6px] border-r-transparent
  624. ${position === 'top'
  625. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  626. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  627. `}
  628. />
  629. </div>
  630. )}
  631. </div>
  632. );
  633. }
  634. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  635. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  636. const { t } = useTranslation();
  637. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  638. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  639. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  640. // base — computing it from min(present IDs) shifts everything left when slot 16
  641. // is the one currently mounted (#943).
  642. const rackNozzles = slots.filter(s => s.id >= 2);
  643. const RACK_SIZE = 6;
  644. const RACK_BASE_ID = 16;
  645. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  646. { length: RACK_SIZE },
  647. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  648. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  649. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  650. },
  651. );
  652. return (
  653. // Sized to its contents rather than growing: the six chips are a fixed
  654. // width at any one card size, so extra width would be dead space taken
  655. // from the temperature cards beside it — which are flex-1 with a 0 basis
  656. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  657. // stays enabled so the card still gives way on a narrow printer card
  658. // instead of overflowing.
  659. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  660. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  661. <div className="flex gap-[3px] justify-center">
  662. {rackSlots.map((slot, i) => {
  663. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  664. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  665. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  666. return (
  667. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  668. <div className="flex flex-col items-center gap-0.5">
  669. <div
  670. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  671. isEmpty
  672. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  673. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  674. }`}
  675. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  676. >
  677. <span
  678. data-rack-diameter
  679. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  680. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  681. >
  682. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  683. </span>
  684. </div>
  685. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  686. acted on without counting chips. Sits below the chip rather
  687. than inside it: the chip is barely wider than its own
  688. diameter text and already carries that over a
  689. filament-coloured background. */}
  690. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  691. {i + 1}
  692. </span>
  693. </div>
  694. </NozzleSlotHoverCard>
  695. );
  696. })}
  697. </div>
  698. </div>
  699. );
  700. }
  701. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  702. function WaterDropEmpty({ className }: { className?: string }) {
  703. return (
  704. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  705. <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"/>
  706. </svg>
  707. );
  708. }
  709. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  710. function WaterDropHalf({ className }: { className?: string }) {
  711. return (
  712. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  713. <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"/>
  714. <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"/>
  715. </svg>
  716. );
  717. }
  718. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  719. function WaterDropFull({ className }: { className?: string }) {
  720. return (
  721. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  722. <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"/>
  723. <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"/>
  724. </svg>
  725. );
  726. }
  727. // Thermometer SVG - empty outline
  728. function ThermometerEmpty({ className }: { className?: string }) {
  729. return (
  730. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  731. <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"/>
  732. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  733. </svg>
  734. );
  735. }
  736. // Thermometer SVG - half filled (gold - same as humidity fair)
  737. function ThermometerHalf({ className }: { className?: string }) {
  738. return (
  739. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  740. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  741. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  742. <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"/>
  743. </svg>
  744. );
  745. }
  746. // Thermometer SVG - fully filled (red - same as humidity bad)
  747. function ThermometerFull({ className }: { className?: string }) {
  748. return (
  749. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  750. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  751. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  752. <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"/>
  753. </svg>
  754. );
  755. }
  756. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  757. // Added for visual parity with the thermometer icons on the dual-nozzle card
  758. // that previously had no icon at all (#1115, design by @m4rtini2).
  759. function NozzleIcon({ className }: { className?: string }) {
  760. return (
  761. <svg
  762. className={className}
  763. viewBox="0 0 24 24"
  764. fill="none"
  765. xmlns="http://www.w3.org/2000/svg"
  766. stroke="currentColor"
  767. strokeWidth="1.5"
  768. strokeLinecap="round"
  769. strokeLinejoin="round"
  770. >
  771. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  772. <rect x="6" y="11.5" width="12.1" height="3.7" />
  773. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  774. </svg>
  775. );
  776. }
  777. // Heater thermometer icon - filled when heating, outline when off
  778. interface HeaterThermometerProps {
  779. className?: string;
  780. color: string; // The color class (e.g., "text-orange-400")
  781. isHeating: boolean;
  782. }
  783. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  784. // Extract the actual color from Tailwind class for SVG fill
  785. const colorMap: Record<string, string> = {
  786. 'text-orange-400': '#fb923c',
  787. 'text-blue-400': '#60a5fa',
  788. 'text-green-400': '#4ade80',
  789. };
  790. const fillColor = colorMap[color] || '#888';
  791. // Glow style when heating
  792. const glowStyle = isHeating ? {
  793. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  794. } : {};
  795. if (isHeating) {
  796. // Filled thermometer with glow - heater is ON
  797. return (
  798. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  799. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  800. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  801. <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"/>
  802. </svg>
  803. );
  804. }
  805. // Empty thermometer - heater is OFF
  806. return (
  807. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  808. <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"/>
  809. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  810. </svg>
  811. );
  812. }
  813. // AMS Filament Backup tri-state indicator + toggle.
  814. // state=true → ON, click to disable
  815. // state=false → OFF, click opens modal
  816. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  817. interface AmsBackupBadgeProps {
  818. state: boolean | null;
  819. onClick: () => void;
  820. }
  821. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  822. const { t } = useTranslation();
  823. const known = state !== null;
  824. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  825. let title: string;
  826. if (state === true) {
  827. className += known
  828. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  829. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  830. title = t('printers.amsBackup.titleOn');
  831. } else if (state === false) {
  832. className += known
  833. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  834. : 'bg-bambu-dark text-bambu-gray cursor-default';
  835. title = t('printers.amsBackup.titleOff');
  836. } else {
  837. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  838. title = t('printers.amsBackup.titleUnknown');
  839. }
  840. return (
  841. <button
  842. type="button"
  843. disabled={!known}
  844. onClick={() => known && onClick()}
  845. className={className}
  846. title={title}
  847. aria-label={title}
  848. >
  849. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  850. </button>
  851. );
  852. }
  853. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  854. // like AmsBackupBadge so the two sit together in the section header, but
  855. // pinned to the right-hand end of the rule: this is a view preference for the
  856. // row, not a property of the printer.
  857. interface ExternalSpoolToggleProps {
  858. hidden: boolean;
  859. onClick: () => void;
  860. }
  861. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  862. const { t } = useTranslation();
  863. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  864. return (
  865. <button
  866. type="button"
  867. onClick={onClick}
  868. aria-pressed={hidden}
  869. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  870. hidden
  871. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  872. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  873. }`}
  874. title={title}
  875. aria-label={title}
  876. >
  877. {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)]" />}
  878. </button>
  879. );
  880. }
  881. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  882. // Reference: https://github.com/theicedmango/bambu-humidity
  883. interface HumidityIndicatorProps {
  884. humidity: number | string;
  885. goodThreshold?: number; // <= this is green
  886. fairThreshold?: number; // <= this is orange, > is red
  887. onClick?: () => void;
  888. compact?: boolean; // Smaller version for grid layout
  889. }
  890. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  891. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  892. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  893. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  894. // Status thresholds (configurable via settings)
  895. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  896. let textColor: string;
  897. let statusText: string;
  898. if (isNaN(humidityValue)) {
  899. textColor = '#C3C2C1';
  900. statusText = 'Unknown';
  901. } else if (humidityValue <= good) {
  902. textColor = '#22a352'; // Green - Good
  903. statusText = 'Good';
  904. } else if (humidityValue <= fair) {
  905. textColor = '#d4a017'; // Gold - Fair
  906. statusText = 'Fair';
  907. } else {
  908. textColor = '#c62828'; // Red - Bad
  909. statusText = 'Bad';
  910. }
  911. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  912. let DropComponent: React.FC<{ className?: string }>;
  913. if (isNaN(humidityValue)) {
  914. DropComponent = WaterDropEmpty;
  915. } else if (humidityValue <= good) {
  916. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  917. } else if (humidityValue <= fair) {
  918. DropComponent = WaterDropHalf; // Fair - half filled
  919. } else {
  920. DropComponent = WaterDropFull; // Bad - full (too humid)
  921. }
  922. return (
  923. <button
  924. type="button"
  925. onClick={onClick}
  926. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  927. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  928. >
  929. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  930. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  931. </button>
  932. );
  933. }
  934. // Temperature indicator with dynamic icon and coloring
  935. interface TemperatureIndicatorProps {
  936. temp: number;
  937. goodThreshold?: number; // <= this is blue
  938. fairThreshold?: number; // <= this is orange, > is red
  939. onClick?: () => void;
  940. compact?: boolean; // Smaller version for grid layout
  941. }
  942. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  943. // Ensure thresholds are numbers
  944. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  945. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  946. let textColor: string;
  947. let statusText: string;
  948. let ThermoComponent: React.FC<{ className?: string }>;
  949. if (temp <= good) {
  950. textColor = '#22a352'; // Green - good (same as humidity)
  951. statusText = 'Good';
  952. ThermoComponent = ThermometerEmpty;
  953. } else if (temp <= fair) {
  954. textColor = '#d4a017'; // Gold - fair (same as humidity)
  955. statusText = 'Fair';
  956. ThermoComponent = ThermometerHalf;
  957. } else {
  958. textColor = '#c62828'; // Red - bad (same as humidity)
  959. statusText = 'Bad';
  960. ThermoComponent = ThermometerFull;
  961. }
  962. return (
  963. <button
  964. type="button"
  965. onClick={onClick}
  966. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  967. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  968. >
  969. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  970. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  971. </button>
  972. );
  973. }
  974. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  975. *
  976. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  977. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  978. * every empty-by-bitmask slot lands here regardless of firmware payload
  979. * shape.
  980. *
  981. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  982. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  983. * the user cleared with "Reset Slot" where a physical spool may still be
  984. * loaded but unassigned.
  985. *
  986. * Returns null when the slot is loaded (tray_type is present).
  987. */
  988. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  989. if (tray?.tray_type) return null;
  990. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  991. // spool the firmware can't identify is physically present (exists === true)
  992. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  993. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  994. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  995. if (tray?.exists === true) return 'reset';
  996. if (tray?.exists === false) return 'physical';
  997. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  998. }
  999. // How long to wait for an AMS to report a live drying cycle after the printer
  1000. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  1001. // within a couple of seconds; 30s covers the slowest observed push cadence
  1002. // without leaving the user waiting on a verdict.
  1003. const DRY_START_CONFIRM_MS = 30_000;
  1004. export function CoverImage({
  1005. url,
  1006. printName,
  1007. className = 'w-20 h-20',
  1008. radiusClass = 'rounded-lg',
  1009. }: {
  1010. url: string | null;
  1011. printName?: string;
  1012. className?: string;
  1013. radiusClass?: string;
  1014. }) {
  1015. const { t } = useTranslation();
  1016. const [loaded, setLoaded] = useState(false);
  1017. const [error, setError] = useState(false);
  1018. const [showOverlay, setShowOverlay] = useState(false);
  1019. const imgRef = useRef<HTMLImageElement>(null);
  1020. // Cache-bust the image URL when the print name changes so the browser
  1021. // fetches the new cover instead of serving the stale cached image.
  1022. const cacheBustedUrl = useMemo(() => {
  1023. if (!url) return null;
  1024. const sep = url.includes('?') ? '&' : '?';
  1025. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  1026. }, [url, printName]);
  1027. // Re-evaluate load state when the image URL changes, and ask the element
  1028. // whether it is already showing something rather than assuming it is not.
  1029. //
  1030. // `onLoad` used to be the only thing that could set `loaded`, and this
  1031. // effect reset it to false unconditionally. That is right when the URL
  1032. // really changes, but it also runs on mount — and the two are not the same
  1033. // situation (#2826). The URL is cache-busted on the print *name*, which is
  1034. // constant for the duration of a print, so navigating away from the
  1035. // printers page and back re-mounts with a byte-identical src that the
  1036. // browser serves from its in-memory cache. The `load` event for a cache hit
  1037. // and React's passive-effect flush are both plain tasks with no ordering
  1038. // between them, so when `load` won, this effect ran afterwards and undid
  1039. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  1040. // sat there until a full reload. Nothing recovered it, because the URL
  1041. // never changes again during the print and so this effect never re-runs.
  1042. //
  1043. // Being a race, it reproduced every time for #2826's reporter and not at
  1044. // all here, which is also why the network panel showed no request: there
  1045. // was no request to show.
  1046. //
  1047. // Asking `complete && naturalWidth > 0` settles it without needing to know
  1048. // which of the two ran first. It is also correct for the case the reporter
  1049. // proposed (a `load` that fires before React's handler is live), so the
  1050. // fix stands whichever mechanism is really at work.
  1051. useEffect(() => {
  1052. setError(false);
  1053. const el = imgRef.current;
  1054. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  1055. }, [cacheBustedUrl]);
  1056. return (
  1057. <>
  1058. <div
  1059. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  1060. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  1061. >
  1062. {cacheBustedUrl && !error ? (
  1063. <>
  1064. <img
  1065. ref={imgRef}
  1066. src={cacheBustedUrl}
  1067. alt={t('printers.printPreview')}
  1068. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  1069. onLoad={() => setLoaded(true)}
  1070. onError={() => setError(true)}
  1071. />
  1072. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  1073. </>
  1074. ) : (
  1075. <Box className="w-8 h-8 text-bambu-gray" />
  1076. )}
  1077. </div>
  1078. {/* Cover Image Overlay */}
  1079. {showOverlay && cacheBustedUrl && (
  1080. <div
  1081. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  1082. onClick={() => setShowOverlay(false)}
  1083. >
  1084. <div className="relative max-w-2xl max-h-full">
  1085. <img
  1086. src={cacheBustedUrl}
  1087. alt={t('printers.printPreview')}
  1088. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  1089. />
  1090. {printName && (
  1091. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  1092. )}
  1093. </div>
  1094. </div>
  1095. )}
  1096. </>
  1097. );
  1098. }
  1099. interface PrinterMaintenanceInfo {
  1100. due_count: number;
  1101. warning_count: number;
  1102. total_print_hours: number;
  1103. }
  1104. // Status summary bar component - uses queryClient to read cached statuses
  1105. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  1106. const { t } = useTranslation();
  1107. const queryClient = useQueryClient();
  1108. // Subscribe to query cache changes to re-render when status updates
  1109. // Throttled to prevent rapid re-renders from causing tab crashes
  1110. const [cacheTick, setCacheTick] = useState(0);
  1111. useEffect(() => {
  1112. let pending = false;
  1113. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  1114. if (!pending) {
  1115. pending = true;
  1116. requestAnimationFrame(() => {
  1117. setCacheTick(t => t + 1);
  1118. pending = false;
  1119. });
  1120. }
  1121. });
  1122. return () => unsubscribe();
  1123. }, [queryClient]);
  1124. const { counts, nextFinish } = useMemo(() => {
  1125. let printing = 0;
  1126. let paused = 0;
  1127. let finished = 0;
  1128. let idle = 0;
  1129. let offline = 0;
  1130. let loading = 0;
  1131. let error = 0;
  1132. let nextPrinterName: string | null = null;
  1133. let nextRemainingMin: number | null = null;
  1134. let nextProgress: number = 0;
  1135. printers?.forEach((printer) => {
  1136. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1137. if (status === undefined) {
  1138. // Status not yet loaded - don't count as offline yet
  1139. loading++;
  1140. } else if (!status.connected) {
  1141. offline++;
  1142. } else {
  1143. // Count printers with active HMS errors as problems
  1144. const knownHmsCount =
  1145. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1146. if (knownHmsCount > 0) {
  1147. error++;
  1148. }
  1149. switch (status.state) {
  1150. case 'RUNNING':
  1151. printing++;
  1152. if (status.remaining_time != null && status.remaining_time > 0) {
  1153. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1154. nextRemainingMin = status.remaining_time;
  1155. nextPrinterName = printer.name;
  1156. nextProgress = status.progress || 0;
  1157. }
  1158. }
  1159. break;
  1160. case 'PAUSE':
  1161. paused++;
  1162. break;
  1163. case 'FINISH':
  1164. finished++;
  1165. break;
  1166. case 'FAILED':
  1167. // FAILED is the printer's terminal gcode_state after a print stops —
  1168. // including user cancellations, where there's no actual fault. Only
  1169. // count it as a "problem" when an HMS error is also active; otherwise
  1170. // it's just a print that ended unsuccessfully and the plate needs
  1171. // clearing (same as FINISH from the operator's perspective).
  1172. if (knownHmsCount > 0) {
  1173. // Already counted above
  1174. } else {
  1175. finished++;
  1176. }
  1177. break;
  1178. default:
  1179. idle++;
  1180. break;
  1181. }
  1182. }
  1183. });
  1184. return {
  1185. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1186. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1187. };
  1188. // eslint-disable-next-line react-hooks/exhaustive-deps
  1189. }, [printers, queryClient, cacheTick]);
  1190. if (!printers?.length) return null;
  1191. const badges: { count: number; dot: string; label: string }[] = [
  1192. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1193. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1194. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1195. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1196. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1197. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1198. ];
  1199. return (
  1200. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1201. {badges.map(({ count, dot, label }) => count > 0 && (
  1202. <div key={label} className="flex items-center gap-1.5">
  1203. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1204. <span className="text-bambu-gray">
  1205. <span className="text-white font-medium">{count}</span> {label}
  1206. </span>
  1207. </div>
  1208. ))}
  1209. {nextFinish && (
  1210. <>
  1211. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1212. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1213. <div className="flex items-center gap-2">
  1214. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1215. <span className="text-white font-medium">{nextFinish.name}</span>
  1216. </div>
  1217. <div className="flex items-center gap-2 w-full sm:w-auto">
  1218. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1219. <div
  1220. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1221. style={{ width: `${nextFinish.progress}%` }}
  1222. />
  1223. </div>
  1224. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1225. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1226. </div>
  1227. </div>
  1228. </>
  1229. )}
  1230. </div>
  1231. );
  1232. }
  1233. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1234. type ViewMode = 'expanded' | 'compact';
  1235. type ToolbarDropdownOption<T extends string> = {
  1236. value: T;
  1237. label: string;
  1238. };
  1239. function ToolbarDropdown<T extends string>({
  1240. value,
  1241. options,
  1242. onChange,
  1243. fullWidth = false,
  1244. }: {
  1245. value: T;
  1246. options: ToolbarDropdownOption<T>[];
  1247. onChange: (value: T) => void;
  1248. fullWidth?: boolean;
  1249. }) {
  1250. const [isOpen, setIsOpen] = useState(false);
  1251. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1252. return (
  1253. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1254. <button
  1255. type="button"
  1256. onClick={() => setIsOpen(open => !open)}
  1257. 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'}`}
  1258. >
  1259. <span className="truncate">{selectedOption?.label}</span>
  1260. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1261. </button>
  1262. {isOpen && (
  1263. <>
  1264. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1265. <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">
  1266. {options.map(option => (
  1267. <button
  1268. key={option.value}
  1269. type="button"
  1270. onClick={() => {
  1271. onChange(option.value);
  1272. setIsOpen(false);
  1273. }}
  1274. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1275. option.value === value ? 'text-bambu-green' : 'text-white'
  1276. }`}
  1277. >
  1278. {option.label}
  1279. </button>
  1280. ))}
  1281. </div>
  1282. </>
  1283. )}
  1284. </div>
  1285. );
  1286. }
  1287. function ToolbarMenu({
  1288. label,
  1289. icon,
  1290. children,
  1291. }: {
  1292. label: string;
  1293. icon: React.ReactNode;
  1294. children: React.ReactNode;
  1295. }) {
  1296. const [isOpen, setIsOpen] = useState(false);
  1297. return (
  1298. <div className="relative">
  1299. <button
  1300. type="button"
  1301. onClick={() => setIsOpen(open => !open)}
  1302. 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"
  1303. aria-label={label}
  1304. title={label}
  1305. >
  1306. {icon}
  1307. </button>
  1308. {isOpen && (
  1309. <>
  1310. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1311. <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">
  1312. {children}
  1313. </div>
  1314. </>
  1315. )}
  1316. </div>
  1317. );
  1318. }
  1319. function IndicatorControlPopover({
  1320. title,
  1321. options = [],
  1322. unit,
  1323. customMin,
  1324. customMax,
  1325. customStep = 1,
  1326. widthClass = 'w-[240px]',
  1327. popoverWidth = 240,
  1328. popoverHeight = 280,
  1329. isPending,
  1330. onClose,
  1331. onSubmit,
  1332. children,
  1333. }: {
  1334. title: string;
  1335. options?: Array<{ label: string; value: number }>;
  1336. unit?: string;
  1337. customMin?: number;
  1338. customMax?: number;
  1339. customStep?: number;
  1340. widthClass?: string;
  1341. popoverWidth?: number;
  1342. popoverHeight?: number;
  1343. isPending?: boolean;
  1344. onClose: () => void;
  1345. onSubmit?: (value: number) => void;
  1346. children?: React.ReactNode;
  1347. }) {
  1348. const anchorRef = useRef<HTMLSpanElement>(null);
  1349. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1350. const [customValue, setCustomValue] = useState('');
  1351. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1352. // can position via fixed coords. Portaling to document.body escapes
  1353. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1354. // own contexts and would otherwise cover the popover even at z-[60].
  1355. useLayoutEffect(() => {
  1356. const trigger = anchorRef.current?.parentElement;
  1357. if (!trigger) return;
  1358. const measure = () => {
  1359. const rect = trigger.getBoundingClientRect();
  1360. setCoords(computePopoverPosition({
  1361. triggerRect: rect,
  1362. popoverWidth,
  1363. estimatedHeight: popoverHeight,
  1364. horizontalAlign: 'center',
  1365. }));
  1366. };
  1367. measure();
  1368. window.addEventListener('resize', measure);
  1369. window.addEventListener('scroll', measure, true);
  1370. return () => {
  1371. window.removeEventListener('resize', measure);
  1372. window.removeEventListener('scroll', measure, true);
  1373. };
  1374. }, [popoverWidth, popoverHeight]);
  1375. const showCustomInput = unit !== undefined;
  1376. const submitCustom = () => {
  1377. const value = Number(customValue);
  1378. if (!Number.isFinite(value)) return;
  1379. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1380. onSubmit?.(Math.round(bounded));
  1381. };
  1382. return (
  1383. <>
  1384. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1385. {createPortal(
  1386. <>
  1387. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1388. <div
  1389. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1390. style={{
  1391. top: coords?.top ?? -9999,
  1392. left: coords?.left ?? -9999,
  1393. visibility: coords ? 'visible' : 'hidden',
  1394. }}
  1395. onClick={e => e.stopPropagation()}
  1396. >
  1397. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1398. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1399. {options.length > 0 && (
  1400. <div className="px-3 py-2.5">
  1401. <div className="grid grid-cols-2 gap-1.5">
  1402. {options.map(option => (
  1403. <button
  1404. key={`${option.label}-${option.value}`}
  1405. type="button"
  1406. disabled={isPending}
  1407. onClick={() => onSubmit?.(option.value)}
  1408. 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"
  1409. >
  1410. {option.label}
  1411. </button>
  1412. ))}
  1413. </div>
  1414. </div>
  1415. )}
  1416. {children}
  1417. {showCustomInput && (
  1418. <>
  1419. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1420. <form
  1421. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1422. onSubmit={(e) => {
  1423. e.preventDefault();
  1424. submitCustom();
  1425. }}
  1426. >
  1427. <input
  1428. type="number"
  1429. min={customMin}
  1430. max={customMax}
  1431. step={customStep}
  1432. value={customValue}
  1433. onChange={e => setCustomValue(e.target.value)}
  1434. placeholder="Custom"
  1435. 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"
  1436. />
  1437. <button
  1438. type="submit"
  1439. disabled={isPending || customValue.trim() === ''}
  1440. 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"
  1441. >
  1442. Set
  1443. </button>
  1444. </form>
  1445. </>
  1446. )}
  1447. </div>
  1448. </>,
  1449. document.body
  1450. )}
  1451. </>
  1452. );
  1453. }
  1454. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1455. function NozzleTemperatureControlBox({
  1456. label,
  1457. current,
  1458. target,
  1459. isActive,
  1460. isPending,
  1461. onSubmit,
  1462. options = NOZZLE_TEMPERATURE_OPTIONS,
  1463. }: {
  1464. label: string;
  1465. current?: number;
  1466. target?: number;
  1467. isActive: boolean;
  1468. isPending?: boolean;
  1469. onSubmit: (value: number) => void;
  1470. options?: Array<{ label: string; value: number }>;
  1471. }) {
  1472. const [customValue, setCustomValue] = useState('');
  1473. const submitCustom = () => {
  1474. const value = Number(customValue);
  1475. if (!Number.isFinite(value)) return;
  1476. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1477. };
  1478. return (
  1479. <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'}`}>
  1480. <div className="mb-1.5 flex items-center justify-between gap-2">
  1481. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1482. <span className="text-[10px] text-bambu-gray">
  1483. {Math.round(current ?? 0)}°C
  1484. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1485. </span>
  1486. </div>
  1487. <div className="grid grid-cols-2 gap-1">
  1488. {options.map(option => (
  1489. <button
  1490. key={`${label}-${option.value}`}
  1491. type="button"
  1492. disabled={isPending}
  1493. onClick={() => onSubmit(option.value)}
  1494. 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"
  1495. >
  1496. {option.label}
  1497. </button>
  1498. ))}
  1499. </div>
  1500. <form
  1501. className="mt-1.5 flex gap-1"
  1502. onSubmit={(e) => {
  1503. e.preventDefault();
  1504. submitCustom();
  1505. }}
  1506. >
  1507. <input
  1508. type="number"
  1509. min={0}
  1510. max={320}
  1511. step={1}
  1512. value={customValue}
  1513. onChange={e => setCustomValue(e.target.value)}
  1514. placeholder="Custom"
  1515. 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"
  1516. />
  1517. <button
  1518. type="submit"
  1519. disabled={isPending || customValue.trim() === ''}
  1520. 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"
  1521. >
  1522. Set
  1523. </button>
  1524. </form>
  1525. </div>
  1526. );
  1527. }
  1528. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1529. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1530. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1531. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1532. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1533. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1534. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1535. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1536. };
  1537. /** Classify a printer into one of the UI status buckets. */
  1538. function classifyPrinterStatus(
  1539. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1540. ): PrinterState {
  1541. if (!status?.connected) return 'offline';
  1542. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1543. if (hmsErrors.length > 0) return 'error';
  1544. switch (status.state) {
  1545. case 'RUNNING': return 'printing';
  1546. case 'PAUSE': return 'paused';
  1547. case 'FINISH': return 'finished';
  1548. // FAILED without an active HMS error is the printer's terminal state after
  1549. // any unsuccessful end — including user-cancellations. Treat the same as
  1550. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1551. // HMS code is actually attached (handled by the early-return above).
  1552. case 'FAILED': return 'finished';
  1553. default: return 'idle';
  1554. }
  1555. }
  1556. /**
  1557. * Get human-readable status display text for a printer.
  1558. * Uses stg_cur_name for detailed calibration/preparation stages,
  1559. * otherwise formats the gcode_state nicely.
  1560. */
  1561. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1562. // If we have a specific stage name (calibration, heating, etc.), use it
  1563. if (stg_cur_name) {
  1564. return stg_cur_name;
  1565. }
  1566. // Format the gcode_state nicely
  1567. switch (state) {
  1568. case 'RUNNING':
  1569. return 'Printing';
  1570. case 'PAUSE':
  1571. return 'Paused';
  1572. case 'FINISH':
  1573. return 'Finished';
  1574. case 'FAILED':
  1575. return 'Failed';
  1576. case 'IDLE':
  1577. return 'Idle';
  1578. default:
  1579. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1580. }
  1581. }
  1582. // Bambu models that ship with an enclosure chamber fan (firmware field
  1583. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1584. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1585. // widget is hidden in fanItems instead of rendered greyed-out.
  1586. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1587. 'X1C',
  1588. 'X1',
  1589. 'X1E',
  1590. 'X2D',
  1591. 'P1S',
  1592. 'P2S',
  1593. 'H2D',
  1594. 'H2D Pro',
  1595. 'H2C',
  1596. 'H2S',
  1597. ]);
  1598. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1599. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1600. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1601. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1602. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1603. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1604. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1605. 'P2S',
  1606. 'X2D',
  1607. ]);
  1608. // Map SSDP model codes to display names
  1609. function mapModelCode(ssdpModel: string | null): string {
  1610. if (!ssdpModel) return '';
  1611. const modelMap: Record<string, string> = {
  1612. // H2 Series
  1613. 'O1D': 'H2D',
  1614. 'O1E': 'H2D Pro',
  1615. 'O2D': 'H2D Pro',
  1616. 'O1C': 'H2C',
  1617. 'O1C2': 'H2C',
  1618. 'O1S': 'H2S',
  1619. // X1 Series
  1620. 'BL-P001': 'X1C',
  1621. 'BL-P002': 'X1',
  1622. 'BL-P003': 'X1E',
  1623. // X2 Series
  1624. 'N6': 'X2D',
  1625. // A2 Series
  1626. 'N9': 'A2L',
  1627. // P Series
  1628. 'C11': 'P1S',
  1629. 'C12': 'P1P',
  1630. 'C13': 'P2S',
  1631. // A1 Series
  1632. 'N2S': 'A1',
  1633. 'N1': 'A1 Mini',
  1634. // Direct matches
  1635. 'X1C': 'X1C',
  1636. 'X1': 'X1',
  1637. 'X1E': 'X1E',
  1638. 'X2D': 'X2D',
  1639. 'P1S': 'P1S',
  1640. 'P1P': 'P1P',
  1641. 'P2S': 'P2S',
  1642. 'A1': 'A1',
  1643. 'A1 Mini': 'A1 Mini',
  1644. 'A2L': 'A2L',
  1645. 'H2D': 'H2D',
  1646. 'H2D Pro': 'H2D Pro',
  1647. 'H2C': 'H2C',
  1648. 'H2S': 'H2S',
  1649. };
  1650. return modelMap[ssdpModel] || ssdpModel;
  1651. }
  1652. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1653. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1654. // • User-defined friendly name (editable, protected by printers:update)
  1655. // • AMS serial number
  1656. // • AMS firmware version
  1657. export function AmsNameHoverCard({
  1658. ams,
  1659. printerId,
  1660. label,
  1661. amsLabels,
  1662. canEdit,
  1663. onSaved,
  1664. children,
  1665. }: {
  1666. ams: import('../api/client').AMSUnit;
  1667. printerId: number;
  1668. label: string; // auto-generated label, e.g. "AMS-A"
  1669. amsLabels?: Record<number, string>;
  1670. canEdit: boolean;
  1671. onSaved: () => void;
  1672. children: React.ReactNode;
  1673. }) {
  1674. const { t } = useTranslation();
  1675. const [isVisible, setIsVisible] = useState(false);
  1676. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1677. const [editValue, setEditValue] = useState('');
  1678. const [isSaving, setIsSaving] = useState(false);
  1679. const [saveError, setSaveError] = useState<string | null>(null);
  1680. const [isInputFocused, setIsInputFocused] = useState(false);
  1681. const triggerRef = useRef<HTMLDivElement>(null);
  1682. const cardRef = useRef<HTMLDivElement>(null);
  1683. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1684. useEffect(() => {
  1685. if (isVisible) {
  1686. setEditValue(amsLabels?.[ams.id] ?? '');
  1687. setSaveError(null);
  1688. requestAnimationFrame(() => {
  1689. if (triggerRef.current && cardRef.current) {
  1690. const rect = triggerRef.current.getBoundingClientRect();
  1691. const spaceAbove = rect.top - 56;
  1692. const spaceBelow = window.innerHeight - rect.bottom;
  1693. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1694. }
  1695. });
  1696. }
  1697. }, [isVisible, amsLabels, ams.id]);
  1698. const handleMouseEnter = () => {
  1699. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1700. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1701. };
  1702. const handleMouseLeave = () => {
  1703. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1704. if (!isInputFocused) {
  1705. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1706. }
  1707. };
  1708. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1709. const handleSave = async () => {
  1710. if (!canEdit) return;
  1711. setIsSaving(true);
  1712. setSaveError(null);
  1713. try {
  1714. const trimmed = editValue.trim();
  1715. if (trimmed) {
  1716. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1717. } else {
  1718. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1719. }
  1720. onSaved();
  1721. setIsVisible(false);
  1722. } catch (err) {
  1723. setSaveError(err instanceof Error ? err.message : String(err));
  1724. } finally {
  1725. setIsSaving(false);
  1726. }
  1727. };
  1728. const handleClear = async () => {
  1729. if (!canEdit) return;
  1730. setIsSaving(true);
  1731. setSaveError(null);
  1732. try {
  1733. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1734. onSaved();
  1735. setIsVisible(false);
  1736. } catch (err) {
  1737. setSaveError(err instanceof Error ? err.message : String(err));
  1738. } finally {
  1739. setIsSaving(false);
  1740. }
  1741. };
  1742. return (
  1743. <div
  1744. ref={triggerRef}
  1745. className="relative inline-block"
  1746. onMouseEnter={handleMouseEnter}
  1747. onMouseLeave={handleMouseLeave}
  1748. >
  1749. {children}
  1750. {isVisible && (
  1751. <div
  1752. ref={cardRef}
  1753. className={`
  1754. absolute left-0 z-50
  1755. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1756. animate-in fade-in-0 zoom-in-95 duration-150
  1757. `}
  1758. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1759. onMouseEnter={handleMouseEnter}
  1760. onMouseLeave={handleMouseLeave}
  1761. >
  1762. <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">
  1763. {/* AMS auto-label */}
  1764. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1765. {/* Serial number */}
  1766. <div className="flex items-center justify-between gap-2">
  1767. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1768. {t('printers.amsPopup.serialNumber')}
  1769. </span>
  1770. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1771. </div>
  1772. {/* Firmware version */}
  1773. <div className="flex items-center justify-between gap-2">
  1774. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1775. {t('printers.amsPopup.firmwareVersion')}
  1776. </span>
  1777. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1778. </div>
  1779. {/* Friendly name editor */}
  1780. <div className="space-y-1">
  1781. <div className="flex items-center gap-2">
  1782. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1783. {t('printers.amsPopup.friendlyName')}
  1784. </span>
  1785. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1786. </div>
  1787. <input
  1788. type="text"
  1789. value={editValue}
  1790. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1791. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1792. onFocus={() => setIsInputFocused(true)}
  1793. onBlur={() => {
  1794. setIsInputFocused(false);
  1795. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1796. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1797. }}
  1798. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1799. disabled={!canEdit}
  1800. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1801. 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"
  1802. maxLength={100}
  1803. />
  1804. {canEdit && (
  1805. <div className="space-y-1">
  1806. {saveError && (
  1807. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1808. )}
  1809. <div className="flex gap-1 justify-end">
  1810. <button
  1811. onClick={handleSave}
  1812. disabled={isSaving}
  1813. 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"
  1814. >
  1815. {t('printers.amsPopup.save')}
  1816. </button>
  1817. {amsLabels?.[ams.id] && (
  1818. <button
  1819. onClick={handleClear}
  1820. disabled={isSaving}
  1821. 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"
  1822. >
  1823. {t('printers.amsPopup.clear')}
  1824. </button>
  1825. )}
  1826. </div>
  1827. </div>
  1828. )}
  1829. </div>
  1830. </div>
  1831. </div>
  1832. )}
  1833. </div>
  1834. );
  1835. }
  1836. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1837. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1838. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1839. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1840. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1841. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1842. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1843. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1844. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1845. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1846. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1847. };
  1848. // How much the printer card's body type and icons grow at each card size
  1849. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1850. // 1.0 and an existing install looks identical until the user picks L or XL --
  1851. // the same control the request asked to have this follow.
  1852. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1853. // The scaled sizes, handed to the card subtree as custom properties. Every
  1854. // converted class names its old fixed value as the fallback, so anything that
  1855. // renders outside a card root -- the portalled temperature popover -- keeps
  1856. // exactly the size it has today.
  1857. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1858. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1859. // Rounded to a tenth so the values stay readable in devtools.
  1860. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1861. return {
  1862. '--pc-t8': px(8),
  1863. '--pc-t9': px(9),
  1864. '--pc-t10': px(10),
  1865. '--pc-t11': px(11),
  1866. '--pc-i2': px(8),
  1867. '--pc-i25': px(10),
  1868. '--pc-i3': px(12),
  1869. '--pc-i35': px(14),
  1870. '--pc-i4': px(16),
  1871. '--pc-i5': px(20),
  1872. '--pc-i7': px(28),
  1873. } as React.CSSProperties;
  1874. }
  1875. function ScheduledDryingBanner({ printerId, dryingActive, timeFormat }: { printerId: number; dryingActive: boolean; timeFormat: 'system' | '12h' | '24h' }) {
  1876. const { t } = useTranslation();
  1877. const queryClient = useQueryClient();
  1878. const { showToast } = useToast();
  1879. // One fleet-wide query shared by every card, not one per card: the list is
  1880. // nearly always empty and a 20-printer fleet would otherwise make 20
  1881. // requests every 30s. React Query dedupes on the key.
  1882. const { data: scheduled = [] } = useQuery({
  1883. queryKey: SCHEDULED_DRYINGS_KEY,
  1884. queryFn: () => api.listScheduledDryings(),
  1885. refetchInterval: 30_000,
  1886. });
  1887. // The live AMS status reports a starting cycle well before the next poll;
  1888. // refetch so a just-dispatched schedule doesn't linger as pending.
  1889. useEffect(() => {
  1890. if (dryingActive) {
  1891. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  1892. }
  1893. }, [dryingActive, queryClient]);
  1894. const cancelMutation = useMutation({
  1895. mutationFn: (id: number) => api.cancelScheduledDrying(id),
  1896. onSuccess: () => queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY }),
  1897. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  1898. });
  1899. // Failed rows are shown too: dispatch is the only place a run can fail (too
  1900. // old firmware on a printer that was offline at schedule time), and without
  1901. // this the run just vanishes with only the backend log saying why.
  1902. const rows = scheduled.filter(s => s.printer_id === printerId && (s.status === 'pending' || s.status === 'failed'));
  1903. if (rows.length === 0) return null;
  1904. return (
  1905. <div className="mt-2 space-y-1">
  1906. {rows.map(s => {
  1907. const failed = s.status === 'failed';
  1908. const reasonKey = waitingReasonKey(s.waiting_reason);
  1909. return (
  1910. <div
  1911. key={s.id}
  1912. data-testid={failed ? 'scheduled-drying-failed' : 'scheduled-drying-pending'}
  1913. className={`flex items-center justify-between px-2 py-1 rounded-lg text-[length:var(--pc-t11,11px)] ${
  1914. failed ? 'bg-red-500/10 border border-red-500/30' : 'bg-amber-500/10 border border-amber-500/30'
  1915. }`}
  1916. >
  1917. <span className={failed ? 'text-red-700 dark:text-red-400' : 'text-amber-700 dark:text-amber-400'}>
  1918. {failed ? (
  1919. t('printers.drying.scheduleFailedReason', {
  1920. reason: s.error_message || t('printers.drying.scheduleFailedUnknown'),
  1921. })
  1922. ) : (
  1923. <>
  1924. {s.start_after
  1925. ? t('printers.drying.scheduledFor', { time: formatDateTime(s.start_after, timeFormat) })
  1926. : t('printers.drying.scheduledAsap')}
  1927. {reasonKey && <span className="ml-1 opacity-80">{t(reasonKey)}</span>}
  1928. </>
  1929. )}
  1930. </span>
  1931. <button
  1932. onClick={() => cancelMutation.mutate(s.id)}
  1933. disabled={cancelMutation.isPending}
  1934. title={failed ? t('printers.drying.dismissFailed') : t('printers.drying.cancelScheduled')}
  1935. className="text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
  1936. >
  1937. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  1938. </button>
  1939. </div>
  1940. );
  1941. })}
  1942. </div>
  1943. );
  1944. }
  1945. function PrinterCard({
  1946. printer,
  1947. hideIfDisconnected,
  1948. maintenanceInfo,
  1949. viewMode = 'expanded',
  1950. cardSize = 2,
  1951. amsThresholds,
  1952. spoolmanEnabled = false,
  1953. linkedSpools,
  1954. spoolmanUrl,
  1955. spoolmanSyncMode,
  1956. onGetAssignment,
  1957. onUnassignSpool,
  1958. spoolmanSpools,
  1959. spoolmanSlotAssignments,
  1960. spoolmanLoading = false,
  1961. onUnassignSpoolmanSpool,
  1962. timeFormat = 'system',
  1963. cameraViewMode = 'window',
  1964. onOpenEmbeddedCamera,
  1965. onSelectCameraViewMode,
  1966. checkPrinterFirmware = true,
  1967. dryingPresets = DRYING_PRESETS,
  1968. requirePlateClear = false,
  1969. selectionMode = false,
  1970. isSelected = false,
  1971. onToggleSelect,
  1972. onOpenCompactCard,
  1973. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1974. bedTempPresets = BED_TEMP_DEFAULTS,
  1975. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1976. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1977. aiDetectionEnabled = false,
  1978. aiDetection,
  1979. aiLastError = null,
  1980. }: {
  1981. printer: Printer;
  1982. hideIfDisconnected?: boolean;
  1983. maintenanceInfo?: PrinterMaintenanceInfo;
  1984. viewMode?: ViewMode;
  1985. cardSize?: number;
  1986. amsThresholds?: {
  1987. humidityGood: number;
  1988. humidityFair: number;
  1989. tempGood: number;
  1990. tempFair: number;
  1991. };
  1992. spoolmanEnabled?: boolean;
  1993. hasUnlinkedSpools?: boolean;
  1994. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1995. spoolmanUrl?: string | null;
  1996. spoolmanSyncMode?: string | null;
  1997. spoolAssignments?: SpoolAssignment[];
  1998. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1999. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  2000. spoolmanSpools?: InventorySpool[];
  2001. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  2002. spoolmanLoading?: boolean;
  2003. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  2004. timeFormat?: 'system' | '12h' | '24h';
  2005. cameraViewMode?: CameraViewMode;
  2006. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  2007. onSelectCameraViewMode?: (mode: CameraViewMode) => void;
  2008. checkPrinterFirmware?: boolean;
  2009. dryingPresets?: Record<string, DryingPreset>;
  2010. requirePlateClear?: boolean;
  2011. selectionMode?: boolean;
  2012. isSelected?: boolean;
  2013. onToggleSelect?: (id: number) => void;
  2014. onOpenCompactCard?: (id: number) => void;
  2015. nozzleTempPresets?: readonly [number, number, number];
  2016. bedTempPresets?: readonly [number, number, number];
  2017. chamberTempPresets?: readonly [number, number, number];
  2018. fanSpeedPresets?: readonly [number, number, number];
  2019. aiDetectionEnabled?: boolean;
  2020. aiDetection?: { class: string; frame_count: number; score: number };
  2021. aiLastError?: string | null;
  2022. }) {
  2023. const { t } = useTranslation();
  2024. const queryClient = useQueryClient();
  2025. const navigate = useNavigate();
  2026. const { showToast } = useToast();
  2027. const { hasPermission } = useAuth();
  2028. const [showMenu, setShowMenu] = useState(false);
  2029. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  2030. const [deleteArchives, setDeleteArchives] = useState(true);
  2031. const [showEditModal, setShowEditModal] = useState(false);
  2032. const [showFileManager, setShowFileManager] = useState(false);
  2033. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  2034. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  2035. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  2036. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  2037. const [showHMSModal, setShowHMSModal] = useState(false);
  2038. // #1546: AI failure detection modal — opens from the AI badge.
  2039. const [showAiModal, setShowAiModal] = useState(false);
  2040. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  2041. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  2042. // External spool visibility (#1782) — browser-local, per printer. Read once
  2043. // per card; the toggle that writes it is the only thing that changes it.
  2044. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  2045. isExternalSpoolHidden(printer.id),
  2046. );
  2047. const toggleExternalSpool = useCallback(() => {
  2048. setExternalSpoolHidden((prev) => {
  2049. const next = !prev;
  2050. persistExternalSpoolHidden(printer.id, next);
  2051. return next;
  2052. });
  2053. }, [printer.id]);
  2054. const [showStopConfirm, setShowStopConfirm] = useState(false);
  2055. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  2056. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  2057. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  2058. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  2059. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  2060. const [bedJogStep, setBedJogStep] = useState<number>(10);
  2061. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  2062. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  2063. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  2064. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  2065. const [showDiagnostic, setShowDiagnostic] = useState(false);
  2066. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  2067. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  2068. // AMS drying popover state: which AMS unit has the popover open
  2069. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  2070. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  2071. const [dryingFilament, setDryingFilament] = useState('PLA');
  2072. const [dryingTemp, setDryingTemp] = useState(50);
  2073. const [dryingDuration, setDryingDuration] = useState(4);
  2074. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  2075. // Drying start mode (#2638): 'now' starts immediately; 'delay' and 'at_time'
  2076. // go through scheduleDryingMutation.
  2077. const [dryingStartMode, setDryingStartMode] = useState<DryingStartMode>('now');
  2078. const [dryingDelayMinutes, setDryingDelayMinutes] = useState(120);
  2079. const [dryingStartAt, setDryingStartAt] = useState('');
  2080. const [dryingPopoverPos, setDryingPopoverPos] = useState<PopoverPosition | null>(null);
  2081. const [dryingPopoverAnchor, setDryingPopoverAnchor] = useState<HTMLElement | null>(null);
  2082. // Reset every field the popover owns, including the start mode. Leaving the
  2083. // mode alone let an "At time" timestamp from an earlier schedule persist into
  2084. // the next open, by then in the past, and the POST rejected it.
  2085. const openDryingPopover = useCallback((ams: AMSUnit, trigger: HTMLElement) => {
  2086. const firstTray = ams.tray.find(t => t.tray_type);
  2087. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  2088. // Only reachable if a custom preset set dropped PLA itself.
  2089. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  2090. const moduleType = ams.module_type as 'n3f' | 'n3s';
  2091. setDryingFilament(filType);
  2092. setDryingTemp(preset[moduleType] || preset.n3f);
  2093. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  2094. setDryingRotateTray(false);
  2095. setDryingStartMode('now');
  2096. setDryingDelayMinutes(120);
  2097. setDryingStartAt('');
  2098. setDryingPopoverModuleType(ams.module_type);
  2099. setDryingPopoverAmsId(ams.id);
  2100. setDryingPopoverAnchor(trigger);
  2101. }, [dryingPresets]);
  2102. // Re-measure on resize/scroll so the popover and its arrow track the
  2103. // flame button, like IndicatorControlPopover.
  2104. useLayoutEffect(() => {
  2105. if (dryingPopoverAmsId === null || !dryingPopoverAnchor) return;
  2106. const measure = () => {
  2107. setDryingPopoverPos(computePopoverPosition({
  2108. triggerRect: dryingPopoverAnchor.getBoundingClientRect(),
  2109. popoverWidth: DRYING_POPOVER_WIDTH,
  2110. estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT,
  2111. horizontalAlign: 'center',
  2112. }));
  2113. };
  2114. measure();
  2115. window.addEventListener('resize', measure);
  2116. window.addEventListener('scroll', measure, true);
  2117. return () => {
  2118. window.removeEventListener('resize', measure);
  2119. window.removeEventListener('scroll', measure, true);
  2120. };
  2121. }, [dryingPopoverAmsId, dryingPopoverAnchor]);
  2122. const dryingAtTimeInputRef = useRef<HTMLInputElement | null>(null);
  2123. // Whether the click hitting the backdrop is the one that dismissed the
  2124. // native datetime picker (see the backdrop's onMouseDown).
  2125. const dryingBackdropSkipCloseRef = useRef(false);
  2126. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  2127. // an object rather than a bare id so restarting drying on the SAME unit produces
  2128. // a new identity and rearms the timeout below.
  2129. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  2130. const [isDraggingFile, setIsDraggingFile] = useState(false);
  2131. const [isDropUploading, setIsDropUploading] = useState(false);
  2132. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  2133. // Viewport coordinates, because the camera mode menu is a `ContextMenu` at
  2134. // `position: fixed`. The button sits in the card's footer, so a menu drawn
  2135. // inside the card would have to open upward into the card body; anchored to
  2136. // the viewport it escapes the card and the grid's scroll container both.
  2137. const [cameraMenuAnchor, setCameraMenuAnchor] = useState<{ x: number; y: number } | null>(null);
  2138. const dragCounterRef = useRef(0);
  2139. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  2140. amsId: number;
  2141. amsLabel: string;
  2142. mode: 'humidity' | 'temperature';
  2143. } | null>(null);
  2144. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  2145. initialKind: HeaterSensorKind;
  2146. availableKinds: HeaterSensorKind[];
  2147. } | null>(null);
  2148. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  2149. tagUid: string;
  2150. trayUuid: string;
  2151. printerId: number;
  2152. amsId: number;
  2153. trayId: number;
  2154. } | null>(null);
  2155. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  2156. printerId: number;
  2157. amsId: number;
  2158. trayId: number;
  2159. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  2160. } | null>(null);
  2161. const [configureSlotModal, setConfigureSlotModal] = useState<{
  2162. amsId: number;
  2163. trayId: number;
  2164. trayCount: number;
  2165. trayType?: string;
  2166. trayColor?: string;
  2167. traySubBrands?: string;
  2168. trayInfoIdx?: string;
  2169. extruderId?: number;
  2170. caliIdx?: number | null;
  2171. savedPresetId?: string;
  2172. } | null>(null);
  2173. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  2174. const [plateCheckResult, setPlateCheckResult] = useState<{
  2175. is_empty: boolean;
  2176. confidence: number;
  2177. difference_percent: number;
  2178. message: string;
  2179. debug_image_url?: string;
  2180. needs_calibration: boolean;
  2181. light_warning?: boolean;
  2182. reference_count?: number;
  2183. max_references?: number;
  2184. roi?: { x: number; y: number; w: number; h: number };
  2185. } | null>(null);
  2186. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  2187. const [isCalibrating, setIsCalibrating] = useState(false);
  2188. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  2189. const [isSavingRoi, setIsSavingRoi] = useState(false);
  2190. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  2191. const { data: status } = useQuery({
  2192. queryKey: ['printerStatus', printer.id],
  2193. queryFn: () => api.getPrinterStatus(printer.id),
  2194. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  2195. });
  2196. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  2197. const { data: firmwareInfo } = useQuery({
  2198. queryKey: ['firmwareUpdate', printer.id],
  2199. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  2200. staleTime: 5 * 60 * 1000,
  2201. refetchInterval: 5 * 60 * 1000,
  2202. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  2203. });
  2204. // Collect unique tray_info_idx values for cloud filament info lookup
  2205. const trayInfoIds = useMemo(() => {
  2206. const ids = new Set<string>();
  2207. if (status?.ams) {
  2208. for (const ams of status.ams) {
  2209. for (const tray of ams.tray || []) {
  2210. if (tray.tray_info_idx) {
  2211. ids.add(tray.tray_info_idx);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. for (const vt of status?.vt_tray ?? []) {
  2217. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  2218. }
  2219. if (status?.nozzle_rack) {
  2220. for (const slot of status.nozzle_rack) {
  2221. if (slot.filament_id) {
  2222. ids.add(slot.filament_id);
  2223. }
  2224. }
  2225. }
  2226. return Array.from(ids);
  2227. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  2228. // Collect loaded filament types for queue widget filtering
  2229. const loadedFilamentTypes = useMemo(() => {
  2230. const types = new Set<string>();
  2231. if (status?.ams) {
  2232. for (const ams of status.ams) {
  2233. for (const tray of ams.tray || []) {
  2234. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  2235. }
  2236. }
  2237. }
  2238. for (const vt of status?.vt_tray ?? []) {
  2239. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  2240. }
  2241. return types;
  2242. }, [status?.ams, status?.vt_tray]);
  2243. // Collect loaded filament type+color pairs for queue widget override matching
  2244. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2245. const loadedFilaments = useMemo(() => {
  2246. const filaments = new Set<string>();
  2247. if (status?.ams) {
  2248. for (const ams of status.ams) {
  2249. for (const tray of ams.tray || []) {
  2250. if (tray.tray_type && tray.tray_color) {
  2251. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2252. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2253. }
  2254. }
  2255. }
  2256. }
  2257. for (const vt of status?.vt_tray ?? []) {
  2258. if (vt.tray_type && vt.tray_color) {
  2259. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2260. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2261. }
  2262. }
  2263. return filaments;
  2264. }, [status?.ams, status?.vt_tray]);
  2265. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2266. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2267. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2268. const loadedVariants = useMemo(() => {
  2269. const variants = new Set<string>();
  2270. if (status?.ams) {
  2271. for (const ams of status.ams) {
  2272. for (const tray of ams.tray || []) {
  2273. if (tray.tray_type && tray.tray_color) {
  2274. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2275. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2276. }
  2277. }
  2278. }
  2279. }
  2280. for (const vt of status?.vt_tray ?? []) {
  2281. if (vt.tray_type && vt.tray_color) {
  2282. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2283. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2284. }
  2285. }
  2286. return variants;
  2287. }, [status?.ams, status?.vt_tray]);
  2288. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2289. const { data: filamentInfo } = useQuery({
  2290. queryKey: ['filamentInfo', trayInfoIds],
  2291. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2292. enabled: trayInfoIds.length > 0,
  2293. staleTime: 5 * 60 * 1000, // 5 minutes
  2294. });
  2295. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2296. const { data: slotPresets } = useQuery({
  2297. queryKey: ['slotPresets', printer.id],
  2298. queryFn: () => api.getSlotPresets(printer.id),
  2299. staleTime: 2 * 60 * 1000, // 2 minutes
  2300. });
  2301. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2302. // Only queried when there's a running print backed by an archive; shared
  2303. // React Query cache with the Queue / Archives pages keeps it cheap.
  2304. const activeArchiveId =
  2305. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2306. const { data: activeArchivePlates } = useQuery({
  2307. queryKey: ['archive-plates', activeArchiveId],
  2308. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2309. enabled: activeArchiveId != null,
  2310. staleTime: 5 * 60 * 1000,
  2311. });
  2312. const activePlateLabel = (() => {
  2313. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2314. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2315. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2316. })();
  2317. // Fetch user-defined AMS friendly names from the database
  2318. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2319. queryKey: ['amsLabels', printer.id],
  2320. queryFn: () => api.getAmsLabels(printer.id),
  2321. staleTime: 5 * 60 * 1000, // 5 minutes
  2322. });
  2323. // Cache WiFi signal to prevent it disappearing on updates
  2324. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2325. useEffect(() => {
  2326. if (status?.wifi_signal != null) {
  2327. setCachedWifiSignal(status.wifi_signal);
  2328. }
  2329. }, [status?.wifi_signal]);
  2330. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2331. // Cache connected state to prevent flicker when status briefly becomes undefined
  2332. const cachedConnected = useRef<boolean | undefined>(undefined);
  2333. useEffect(() => {
  2334. if (status?.connected !== undefined) {
  2335. cachedConnected.current = status.connected;
  2336. }
  2337. }, [status?.connected]);
  2338. const isConnected = status?.connected ?? cachedConnected.current;
  2339. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2340. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2341. useEffect(() => {
  2342. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2343. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2344. }
  2345. }, [status?.ams_extruder_map]);
  2346. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2347. ? status.ams_extruder_map
  2348. : cachedAmsExtruderMap.current;
  2349. // Same caching for the Filament Track Switch inlet bindings, for the same
  2350. // reason: a partial MQTT frame briefly empties the map and the badges would
  2351. // otherwise blink out.
  2352. const cachedAmsSwitchInlet = useRef<Record<string, 'A' | 'B'>>({});
  2353. useEffect(() => {
  2354. if (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0) {
  2355. cachedAmsSwitchInlet.current = status.ams_switch_inlet;
  2356. }
  2357. }, [status?.ams_switch_inlet]);
  2358. const ftsInstalled = status?.fila_switch?.installed === true;
  2359. const amsSwitchInlet = (status?.ams_switch_inlet && Object.keys(status.ams_switch_inlet).length > 0)
  2360. ? status.ams_switch_inlet
  2361. : cachedAmsSwitchInlet.current;
  2362. // Cache AMS data to prevent it disappearing on idle/offline printers
  2363. const cachedAmsData = useRef<AMSUnit[]>([]);
  2364. useEffect(() => {
  2365. if (status?.ams && status.ams.length > 0) {
  2366. cachedAmsData.current = status.ams;
  2367. }
  2368. }, [status?.ams]);
  2369. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2370. // #2532: the K-profile line only exists on slots the printer has actually
  2371. // calibrated. The AMS units and the external-spool group are flex siblings in
  2372. // one row, so on a card that shows a value anywhere, the slots without one
  2373. // reserve the same height -- otherwise their fill bars sit a line above their
  2374. // neighbours'. A card with no calibrated slot at all is unaffected.
  2375. const anySlotHasKValue = amsData.some(unit => unit.tray.some(tray => tray.k))
  2376. || (status?.vt_tray ?? []).some(tray => tray.k);
  2377. // Confirm a drying cycle actually started (#2533). Firmware answers
  2378. // ams_filament_drying with result=success even when it then silently declines,
  2379. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2380. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2381. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2382. // means the printer took the command and dropped it.
  2383. useEffect(() => {
  2384. if (!dryStartWatch) return;
  2385. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2386. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2387. }, [dryStartWatch, amsData]);
  2388. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2389. // otherwise rearm the timeout on every frame, so it would never elapse.
  2390. useEffect(() => {
  2391. if (!dryStartWatch) return;
  2392. const timer = setTimeout(() => {
  2393. setDryStartWatch(null);
  2394. showToast(t('printers.drying.toastNotStarted'), 'error');
  2395. }, DRY_START_CONFIRM_MS);
  2396. return () => clearTimeout(timer);
  2397. }, [dryStartWatch, showToast, t]);
  2398. // Cache tray_now to prevent flickering when undefined values come in
  2399. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2400. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2401. const cachedTrayNow = useRef<number | undefined>(undefined);
  2402. const currentTrayNow = status?.tray_now;
  2403. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2404. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2405. cachedTrayNow.current = currentTrayNow;
  2406. } else if (currentTrayNow === 255) {
  2407. cachedTrayNow.current = undefined;
  2408. }
  2409. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2410. ? currentTrayNow
  2411. : cachedTrayNow.current;
  2412. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2413. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2414. // expectedTray = the slot the firmware now expects filament in
  2415. // previousTray = the slot that ran out
  2416. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2417. // so these are often different — the graphic highlights the expected one.
  2418. const expectedTray = status?.expected_tray ?? null;
  2419. const previousTray = status?.previous_tray ?? null;
  2420. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2421. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2422. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2423. if (globalId === null) return null;
  2424. if (globalId === 254) return t('printers.expectedSlot.external');
  2425. if (globalId >= 128 && globalId <= 135) {
  2426. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2427. }
  2428. const amsId = Math.floor(globalId / 4);
  2429. const slot = globalId % 4;
  2430. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2431. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2432. };
  2433. const runoutGuidance = status?.state === 'PAUSE'
  2434. ? {
  2435. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2436. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2437. }
  2438. : null;
  2439. // Fetch smart plug for this printer
  2440. const { data: smartPlug } = useQuery({
  2441. queryKey: ['smartPlugByPrinter', printer.id],
  2442. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2443. });
  2444. // Fetch script plugs for this printer (for multi-device control)
  2445. const { data: scriptPlugs } = useQuery({
  2446. queryKey: ['scriptPlugsByPrinter', printer.id],
  2447. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2448. });
  2449. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2450. const { data: plugStatus } = useQuery({
  2451. queryKey: ['smartPlugStatus', smartPlug?.id],
  2452. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2453. enabled: !!smartPlug,
  2454. refetchInterval: 10000, // 10 seconds for real-time power display
  2455. });
  2456. // Fetch queue count for this printer
  2457. const { data: queueItems } = useQuery({
  2458. queryKey: ['queue', printer.id, 'pending'],
  2459. queryFn: () => api.getQueue(printer.id, 'pending'),
  2460. });
  2461. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2462. // so the badge only shows on printers that can actually run the queued jobs.
  2463. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2464. const queueCount = useMemo(() => {
  2465. if (!queueItems?.length) return 0;
  2466. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2467. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2468. // Fetch currently printing queue item to show who started it (Issue #206)
  2469. const { data: printingQueueItems } = useQuery({
  2470. queryKey: ['queue', printer.id, 'printing'],
  2471. queryFn: () => api.getQueue(printer.id, 'printing'),
  2472. enabled: status?.state === 'RUNNING',
  2473. });
  2474. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2475. const { data: reprintUser } = useQuery({
  2476. queryKey: ['currentPrintUser', printer.id],
  2477. queryFn: () => api.getCurrentPrintUser(printer.id),
  2478. enabled: status?.state === 'RUNNING',
  2479. });
  2480. // Combine both sources: queue item user takes precedence, then reprint user
  2481. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2482. // Fetch last completed print for this printer
  2483. const { data: lastPrints } = useQuery({
  2484. queryKey: ['archives', printer.id, 'last'],
  2485. queryFn: () => api.getArchives(printer.id, 1, 0),
  2486. enabled: status?.connected && status?.state !== 'RUNNING',
  2487. });
  2488. const lastPrint = lastPrints?.[0];
  2489. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2490. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2491. // Not gated on `connected`: the plate-clear gate is Bambuddy-side state, and with
  2492. // Auto Power Off the printer is powered down exactly when the operator clears the
  2493. // plate. Hiding the control there left no way to release the gate (#2864).
  2494. const showClearPlateButton = needsPlateClear && !isPrintingOrPaused;
  2495. const activePrintName = status?.current_print && isPrintingOrPaused
  2496. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2497. : null;
  2498. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2499. useEffect(() => {
  2500. if (activePrintName) {
  2501. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2502. } else if (!needsPlateClear) {
  2503. setRetainedPrintJob(null);
  2504. }
  2505. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2506. const plateStatus = (() => {
  2507. // Connected-only because the pill's only render site sits inside the live-status
  2508. // panel. For a powered-down printer the plate-clear button itself carries the
  2509. // state — see the standalone slot below the status block (#2864).
  2510. if (!requirePlateClear || !status?.connected) return null;
  2511. if (isPrintingOrPaused) {
  2512. return {
  2513. label: t('printers.plateStatus.inUse'),
  2514. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2515. };
  2516. }
  2517. if (status.awaiting_plate_clear) {
  2518. return {
  2519. label: t('printers.plateStatus.notCleared'),
  2520. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2521. };
  2522. }
  2523. return {
  2524. label: t('printers.plateStatus.cleared'),
  2525. className: 'bg-status-ok/20 text-status-ok',
  2526. };
  2527. })();
  2528. const plateStatusPill = plateStatus ? (
  2529. <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}`}>
  2530. {plateStatus.label}
  2531. </span>
  2532. ) : null;
  2533. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2534. const shouldHide = hideIfDisconnected && isConnected === false;
  2535. const deleteMutation = useMutation({
  2536. mutationFn: (options: { deleteArchives: boolean }) =>
  2537. api.deletePrinter(printer.id, options.deleteArchives),
  2538. onSuccess: () => {
  2539. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2540. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2541. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2542. },
  2543. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2544. });
  2545. const connectMutation = useMutation({
  2546. mutationFn: () => api.connectPrinter(printer.id),
  2547. onSuccess: () => {
  2548. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2549. },
  2550. });
  2551. const forceRefreshMutation = useMutation({
  2552. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2553. onSuccess: () => {
  2554. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2555. showToast(t('printers.forceRefreshSuccess'), 'success');
  2556. },
  2557. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2558. });
  2559. const unlinkSpoolMutation = useMutation({
  2560. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2561. onSuccess: (result) => {
  2562. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2563. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2564. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2565. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2566. },
  2567. onError: (error: Error) => {
  2568. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2569. },
  2570. });
  2571. // AMS drying mutations
  2572. const startDryingMutation = useMutation({
  2573. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2574. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2575. onSuccess: (_data, { amsId }) => {
  2576. setDryingPopoverAmsId(null);
  2577. setDryStartWatch({ amsId });
  2578. // "Command sent", not "drying started" — at this point the printer has only
  2579. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2580. // the cycle is genuinely live; the watcher below covers the case where it
  2581. // never appears.
  2582. showToast(t('printers.drying.toastCommandSent'), 'success');
  2583. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2584. },
  2585. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2586. });
  2587. // Scheduled (delayed / at-time) drying runs (#2638)
  2588. const scheduleDryingMutation = useMutation({
  2589. mutationFn: (params: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean; startAfter: string }) =>
  2590. api.createScheduledDrying({
  2591. printer_id: printer.id,
  2592. ams_id: params.amsId,
  2593. temp: params.temp,
  2594. duration_hours: params.duration,
  2595. filament: params.filament,
  2596. rotate_tray: params.rotateTray,
  2597. start_after: params.startAfter,
  2598. }),
  2599. onSuccess: () => {
  2600. queryClient.invalidateQueries({ queryKey: SCHEDULED_DRYINGS_KEY });
  2601. setDryingPopoverAmsId(null);
  2602. },
  2603. onError: (error: Error) => showToast(error.message || t('printers.drying.scheduleFailed'), 'error'),
  2604. });
  2605. const stopDryingMutation = useMutation({
  2606. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2607. onSuccess: () => {
  2608. setDryStartWatch(null);
  2609. showToast(t('printers.drying.toastStopped'), 'success');
  2610. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2611. },
  2612. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2613. });
  2614. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2615. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2616. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2617. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2618. // showing the old backup state until the user reopens it.
  2619. const setAmsBackupMutation = useMutation({
  2620. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2621. onSuccess: (_data, enabled) => {
  2622. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2623. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2624. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2625. },
  2626. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2627. });
  2628. // Smart plug control mutations
  2629. const powerControlMutation = useMutation({
  2630. mutationFn: (action: 'on' | 'off') =>
  2631. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2632. onSuccess: () => {
  2633. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2634. },
  2635. });
  2636. const toggleAutoOffMutation = useMutation({
  2637. mutationFn: (enabled: boolean) =>
  2638. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2639. onSuccess: () => {
  2640. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2641. // Also invalidate the smart-plugs list to keep Settings page in sync
  2642. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2643. },
  2644. });
  2645. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2646. const runScriptMutation = useMutation({
  2647. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2648. onSuccess: () => {
  2649. showToast(t('printers.toast.scriptTriggered'));
  2650. },
  2651. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2652. });
  2653. // Print control mutations
  2654. const stopPrintMutation = useMutation({
  2655. mutationFn: () => api.stopPrint(printer.id),
  2656. onSuccess: () => {
  2657. showToast(t('printers.toast.printStopped'));
  2658. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2659. },
  2660. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2661. });
  2662. const pausePrintMutation = useMutation({
  2663. mutationFn: () => api.pausePrint(printer.id),
  2664. onSuccess: () => {
  2665. showToast(t('printers.toast.printPaused'));
  2666. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2667. },
  2668. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2669. });
  2670. const resumePrintMutation = useMutation({
  2671. mutationFn: () => api.resumePrint(printer.id),
  2672. onSuccess: () => {
  2673. showToast(t('printers.toast.printResumed'));
  2674. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2675. },
  2676. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2677. });
  2678. const clearPlateMutation = useMutation({
  2679. mutationFn: () => api.clearPlate(printer.id),
  2680. onSuccess: () => {
  2681. showToast(t('queue.clearPlateSuccess'));
  2682. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2683. old ? { ...old, awaiting_plate_clear: false } : old
  2684. );
  2685. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2686. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2687. },
  2688. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2689. });
  2690. // Rendered from two places: inside the live-status block for a connected printer,
  2691. // and standalone below it for a powered-down one, whose status block isn't rendered
  2692. // at all (#2864). Shared so the two can't drift apart.
  2693. const expandedClearPlateButton = (
  2694. <button
  2695. type="button"
  2696. onClick={() => clearPlateMutation.mutate()}
  2697. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  2698. 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"
  2699. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  2700. >
  2701. {clearPlateMutation.isPending ? (
  2702. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  2703. ) : (
  2704. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  2705. )}
  2706. {t('printers.plateStatus.markCleared')}
  2707. </button>
  2708. );
  2709. const nozzleTemperatureMutation = useMutation({
  2710. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2711. api.setNozzleTemperature(printer.id, target, nozzle),
  2712. onSuccess: (result) => {
  2713. setStatusControlMenu(null);
  2714. showToast(result.message);
  2715. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2716. },
  2717. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2718. });
  2719. const bedTemperatureMutation = useMutation({
  2720. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2721. onSuccess: (result) => {
  2722. setStatusControlMenu(null);
  2723. showToast(result.message);
  2724. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2725. },
  2726. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2727. });
  2728. const chamberTemperatureMutation = useMutation({
  2729. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2730. onSuccess: (result) => {
  2731. setStatusControlMenu(null);
  2732. showToast(result.message);
  2733. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2734. },
  2735. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2736. });
  2737. const fanSpeedMutation = useMutation({
  2738. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2739. api.setFanSpeed(printer.id, fan, speed),
  2740. onMutate: async ({ fan, speed }) => {
  2741. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2742. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2743. const fanField = {
  2744. part: 'cooling_fan_speed',
  2745. aux: 'big_fan1_speed',
  2746. aux2: 'left_aux_fan_speed',
  2747. chamber: 'big_fan2_speed',
  2748. }[fan];
  2749. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2750. old ? { ...old, [fanField]: speed } : old
  2751. );
  2752. return { previousStatus };
  2753. },
  2754. onSuccess: (result) => {
  2755. setStatusControlMenu(null);
  2756. showToast(result.message);
  2757. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2758. },
  2759. onError: (error: Error, _variables, context) => {
  2760. if (context?.previousStatus) {
  2761. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2762. }
  2763. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2764. },
  2765. });
  2766. const selectExtruderMutation = useMutation({
  2767. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2768. onMutate: async (extruder) => {
  2769. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2770. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2771. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2772. old ? { ...old, active_extruder: extruder } : old
  2773. );
  2774. return { previousStatus };
  2775. },
  2776. onSuccess: (result) => {
  2777. setStatusControlMenu(null);
  2778. showToast(result.message);
  2779. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2780. },
  2781. onError: (error: Error, _extruder, context) => {
  2782. if (context?.previousStatus) {
  2783. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2784. }
  2785. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2786. },
  2787. });
  2788. // Chamber light mutation with optimistic update
  2789. const chamberLightMutation = useMutation({
  2790. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2791. onMutate: async (on) => {
  2792. // Cancel any outgoing refetches
  2793. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2794. // Snapshot the previous value
  2795. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2796. // Optimistically update
  2797. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2798. ...old,
  2799. chamber_light: on,
  2800. }));
  2801. return { previousStatus };
  2802. },
  2803. onSuccess: (_, on) => {
  2804. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2805. },
  2806. onError: (error: Error, _, context) => {
  2807. // Rollback on error
  2808. if (context?.previousStatus) {
  2809. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2810. }
  2811. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2812. },
  2813. });
  2814. // Print speed mutation with optimistic update
  2815. const printSpeedMutation = useMutation({
  2816. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2817. onMutate: async (mode) => {
  2818. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2819. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2820. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2821. ...old,
  2822. speed_level: mode,
  2823. }));
  2824. return { previousStatus };
  2825. },
  2826. onError: (error: Error, _, context) => {
  2827. if (context?.previousStatus) {
  2828. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2829. }
  2830. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2831. },
  2832. });
  2833. const airductMutation = useMutation({
  2834. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2835. onMutate: async (mode) => {
  2836. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2837. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2838. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2839. ...old,
  2840. airduct_mode: mode === 'cooling' ? 0 : 1,
  2841. }));
  2842. return { previousStatus };
  2843. },
  2844. onError: (error: Error, _, context) => {
  2845. if (context?.previousStatus) {
  2846. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2847. }
  2848. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2849. },
  2850. });
  2851. const bedJogMutation = useMutation({
  2852. mutationFn: ({ distance }: { distance: number }) =>
  2853. api.bedJog(printer.id, distance),
  2854. onError: (error: Error) =>
  2855. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2856. });
  2857. const xyJogMutation = useMutation({
  2858. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2859. api.xyJog(printer.id, x, y),
  2860. onError: (error: Error) =>
  2861. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2862. });
  2863. const extruderJogMutation = useMutation({
  2864. mutationFn: (distance: number) =>
  2865. api.extruderJog(printer.id, distance),
  2866. onError: (error: Error) =>
  2867. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2868. });
  2869. const homeAxesMutation = useMutation({
  2870. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2871. onSuccess: () => {
  2872. showToast(t('printers.bedJog.homingStarted'));
  2873. },
  2874. onError: (error: Error) =>
  2875. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2876. });
  2877. // Plate detection setting mutation
  2878. const plateDetectionMutation = useMutation({
  2879. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2880. onSuccess: () => {
  2881. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2882. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2883. },
  2884. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2885. });
  2886. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2887. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2888. // metrics, and the print picker — so flipping this flag puts the printer
  2889. // out of service across every consumer in one place. Used from the
  2890. // overflow menu and EditPrinterModal.
  2891. const maintenanceMutation = useMutation({
  2892. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2893. onSuccess: (_data, isActive) => {
  2894. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2895. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2896. showToast(
  2897. isActive
  2898. ? t('printers.maintenance.toastExited', { name: printer.name })
  2899. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2900. 'success',
  2901. );
  2902. },
  2903. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2904. });
  2905. // Confirm before entering maintenance on a printing printer (entering mode
  2906. // disconnects MQTT, which stops progress tracking + completion notifications
  2907. // for the in-flight job).
  2908. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2909. const handleEnterMaintenance = () => {
  2910. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2911. setConfirmMaintenanceEnter(true);
  2912. } else {
  2913. maintenanceMutation.mutate(false);
  2914. }
  2915. };
  2916. // Query for printable objects (for skip functionality)
  2917. // Fetch when printing with 2+ objects OR when modal is open
  2918. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2919. const { data: objectsData } = useQuery({
  2920. queryKey: ['printableObjects', printer.id],
  2921. queryFn: () => api.getPrintableObjects(printer.id),
  2922. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2923. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2924. });
  2925. // State for tracking which AMS slot is being refreshed
  2926. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2927. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2928. const seenBusyStateRef = useRef<boolean>(false);
  2929. // Fallback timeout ref
  2930. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2931. // Minimum display time passed
  2932. const minTimePassedRef = useRef<boolean>(false);
  2933. // AMS slot refresh mutation
  2934. const refreshAmsSlotMutation = useMutation({
  2935. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2936. api.refreshAmsSlot(printer.id, amsId, slotId),
  2937. onMutate: ({ amsId, slotId }) => {
  2938. // Clear any existing timeout
  2939. if (refreshTimeoutRef.current) {
  2940. clearTimeout(refreshTimeoutRef.current);
  2941. }
  2942. // Reset state
  2943. seenBusyStateRef.current = false;
  2944. minTimePassedRef.current = false;
  2945. setRefreshingSlot({ amsId, slotId });
  2946. // Minimum display time (2 seconds)
  2947. setTimeout(() => {
  2948. minTimePassedRef.current = true;
  2949. }, 2000);
  2950. // Fallback timeout (30 seconds max)
  2951. refreshTimeoutRef.current = setTimeout(() => {
  2952. setRefreshingSlot(null);
  2953. }, 30000);
  2954. },
  2955. onSuccess: (data) => {
  2956. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2957. },
  2958. onError: (error: Error) => {
  2959. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2960. if (refreshTimeoutRef.current) {
  2961. clearTimeout(refreshTimeoutRef.current);
  2962. }
  2963. setRefreshingSlot(null);
  2964. },
  2965. });
  2966. // AMS load/unload mutations (#891)
  2967. const loadAmsTrayMutation = useMutation({
  2968. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2969. onSuccess: (data) => {
  2970. showToast(data.message || t('printers.toast.loadInitiated'));
  2971. },
  2972. onError: (error: Error) => {
  2973. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2974. },
  2975. });
  2976. const unloadAmsMutation = useMutation({
  2977. mutationFn: () => api.unloadAms(printer.id),
  2978. onSuccess: (data) => {
  2979. showToast(data.message || t('printers.toast.unloadInitiated'));
  2980. },
  2981. onError: (error: Error) => {
  2982. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2983. },
  2984. });
  2985. // Plate references state
  2986. const [plateReferences, setPlateReferences] = useState<{
  2987. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2988. max_references: number;
  2989. } | null>(null);
  2990. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2991. // Fetch plate references
  2992. const fetchPlateReferences = async () => {
  2993. try {
  2994. const data = await api.getPlateReferences(printer.id);
  2995. setPlateReferences(data);
  2996. } catch {
  2997. // Ignore errors - references will show as empty
  2998. }
  2999. };
  3000. // Toggle plate detection enabled/disabled
  3001. const handleTogglePlateDetection = () => {
  3002. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  3003. };
  3004. // Open plate detection management modal (for calibration/references)
  3005. const handleOpenPlateManagement = async () => {
  3006. setIsCheckingPlate(true);
  3007. setPlateCheckResult(null);
  3008. // Auto-turn on light if it's off
  3009. const lightWasOff = status?.chamber_light === false;
  3010. setPlateCheckLightWasOff(lightWasOff);
  3011. if (lightWasOff) {
  3012. await api.setChamberLight(printer.id, true);
  3013. // Wait for light to physically turn on and camera to adjust exposure
  3014. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  3015. await new Promise(resolve => setTimeout(resolve, 2500));
  3016. }
  3017. try {
  3018. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3019. setPlateCheckResult(result);
  3020. fetchPlateReferences();
  3021. } catch (error) {
  3022. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  3023. // Restore light if check failed
  3024. if (lightWasOff) {
  3025. await api.setChamberLight(printer.id, false);
  3026. setPlateCheckLightWasOff(false);
  3027. }
  3028. } finally {
  3029. setIsCheckingPlate(false);
  3030. }
  3031. };
  3032. // Close plate check modal and restore light state
  3033. const closePlateCheckModal = useCallback(async () => {
  3034. setPlateCheckResult(null);
  3035. // Restore light to original state if we turned it on
  3036. if (plateCheckLightWasOff) {
  3037. await api.setChamberLight(printer.id, false);
  3038. setPlateCheckLightWasOff(false);
  3039. }
  3040. }, [plateCheckLightWasOff, printer.id]);
  3041. // Calibrate plate detection handler
  3042. const handleCalibratePlate = async (label?: string) => {
  3043. setIsCalibrating(true);
  3044. try {
  3045. const result = await api.calibratePlateDetection(printer.id, { label });
  3046. if (result.success) {
  3047. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  3048. // Refresh references and re-check
  3049. fetchPlateReferences();
  3050. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3051. setPlateCheckResult(checkResult);
  3052. } else {
  3053. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  3054. }
  3055. } catch (error) {
  3056. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  3057. } finally {
  3058. setIsCalibrating(false);
  3059. }
  3060. };
  3061. // Update reference label
  3062. const handleUpdateRefLabel = async (index: number, label: string) => {
  3063. try {
  3064. await api.updatePlateReferenceLabel(printer.id, index, label);
  3065. setEditingRefLabel(null);
  3066. fetchPlateReferences();
  3067. } catch (error) {
  3068. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  3069. }
  3070. };
  3071. // Delete reference
  3072. const handleDeleteRef = async (index: number) => {
  3073. try {
  3074. await api.deletePlateReference(printer.id, index);
  3075. showToast(t('printers.toast.referenceDeleted'), 'success');
  3076. fetchPlateReferences();
  3077. // Re-check to update counts
  3078. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3079. setPlateCheckResult(checkResult);
  3080. } catch (error) {
  3081. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  3082. }
  3083. };
  3084. // Save ROI settings
  3085. const handleSaveRoi = async () => {
  3086. if (!editingRoi) return;
  3087. setIsSavingRoi(true);
  3088. try {
  3089. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  3090. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  3091. setEditingRoi(null);
  3092. // Re-check to see new ROI in action
  3093. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  3094. setPlateCheckResult(checkResult);
  3095. } catch (error) {
  3096. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  3097. } finally {
  3098. setIsSavingRoi(false);
  3099. }
  3100. };
  3101. // Close plate check modal on Escape key
  3102. useEffect(() => {
  3103. const handleEscape = (e: KeyboardEvent) => {
  3104. if (e.key === 'Escape' && plateCheckResult) {
  3105. closePlateCheckModal();
  3106. }
  3107. };
  3108. window.addEventListener('keydown', handleEscape);
  3109. return () => window.removeEventListener('keydown', handleEscape);
  3110. }, [plateCheckResult, closePlateCheckModal]);
  3111. // Watch ams_status_main to detect when RFID read completes
  3112. // ams_status_main: 0=idle, 2=rfid_identifying
  3113. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  3114. useEffect(() => {
  3115. if (!refreshingSlot) return;
  3116. const amsStatus = status?.ams_status_main ?? 0;
  3117. // Track when we see non-idle state (printer is working)
  3118. if (amsStatus !== 0) {
  3119. seenBusyStateRef.current = true;
  3120. // Cancel any deferred clear since we're back to busy
  3121. if (deferredClearRef.current) {
  3122. clearTimeout(deferredClearRef.current);
  3123. deferredClearRef.current = null;
  3124. }
  3125. }
  3126. // When we've seen busy and now idle, clear (with min time check)
  3127. if (seenBusyStateRef.current && amsStatus === 0) {
  3128. if (minTimePassedRef.current) {
  3129. // Min time passed - clear now
  3130. if (refreshTimeoutRef.current) {
  3131. clearTimeout(refreshTimeoutRef.current);
  3132. }
  3133. setRefreshingSlot(null);
  3134. } else {
  3135. // Schedule clear after min time (2 seconds from start)
  3136. if (!deferredClearRef.current) {
  3137. deferredClearRef.current = setTimeout(() => {
  3138. if (refreshTimeoutRef.current) {
  3139. clearTimeout(refreshTimeoutRef.current);
  3140. }
  3141. setRefreshingSlot(null);
  3142. }, 2000);
  3143. }
  3144. }
  3145. }
  3146. return () => {
  3147. if (deferredClearRef.current) {
  3148. clearTimeout(deferredClearRef.current);
  3149. }
  3150. };
  3151. }, [status?.ams_status_main, refreshingSlot]);
  3152. useEffect(() => {
  3153. if (!showMenu) return;
  3154. const handleClickOutside = (event: MouseEvent) => {
  3155. const target = event.target as Node;
  3156. if (!printerActionsMenuRef.current?.contains(target)) {
  3157. setShowMenu(false);
  3158. }
  3159. };
  3160. document.addEventListener('mousedown', handleClickOutside);
  3161. return () => document.removeEventListener('mousedown', handleClickOutside);
  3162. }, [showMenu]);
  3163. if (shouldHide) {
  3164. return null;
  3165. }
  3166. // Size-based styling helpers
  3167. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  3168. // width, its thumbnail and the printer name, but every label inside the
  3169. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  3170. // S one -- the disparity was worst exactly where someone asking for more
  3171. // room ends up. These custom properties carry the scaled sizes into the
  3172. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  3173. // unless they reach for a size that is already asking for more space.
  3174. // Plain computation rather than useMemo: this sits after the card's early
  3175. // returns, where a hook would break the rules-of-hooks ordering, and
  3176. // building ten strings per render costs nothing.
  3177. const cardScaleStyle = buildCardScaleStyle(cardSize);
  3178. const getImageSize = () => {
  3179. switch (cardSize) {
  3180. case 1: return 'w-10 h-10';
  3181. case 2: return 'w-14 h-14';
  3182. case 3: return 'w-16 h-16';
  3183. case 4: return 'w-20 h-20';
  3184. default: return 'w-14 h-14';
  3185. }
  3186. };
  3187. const getTitleSize = () => {
  3188. switch (cardSize) {
  3189. case 1: return 'text-base truncate';
  3190. case 2: return 'text-lg';
  3191. case 3: return 'text-xl';
  3192. case 4: return 'text-2xl';
  3193. default: return 'text-lg';
  3194. }
  3195. };
  3196. const getSpacing = () => {
  3197. switch (cardSize) {
  3198. case 1: return 'mb-2';
  3199. case 2: return 'mb-4';
  3200. case 3: return 'mb-5';
  3201. case 4: return 'mb-6';
  3202. default: return 'mb-4';
  3203. }
  3204. };
  3205. // A dropped file always becomes a queue item, so a printer that is busy,
  3206. // offline or mid-drying is no reason to refuse the drop — it only means the
  3207. // item waits its turn instead of starting now (#2849). Rejecting RUNNING /
  3208. // PAUSE / disconnected sent people to the File Manager to do by hand exactly
  3209. // what this would have done for them.
  3210. //
  3211. // What remains is what the flow actually performs: upload the file, then
  3212. // create a queue item. It never touches printers:control, which is what this
  3213. // used to check — so someone holding that but neither of these had the file
  3214. // uploaded and then rejected by the queue, leaving it stranded. The Print
  3215. // button below has always checked this pair.
  3216. const canDrop = hasPermission('library:upload') && hasPermission('queue:create');
  3217. // Drives the wording alone. Shared with the PrintModal so the card's promise
  3218. // and the modal's own "will start later" toast cannot disagree.
  3219. const dropWouldQueue = !isPrinterCurrentlyDispatchable(status);
  3220. const handleCardDragEnter = (e: React.DragEvent) => {
  3221. e.preventDefault();
  3222. dragCounterRef.current++;
  3223. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  3224. };
  3225. const handleCardDragOver = (e: React.DragEvent) => {
  3226. e.preventDefault();
  3227. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  3228. };
  3229. const handleCardDragLeave = (e: React.DragEvent) => {
  3230. e.preventDefault();
  3231. dragCounterRef.current--;
  3232. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  3233. };
  3234. const handleCardDrop = async (e: React.DragEvent) => {
  3235. e.preventDefault();
  3236. dragCounterRef.current = 0;
  3237. setIsDraggingFile(false);
  3238. if (!canDrop) return;
  3239. const droppedFiles = Array.from(e.dataTransfer.files);
  3240. const file = droppedFiles[0];
  3241. if (!file) return;
  3242. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  3243. const lower = file.name.toLowerCase();
  3244. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  3245. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  3246. return;
  3247. }
  3248. setIsDropUploading(true);
  3249. try {
  3250. const result = await api.uploadLibraryFile(file, null);
  3251. // Check printer compatibility if sliced_for_model is available in metadata
  3252. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  3253. const printerModel = mapModelCode(printer.model);
  3254. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  3255. await api.deleteLibraryFile(result.id).catch(() => {});
  3256. showToast(
  3257. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  3258. 'error'
  3259. );
  3260. return;
  3261. }
  3262. setPrintAfterUpload({ id: result.id, filename: result.filename });
  3263. } catch {
  3264. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  3265. } finally {
  3266. setIsDropUploading(false);
  3267. }
  3268. };
  3269. const handleCardClick = (e: React.MouseEvent) => {
  3270. if (viewMode !== 'compact' || selectionMode) return;
  3271. const target = e.target as HTMLElement;
  3272. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  3273. onOpenCompactCard?.(printer.id);
  3274. };
  3275. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  3276. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  3277. // Opening a camera in a given mode, without touching which mode is remembered
  3278. // -- the split button's two halves want the same action but disagree about
  3279. // whether the choice was deliberate enough to keep.
  3280. const openCameraIn = (mode: CameraViewMode) => {
  3281. if (mode === 'embedded' && onOpenEmbeddedCamera) {
  3282. onOpenEmbeddedCamera(printer.id, printer.name);
  3283. } else {
  3284. openCameraWindow(printer.id);
  3285. }
  3286. };
  3287. // Picking a mode both opens the camera that way and makes it the mode the
  3288. // plain icon uses from now on. A menu that only changed a preference would
  3289. // leave the user with a second click to do the thing they already asked for.
  3290. const cameraViewModeMenuItems: ContextMenuItem[] = (
  3291. [
  3292. {
  3293. mode: 'window' as const,
  3294. icon: <ExternalLink className="w-4 h-4" />,
  3295. label: t('settings.newWindow'),
  3296. title: t('settings.cameraWindowDescription'),
  3297. },
  3298. {
  3299. mode: 'embedded' as const,
  3300. icon: <PictureInPicture2 className="w-4 h-4" />,
  3301. label: t('settings.embeddedOverlay'),
  3302. title: t('settings.cameraOverlayDescription'),
  3303. },
  3304. ]
  3305. ).map(({ mode, icon, label, title }) => ({
  3306. icon,
  3307. // The remembered mode is marked in the label itself: the icon slot already
  3308. // carries the mode's own icon, and a separate tick column would push both
  3309. // entries out of line with every other card menu.
  3310. label: mode === cameraViewMode ? `${label} ✓` : label,
  3311. title,
  3312. onClick: () => {
  3313. onSelectCameraViewMode?.(mode);
  3314. openCameraIn(mode);
  3315. },
  3316. }));
  3317. const renderAmsSlotActions = ({
  3318. amsId,
  3319. slotId,
  3320. loadTrayId,
  3321. isRefreshing,
  3322. includeRfid = true,
  3323. }: {
  3324. amsId: number;
  3325. slotId: number;
  3326. loadTrayId: number;
  3327. isRefreshing?: boolean;
  3328. includeRfid?: boolean;
  3329. }) => {
  3330. const printerBusy = status?.state === 'RUNNING';
  3331. return (
  3332. <>
  3333. {includeRfid && (
  3334. <button
  3335. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3336. hasPermission('printers:ams_rfid')
  3337. ? 'text-white hover:bg-bambu-dark-tertiary'
  3338. : 'text-bambu-gray/50 cursor-not-allowed'
  3339. }`}
  3340. onClick={(e) => {
  3341. e.stopPropagation();
  3342. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  3343. refreshAmsSlotMutation.mutate({ amsId, slotId });
  3344. }}
  3345. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  3346. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  3347. >
  3348. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  3349. {t('printers.rfid.reread')}
  3350. </button>
  3351. )}
  3352. <button
  3353. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3354. hasPermission('printers:control')
  3355. ? 'text-white hover:bg-bambu-dark-tertiary'
  3356. : 'text-bambu-gray/50 cursor-not-allowed'
  3357. }`}
  3358. onClick={(e) => {
  3359. e.stopPropagation();
  3360. if (printerBusy || !hasPermission('printers:control')) return;
  3361. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  3362. }}
  3363. disabled={printerBusy || !hasPermission('printers:control')}
  3364. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3365. >
  3366. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3367. {t('printers.ams.load')}
  3368. </button>
  3369. <button
  3370. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3371. hasPermission('printers:control')
  3372. ? 'text-white hover:bg-bambu-dark-tertiary'
  3373. : 'text-bambu-gray/50 cursor-not-allowed'
  3374. }`}
  3375. onClick={(e) => {
  3376. e.stopPropagation();
  3377. if (printerBusy || !hasPermission('printers:control')) return;
  3378. unloadAmsMutation.mutate();
  3379. }}
  3380. disabled={printerBusy || !hasPermission('printers:control')}
  3381. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3382. >
  3383. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3384. {t('printers.ams.unload')}
  3385. </button>
  3386. </>
  3387. );
  3388. };
  3389. const printerActionsMenu = (
  3390. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3391. <Button
  3392. variant="secondary"
  3393. size="sm"
  3394. onClick={() => setShowMenu(!showMenu)}
  3395. title={t('common.more', 'More')}
  3396. className={footerIconButtonClass}
  3397. >
  3398. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3399. </Button>
  3400. {showMenu && (
  3401. <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">
  3402. <button
  3403. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3404. hasPermission('printers:update')
  3405. ? 'hover:bg-bambu-dark-tertiary'
  3406. : 'opacity-50 cursor-not-allowed'
  3407. }`}
  3408. onClick={() => {
  3409. if (!hasPermission('printers:update')) return;
  3410. setShowEditModal(true);
  3411. setShowMenu(false);
  3412. }}
  3413. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3414. >
  3415. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3416. {t('common.edit')}
  3417. </button>
  3418. <button
  3419. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3420. onClick={() => {
  3421. setShowPrinterInfo(true);
  3422. setShowMenu(false);
  3423. }}
  3424. >
  3425. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3426. {t('printers.printerInformation')}
  3427. </button>
  3428. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3429. <button
  3430. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3431. hasPermission('printers:update')
  3432. ? 'hover:bg-bambu-dark-tertiary'
  3433. : 'opacity-50 cursor-not-allowed'
  3434. }`}
  3435. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3436. onClick={() => {
  3437. if (!hasPermission('printers:update')) return;
  3438. setShowMenu(false);
  3439. if (printer.is_active !== false) {
  3440. handleEnterMaintenance();
  3441. } else {
  3442. maintenanceMutation.mutate(true);
  3443. }
  3444. }}
  3445. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3446. >
  3447. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3448. {printer.is_active !== false
  3449. ? t('printers.maintenance.menuEnter')
  3450. : t('printers.maintenance.menuExit')}
  3451. </button>
  3452. <button
  3453. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3454. onClick={() => {
  3455. connectMutation.mutate();
  3456. setShowMenu(false);
  3457. }}
  3458. >
  3459. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3460. {t('printers.reconnect')}
  3461. </button>
  3462. <button
  3463. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3464. disabled={forceRefreshMutation.isPending}
  3465. onClick={() => {
  3466. forceRefreshMutation.mutate();
  3467. setShowMenu(false);
  3468. }}
  3469. >
  3470. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3471. {t('printers.forceRefresh')}
  3472. </button>
  3473. <button
  3474. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3475. onClick={() => {
  3476. setShowMQTTDebug(true);
  3477. setShowMenu(false);
  3478. }}
  3479. >
  3480. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3481. {t('printers.mqttDebug')}
  3482. </button>
  3483. <button
  3484. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3485. onClick={() => {
  3486. setShowDiagnostic(true);
  3487. setShowMenu(false);
  3488. }}
  3489. >
  3490. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3491. {t('diagnostic.runButton')}
  3492. </button>
  3493. <button
  3494. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3495. hasPermission('printers:delete')
  3496. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3497. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3498. }`}
  3499. onClick={() => {
  3500. if (!hasPermission('printers:delete')) return;
  3501. setShowDeleteConfirm(true);
  3502. setShowMenu(false);
  3503. }}
  3504. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3505. >
  3506. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3507. {t('common.delete')}
  3508. </button>
  3509. </div>
  3510. )}
  3511. </div>
  3512. );
  3513. return (
  3514. <Card
  3515. id={`printer-card-${printer.id}`}
  3516. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3517. style={cardScaleStyle}
  3518. onClick={handleCardClick}
  3519. onDragEnter={handleCardDragEnter}
  3520. onDragOver={handleCardDragOver}
  3521. onDragLeave={handleCardDragLeave}
  3522. onDrop={handleCardDrop}
  3523. >
  3524. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3525. {selectionMode && (
  3526. <div
  3527. className="absolute inset-0 z-20 flex items-start p-2"
  3528. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3529. >
  3530. {isSelected ? (
  3531. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3532. ) : (
  3533. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3534. )}
  3535. </div>
  3536. )}
  3537. {/* Drop zone overlay */}
  3538. {(isDraggingFile || isDropUploading) && (
  3539. <div
  3540. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3541. isDropUploading
  3542. ? 'bg-bambu-green/10 border-bambu-green/50'
  3543. : canDrop
  3544. ? 'bg-bambu-green/10 border-bambu-green'
  3545. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3546. }`}
  3547. >
  3548. <div className="text-center">
  3549. {isDropUploading ? (
  3550. <>
  3551. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3552. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3553. </>
  3554. ) : canDrop ? (
  3555. <>
  3556. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3557. <p className="text-sm font-medium text-bambu-green">
  3558. {dropWouldQueue ? t('printers.dropToQueue') : t('printers.dropToPrint')}
  3559. </p>
  3560. </>
  3561. ) : (
  3562. <>
  3563. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3564. <p className="text-sm font-medium text-red-700 dark:text-red-400">
  3565. {!hasPermission('library:upload')
  3566. ? t('fileManager.noPermissionUpload')
  3567. : t('fileManager.noPermissionAddToQueue')}
  3568. </p>
  3569. </>
  3570. )}
  3571. </div>
  3572. </div>
  3573. )}
  3574. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3575. {/* Header */}
  3576. <div className={getSpacing()}>
  3577. {/* Top row: Image, Name, Menu */}
  3578. <div className="flex items-start justify-between gap-2">
  3579. <div className="flex items-center gap-3 min-w-0 flex-1">
  3580. {/* Printer Model Image */}
  3581. <img
  3582. src={getPrinterImage(printer.model)}
  3583. alt={printer.model || t('common.printer')}
  3584. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3585. />
  3586. <div className="min-w-0 flex-1">
  3587. <div className="flex items-center justify-between gap-2">
  3588. <div className="flex min-w-0 items-center gap-2">
  3589. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3590. {/* Connection indicator dot for compact mode */}
  3591. {viewMode === 'compact' && (() => {
  3592. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3593. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3594. const hasWarning = hmsErrors.length > 0;
  3595. const pipColor = !status?.connected
  3596. ? 'bg-status-error'
  3597. : hasSevere
  3598. ? 'bg-status-error'
  3599. : hasWarning
  3600. ? 'bg-status-warning'
  3601. : 'bg-status-ok';
  3602. const pipTitle = !status?.connected
  3603. ? t('printers.connection.offline')
  3604. : hasWarning
  3605. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3606. : t('printers.connection.connected');
  3607. return (
  3608. <div
  3609. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3610. title={pipTitle}
  3611. />
  3612. );
  3613. })()}
  3614. </div>
  3615. {viewMode === 'compact' && showClearPlateButton && (
  3616. <button
  3617. type="button"
  3618. onClick={() => clearPlateMutation.mutate()}
  3619. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3620. aria-label={t('printers.plateStatus.markCleared')}
  3621. 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"
  3622. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3623. >
  3624. {clearPlateMutation.isPending ? (
  3625. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3626. ) : (
  3627. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3628. )}
  3629. </button>
  3630. )}
  3631. </div>
  3632. <p className="text-sm text-bambu-gray">
  3633. {printer.model || 'Unknown Model'}
  3634. {/* Nozzle Info - only in expanded */}
  3635. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3636. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3637. • {status.nozzles[0].nozzle_diameter}mm
  3638. </span>
  3639. )}
  3640. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3641. <span className="ml-2 text-bambu-gray">
  3642. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3643. {Math.round(maintenanceInfo.total_print_hours)}h
  3644. </span>
  3645. )}
  3646. </p>
  3647. </div>
  3648. </div>
  3649. </div>
  3650. {/* Badges row - only in expanded mode */}
  3651. {viewMode === 'expanded' && (
  3652. <div className="mt-2">
  3653. <div className="flex flex-wrap items-center gap-2">
  3654. {/* Connection status badge (or Maintenance pill when out of service).
  3655. Defensive: only swap when is_active is EXPLICITLY false. An
  3656. undefined / missing field defaults to "active" so the regular
  3657. pill renders — matches the backend default and prevents test
  3658. fixtures (or stale clients) from accidentally tripping the
  3659. maintenance UI. */}
  3660. {printer.is_active === false ? (
  3661. <span
  3662. 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"
  3663. title={t('printers.maintenance.subtitle')}
  3664. >
  3665. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3666. {t('printers.maintenance.pillLabel')}
  3667. </span>
  3668. ) : (
  3669. <span
  3670. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3671. status?.connected
  3672. ? 'bg-status-ok/20 text-status-ok'
  3673. : 'bg-status-error/20 text-status-error'
  3674. }`}
  3675. >
  3676. {status?.connected ? (
  3677. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3678. ) : (
  3679. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3680. )}
  3681. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3682. </span>
  3683. )}
  3684. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3685. {printer.is_active !== false && !status?.connected && (
  3686. <button
  3687. onClick={() => setShowDiagnostic(true)}
  3688. 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"
  3689. title={t('diagnostic.runButton')}
  3690. >
  3691. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3692. {t('diagnostic.runButton')}
  3693. </button>
  3694. )}
  3695. {/* Network connection indicator */}
  3696. {status?.connected && status?.wired_network && (
  3697. <span
  3698. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3699. title={t('printers.connection.ethernet', 'Ethernet')}
  3700. >
  3701. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3702. {t('printers.connection.ethernet', 'Ethernet')}
  3703. </span>
  3704. )}
  3705. {/* WiFi signal indicator */}
  3706. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3707. <span
  3708. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3709. wifiSignal >= -50
  3710. ? 'bg-status-ok/20 text-status-ok'
  3711. : wifiSignal >= -60
  3712. ? 'bg-status-ok/20 text-status-ok'
  3713. : wifiSignal >= -70
  3714. ? 'bg-status-warning/20 text-status-warning'
  3715. : wifiSignal >= -80
  3716. ? 'bg-orange-500/20 text-orange-600'
  3717. : 'bg-status-error/20 text-status-error'
  3718. }`}
  3719. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3720. >
  3721. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3722. {wifiSignal}dBm
  3723. </span>
  3724. )}
  3725. {/* HMS Status Indicator */}
  3726. {status?.connected && (() => {
  3727. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3728. return (
  3729. <button
  3730. onClick={() => setShowHMSModal(true)}
  3731. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3732. knownErrors.length > 0
  3733. ? knownErrors.some(e => e.severity <= 2)
  3734. ? 'bg-status-error/20 text-status-error'
  3735. : 'bg-status-warning/20 text-status-warning'
  3736. : 'bg-status-ok/20 text-status-ok'
  3737. }`}
  3738. title={t('printers.clickToViewHmsErrors')}
  3739. >
  3740. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3741. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3742. </button>
  3743. );
  3744. })()}
  3745. {/* AI failure detection badge (#1546) — always shown while detection
  3746. is enabled for this printer, like the other health badges. Gray
  3747. "Idle" outside a monitored print, class-colored during one. */}
  3748. {aiDetectionEnabled && (() => {
  3749. const cls = aiDetection
  3750. ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
  3751. : 'idle';
  3752. const colorClass =
  3753. cls === 'failure'
  3754. ? 'bg-status-error/20 text-status-error'
  3755. : cls === 'warning'
  3756. ? 'bg-status-warning/20 text-status-warning'
  3757. : cls === 'safe'
  3758. ? 'bg-status-ok/20 text-status-ok'
  3759. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3760. return (
  3761. <button
  3762. onClick={() => setShowAiModal(true)}
  3763. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3764. title={
  3765. aiDetection
  3766. ? t('printers.aiDetection.tooltip', {
  3767. status: t(`printers.aiDetection.${cls}`),
  3768. score: aiDetection.score.toFixed(3),
  3769. })
  3770. : t('printers.aiDetection.tooltipIdle')
  3771. }
  3772. >
  3773. <ScanEye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3774. {t(`printers.aiDetection.${cls}`)}
  3775. </button>
  3776. );
  3777. })()}
  3778. {/* Maintenance Status Indicator */}
  3779. {maintenanceInfo && (
  3780. <button
  3781. onClick={() => navigate('/maintenance')}
  3782. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3783. maintenanceInfo.due_count > 0
  3784. ? 'bg-status-error/20 text-status-error'
  3785. : maintenanceInfo.warning_count > 0
  3786. ? 'bg-status-warning/20 text-status-warning'
  3787. : 'bg-status-ok/20 text-status-ok'
  3788. }`}
  3789. title={
  3790. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3791. ? `${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`
  3792. : t('printers.maintenanceUpToDate')
  3793. }
  3794. >
  3795. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3796. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3797. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3798. : 'OK'}
  3799. </button>
  3800. )}
  3801. {/* Queue Count Badge */}
  3802. {queueCount > 0 && (
  3803. <button
  3804. onClick={() => navigate('/queue')}
  3805. 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"
  3806. title={t('printers.queue.inQueue', { count: queueCount })}
  3807. >
  3808. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3809. {queueCount}
  3810. </button>
  3811. )}
  3812. {/* Firmware Version Badge */}
  3813. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3814. <button
  3815. onClick={() => setShowFirmwareModal(true)}
  3816. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3817. firmwareInfo.update_available
  3818. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3819. : 'bg-status-ok/20 text-status-ok'
  3820. }`}
  3821. title={
  3822. firmwareInfo.update_available
  3823. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3824. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3825. }
  3826. >
  3827. {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)]" />}
  3828. {firmwareInfo.current_version}
  3829. </button>
  3830. ) : status?.firmware_version ? (
  3831. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3832. {status.firmware_version}
  3833. </span>
  3834. ) : null}
  3835. {/* Enclosure Door Badge — models with an actual door sensor.
  3836. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3837. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3838. <span
  3839. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3840. status.door_open
  3841. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3842. : 'bg-status-ok/20 text-status-ok'
  3843. }`}
  3844. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3845. >
  3846. {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)]" />}
  3847. </span>
  3848. )}
  3849. </div>
  3850. </div>
  3851. )}
  3852. </div>
  3853. {/* Delete Confirmation */}
  3854. {showDeleteConfirm && (
  3855. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3856. <Card className="w-full max-w-md mx-4">
  3857. <CardContent>
  3858. <div className="flex items-start gap-3 mb-4">
  3859. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3860. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3861. </div>
  3862. <div>
  3863. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3864. <p className="text-sm text-bambu-gray mt-1">
  3865. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3866. </p>
  3867. </div>
  3868. </div>
  3869. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3870. <label className="flex items-start gap-3 cursor-pointer">
  3871. <input
  3872. type="checkbox"
  3873. checked={deleteArchives}
  3874. onChange={(e) => setDeleteArchives(e.target.checked)}
  3875. 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"
  3876. />
  3877. <div>
  3878. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3879. <p className="text-xs text-bambu-gray mt-0.5">
  3880. {deleteArchives
  3881. ? t('printers.confirm.deleteArchivesNote')
  3882. : t('printers.confirm.keepArchivesNote')}
  3883. </p>
  3884. </div>
  3885. </label>
  3886. </div>
  3887. <div className="flex justify-end gap-2">
  3888. <Button
  3889. variant="secondary"
  3890. onClick={() => {
  3891. setShowDeleteConfirm(false);
  3892. setDeleteArchives(true);
  3893. }}
  3894. >
  3895. {t('common.cancel')}
  3896. </Button>
  3897. <Button
  3898. variant="danger"
  3899. onClick={() => {
  3900. deleteMutation.mutate({ deleteArchives });
  3901. setShowDeleteConfirm(false);
  3902. setDeleteArchives(true);
  3903. }}
  3904. >
  3905. Delete
  3906. </Button>
  3907. </div>
  3908. </CardContent>
  3909. </Card>
  3910. </div>
  3911. )}
  3912. {/* Status — see the equivalent defensive `=== false` check on the
  3913. header pill above for why this is not `!printer.is_active`. */}
  3914. {printer.is_active === false ? (
  3915. // Maintenance mode (#1476) — replaces the cover/progress container
  3916. // so the card keeps the same height. Renders for both compact and
  3917. // expanded view modes so the printer stays visible but plainly
  3918. // out-of-service.
  3919. <>
  3920. {viewMode === 'compact' ? (
  3921. <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">
  3922. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  3923. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  3924. {t('printers.maintenance.pillLabel')}
  3925. </span>
  3926. </div>
  3927. ) : (
  3928. <>
  3929. <div className="flex items-center gap-2 mb-2">
  3930. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  3931. {t('printers.status.title', 'Status')}
  3932. </span>
  3933. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3934. </div>
  3935. <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">
  3936. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3937. <div className="flex-1 min-w-0">
  3938. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3939. {t('printers.maintenance.title')}
  3940. </p>
  3941. <p className="text-xs text-bambu-gray mt-0.5">
  3942. {t('printers.maintenance.subtitle')}
  3943. </p>
  3944. </div>
  3945. <Button
  3946. variant="secondary"
  3947. size="sm"
  3948. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3949. onClick={() => maintenanceMutation.mutate(true)}
  3950. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3951. >
  3952. {t('printers.maintenance.exitButton')}
  3953. </Button>
  3954. </div>
  3955. </>
  3956. )}
  3957. </>
  3958. ) : status?.connected && (
  3959. <>
  3960. {/* Compact: Simple status bar */}
  3961. {viewMode === 'compact' ? (
  3962. (() => {
  3963. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3964. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3965. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3966. ? Math.max(0, Math.min(100, status.progress || 0))
  3967. : showClearPlateButton
  3968. ? 100
  3969. : hasProblem
  3970. ? 100
  3971. : 0;
  3972. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3973. const compactProgressClass = hasProblem
  3974. ? 'bg-status-error'
  3975. : status.state === 'PAUSE'
  3976. ? 'bg-status-warning'
  3977. : 'bg-bambu-green';
  3978. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  3979. const hasCompactLayers =
  3980. isActiveCompactPrint &&
  3981. status.layer_num != null &&
  3982. status.total_layers != null &&
  3983. status.total_layers > 0;
  3984. return (
  3985. <>
  3986. <div className="relative mt-2 flex items-center gap-2">
  3987. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3988. <div
  3989. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3990. style={{ width: `${compactProgress}%` }}
  3991. />
  3992. </div>
  3993. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3994. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3995. </span>
  3996. </div>
  3997. {/* #2674: size S showed only a name, a pip and a progress bar — not
  3998. enough to answer "which printer finishes first", which is what a
  3999. wall-mounted fleet view is for. One line of the metrics the
  4000. expanded card already renders, using the same formatters and the
  4001. same ETA styling so S and M read alike. The row keeps its height
  4002. when idle so cards don't shift as prints start and stop. */}
  4003. <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">
  4004. {hasCompactEta && (
  4005. <>
  4006. <span className="flex shrink-0 items-center gap-1">
  4007. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4008. {formatDuration(status.remaining_time! * 60)}
  4009. </span>
  4010. <span
  4011. className="shrink-0 font-medium text-bambu-green"
  4012. title={t('printers.estimatedCompletion')}
  4013. >
  4014. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  4015. </span>
  4016. </>
  4017. )}
  4018. {hasCompactLayers && (
  4019. <span className="flex min-w-0 items-center gap-1 truncate">
  4020. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  4021. {status.layer_num}/{status.total_layers}
  4022. </span>
  4023. )}
  4024. </div>
  4025. </>
  4026. );
  4027. })()
  4028. ) : (
  4029. /* Expanded: Full status section */
  4030. <>
  4031. <div className="flex items-center gap-2 mb-2">
  4032. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4033. {t('printers.status.title', 'Status')}
  4034. </span>
  4035. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4036. </div>
  4037. {/* Current Print or Idle Placeholder */}
  4038. {(() => {
  4039. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  4040. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  4041. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  4042. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  4043. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  4044. // A running print always has at least one object, so a count of
  4045. // zero means "not loaded", not "nothing to skip" — after a
  4046. // restart mid-print the list is empty until something rebuilds
  4047. // it. Treating that as nothing-to-skip disabled the only
  4048. // control that opens the modal, and the modal's own fetch is
  4049. // what rebuilds the list, so the print could never get it back.
  4050. // Exactly one object is the real nothing-to-skip case.
  4051. const objectCount = status.printable_objects_count ?? 0;
  4052. const canSkipObjects = isActivePrint && objectCount !== 1 && hasPermission('printers:control');
  4053. return (
  4054. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  4055. <button
  4056. onClick={() => setShowSkipObjectsModal(true)}
  4057. disabled={!canSkipObjects}
  4058. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  4059. canSkipObjects
  4060. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  4061. : 'text-bambu-gray/30 cursor-not-allowed'
  4062. }`}
  4063. title={
  4064. !hasPermission('printers:control')
  4065. ? t('printers.permission.noControl')
  4066. : !isActivePrint
  4067. ? t('printers.skipObjects.onlyWhilePrinting')
  4068. : objectCount === 1
  4069. ? t('printers.skipObjects.requiresMultiple')
  4070. : t('printers.skipObjects.tooltip')
  4071. }
  4072. >
  4073. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4074. {objectsData && objectsData.skipped_count > 0 && (
  4075. <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">
  4076. {objectsData.skipped_count}
  4077. </span>
  4078. )}
  4079. </button>
  4080. <div className="flex items-stretch gap-2">
  4081. <CoverImage
  4082. url={coverUrl}
  4083. printName={printName || undefined}
  4084. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  4085. />
  4086. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  4087. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  4088. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  4089. {plateStatusPill}
  4090. </div>
  4091. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  4092. {printName || t('printers.noActiveJob', 'No active job')}
  4093. </p>
  4094. <div className="flex h-3 items-center gap-2 text-sm">
  4095. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  4096. <div
  4097. 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`}
  4098. style={{ width: `${progress}%` }}
  4099. />
  4100. </div>
  4101. <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>
  4102. </div>
  4103. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  4104. {isActivePrint ? (
  4105. <>
  4106. {status.remaining_time != null && status.remaining_time > 0 && (
  4107. <>
  4108. <span className="flex items-center gap-1">
  4109. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4110. {formatDuration(status.remaining_time * 60)}
  4111. </span>
  4112. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  4113. ETA {formatETA(status.remaining_time, timeFormat, t)}
  4114. </span>
  4115. </>
  4116. )}
  4117. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  4118. <span className="flex items-center gap-1">
  4119. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4120. {status.layer_num}/{status.total_layers}
  4121. </span>
  4122. )}
  4123. {currentPrintUser && (
  4124. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  4125. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4126. {currentPrintUser}
  4127. </span>
  4128. )}
  4129. </>
  4130. ) : lastPrint ? (
  4131. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  4132. Last: {lastPrint.print_name || lastPrint.filename}
  4133. {lastPrint.completed_at && (
  4134. <span className="ml-1 text-bambu-gray/60">
  4135. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  4136. </span>
  4137. )}
  4138. </p>
  4139. ) : (
  4140. <span>{t('printers.readyToPrint')}</span>
  4141. )}
  4142. </div>
  4143. </div>
  4144. </div>
  4145. <PrinterQueueWidget
  4146. printerId={printer.id}
  4147. printerModel={printer.model}
  4148. loadedFilamentTypes={loadedFilamentTypes}
  4149. loadedFilaments={loadedFilaments}
  4150. loadedVariants={loadedVariants}
  4151. variant="panelExtension"
  4152. />
  4153. </div>
  4154. );
  4155. })()}
  4156. </>
  4157. )}
  4158. {/* Temperatures */}
  4159. {status.temperatures && viewMode === 'expanded' && (() => {
  4160. // Use actual heater states from MQTT stream
  4161. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  4162. const bedHeating = status.temperatures.bed_heating || false;
  4163. const chamberHeating = status.temperatures.chamber_heating || false;
  4164. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  4165. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  4166. const kinds: HeaterSensorKind[] = ['nozzle'];
  4167. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  4168. kinds.push('bed');
  4169. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  4170. return kinds;
  4171. })();
  4172. // active_extruder: 0=right, 1=left
  4173. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  4174. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  4175. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  4176. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  4177. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  4178. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  4179. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  4180. const canUseStatusControls = status.connected && hasPermission('printers:control');
  4181. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  4182. 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 ${
  4183. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4184. }`;
  4185. // Chamber fan only exists on enclosed Bambu models. Open-frame
  4186. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  4187. // the widget there is at best dead UI and at worst suggests a
  4188. // control that does nothing. Mirrors the enclosure-door badge
  4189. // gate above.
  4190. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  4191. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  4192. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  4193. // show it only when the printer actually reports it (airduct part id 3,
  4194. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  4195. // have a built-in chamber fan that's always present, so they keep the
  4196. // existing model-list gate and the "Chamber Fan" label.
  4197. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  4198. const chamberFanLabel = isExhaustModel
  4199. ? t('printers.fans.exhaust')
  4200. : t('printers.fans.chamber');
  4201. // Composed rather than either/or so both lists stay live for
  4202. // P2S/X2D: the model must have an enclosure fan at all, AND —
  4203. // where that fan is an add-on kit — actually report it. Written
  4204. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  4205. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  4206. // which reads as if removing them were safe.
  4207. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  4208. const fanItems: {
  4209. key: string;
  4210. label: string;
  4211. value: number;
  4212. Icon: typeof Fan;
  4213. activeClass: string;
  4214. }[] = [
  4215. {
  4216. key: 'part',
  4217. label: t('printers.fans.partCooling'),
  4218. value: status.cooling_fan_speed ?? 0,
  4219. Icon: Fan,
  4220. activeClass: 'text-cyan-600 dark:text-cyan-400',
  4221. },
  4222. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  4223. // Only reported (non-null) when the firmware lists airduct part
  4224. // id 10, i.e. when the fan is physically installed. Placed
  4225. // before the right-hand auxiliary fan so the two aux badges read
  4226. // left-to-right in the same order as the physical hardware.
  4227. ...(status.left_aux_fan_speed != null
  4228. ? [
  4229. {
  4230. key: 'aux2',
  4231. label: t('printers.fans.leftAuxiliary'),
  4232. value: status.left_aux_fan_speed,
  4233. Icon: Wind,
  4234. activeClass: 'text-indigo-600 dark:text-indigo-400',
  4235. },
  4236. ]
  4237. : []),
  4238. {
  4239. key: 'aux',
  4240. label: t('printers.fans.auxiliary'),
  4241. value: status.big_fan1_speed ?? 0,
  4242. Icon: Wind,
  4243. activeClass: 'text-blue-600 dark:text-blue-400',
  4244. },
  4245. ...(showChamberFan
  4246. ? [
  4247. {
  4248. key: 'chamber',
  4249. label: chamberFanLabel,
  4250. value: status.big_fan2_speed ?? 0,
  4251. Icon: AirVent,
  4252. activeClass: 'text-green-600 dark:text-green-400',
  4253. },
  4254. ]
  4255. : []),
  4256. ];
  4257. return (
  4258. <>
  4259. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  4260. {/* Nozzle temp - combined for dual nozzle */}
  4261. <div
  4262. className={statusControlClass}
  4263. title={statusControlTitle}
  4264. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  4265. >
  4266. <button
  4267. type="button"
  4268. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4269. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4270. onClick={(e) => {
  4271. e.stopPropagation();
  4272. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  4273. }}
  4274. >
  4275. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4276. </button>
  4277. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  4278. {status.temperatures.nozzle_2 !== undefined ? (
  4279. <>
  4280. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  4281. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4282. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  4283. </p>
  4284. </>
  4285. ) : singleNozzleSlot ? (
  4286. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  4287. <div className="cursor-default">
  4288. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4289. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4290. {Math.round(status.temperatures.nozzle || 0)}°C
  4291. </p>
  4292. </div>
  4293. </NozzleSlotHoverCard>
  4294. ) : (
  4295. <>
  4296. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4297. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4298. {Math.round(status.temperatures.nozzle || 0)}°C
  4299. </p>
  4300. </>
  4301. )}
  4302. {statusControlMenu === 'nozzle-temp' && (
  4303. isDualNozzle ? (
  4304. <IndicatorControlPopover
  4305. title="Set Nozzle Temperatures"
  4306. widthClass="w-[300px]"
  4307. popoverWidth={300}
  4308. popoverHeight={260}
  4309. isPending={nozzleTemperatureMutation.isPending}
  4310. onClose={() => setStatusControlMenu(null)}
  4311. >
  4312. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  4313. <NozzleTemperatureControlBox
  4314. label="Left Temp"
  4315. current={status.temperatures.nozzle}
  4316. target={status.temperatures.nozzle_target}
  4317. isActive={activeNozzle === 'L'}
  4318. isPending={nozzleTemperatureMutation.isPending}
  4319. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  4320. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4321. />
  4322. <NozzleTemperatureControlBox
  4323. label="Right Temp"
  4324. current={status.temperatures.nozzle_2}
  4325. target={status.temperatures.nozzle_2_target}
  4326. isActive={activeNozzle === 'R'}
  4327. isPending={nozzleTemperatureMutation.isPending}
  4328. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  4329. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4330. />
  4331. </div>
  4332. </IndicatorControlPopover>
  4333. ) : (
  4334. <IndicatorControlPopover
  4335. title="Set Nozzle Temperature"
  4336. unit="°C"
  4337. customMin={0}
  4338. customMax={320}
  4339. isPending={nozzleTemperatureMutation.isPending}
  4340. options={buildPresetOptions(nozzleTempPresets, 'C')}
  4341. onClose={() => setStatusControlMenu(null)}
  4342. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  4343. />
  4344. )
  4345. )}
  4346. </div>
  4347. <div
  4348. className={statusControlClass}
  4349. title={statusControlTitle}
  4350. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  4351. >
  4352. <button
  4353. type="button"
  4354. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4355. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4356. onClick={(e) => {
  4357. e.stopPropagation();
  4358. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  4359. }}
  4360. >
  4361. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4362. </button>
  4363. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  4364. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  4365. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4366. {Math.round(status.temperatures.bed || 0)}°C
  4367. </p>
  4368. {statusControlMenu === 'bed-temp' && (
  4369. <IndicatorControlPopover
  4370. title="Set Bed Temperature"
  4371. unit="°C"
  4372. customMin={0}
  4373. customMax={140}
  4374. isPending={bedTemperatureMutation.isPending}
  4375. options={buildPresetOptions(bedTempPresets, 'C')}
  4376. onClose={() => setStatusControlMenu(null)}
  4377. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4378. />
  4379. )}
  4380. </div>
  4381. {status.temperatures.chamber !== undefined && (() => {
  4382. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4383. // but can't act on M141, so we keep the card read-only there.
  4384. const hasChamberHeater = status.supports_chamber_heater === true;
  4385. return (
  4386. <div
  4387. className={hasChamberHeater
  4388. ? statusControlClass
  4389. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4390. title={hasChamberHeater ? statusControlTitle : undefined}
  4391. onClick={hasChamberHeater
  4392. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4393. : undefined}
  4394. >
  4395. <button
  4396. type="button"
  4397. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4398. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4399. onClick={(e) => {
  4400. e.stopPropagation();
  4401. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4402. }}
  4403. >
  4404. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4405. </button>
  4406. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4407. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4408. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4409. {Math.round(status.temperatures.chamber || 0)}°C
  4410. </p>
  4411. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4412. <IndicatorControlPopover
  4413. title="Set Chamber Temperature"
  4414. unit="°C"
  4415. customMin={0}
  4416. customMax={MAX_CHAMBER_TEMP_C}
  4417. isPending={chamberTemperatureMutation.isPending}
  4418. options={buildPresetOptions(chamberTempPresets, 'C')}
  4419. onClose={() => setStatusControlMenu(null)}
  4420. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4421. />
  4422. )}
  4423. </div>
  4424. );
  4425. })()}
  4426. {/* Active nozzle indicator for dual-nozzle printers */}
  4427. {isDualNozzle && (
  4428. <DualNozzleHoverCard
  4429. leftSlot={leftNozzleSlot}
  4430. rightSlot={rightNozzleSlot}
  4431. activeNozzle={activeNozzle}
  4432. filamentInfo={filamentInfo}
  4433. >
  4434. <div
  4435. 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 ${
  4436. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4437. }`}
  4438. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4439. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4440. >
  4441. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4442. <div className="flex items-center gap-2">
  4443. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4444. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4445. </span>
  4446. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4447. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4448. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4449. </span>
  4450. </div>
  4451. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4452. {statusControlMenu === 'nozzle-select' && (
  4453. <IndicatorControlPopover
  4454. title="Set Nozzle Selection"
  4455. widthClass="w-[300px]"
  4456. popoverWidth={300}
  4457. popoverHeight={140}
  4458. isPending={selectExtruderMutation.isPending}
  4459. options={[
  4460. { label: 'Left', value: 1 },
  4461. { label: 'Right', value: 0 },
  4462. ]}
  4463. onClose={() => setStatusControlMenu(null)}
  4464. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4465. />
  4466. )}
  4467. </div>
  4468. </DualNozzleHoverCard>
  4469. )}
  4470. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4471. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4472. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4473. )}
  4474. </div>
  4475. <div className="mt-2 flex items-center gap-1.5">
  4476. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4477. const active = value > 0;
  4478. return (
  4479. <div
  4480. key={key}
  4481. 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 ${
  4482. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4483. }`}
  4484. title={canUseStatusControls ? label : statusControlTitle}
  4485. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4486. >
  4487. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4488. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4489. {value}%
  4490. </span>
  4491. {statusControlMenu === `fan-${key}` && (
  4492. <IndicatorControlPopover
  4493. title={`Set ${label} Speed`}
  4494. unit="%"
  4495. customMin={0}
  4496. customMax={100}
  4497. isPending={fanSpeedMutation.isPending}
  4498. options={buildPresetOptions(fanSpeedPresets, '%')}
  4499. onClose={() => setStatusControlMenu(null)}
  4500. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4501. />
  4502. )}
  4503. </div>
  4504. );
  4505. })}
  4506. </div>
  4507. </>
  4508. );
  4509. })()}
  4510. {viewMode === 'expanded' && showClearPlateButton && expandedClearPlateButton}
  4511. {/* Controls */}
  4512. {viewMode === 'expanded' && (() => {
  4513. // Determine print state for control buttons
  4514. const isRunning = status.state === 'RUNNING';
  4515. const isPaused = status.state === 'PAUSE';
  4516. const isPrinting = isRunning || isPaused;
  4517. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4518. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4519. 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';
  4520. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4521. return (
  4522. <div className="mt-3">
  4523. {/* Section Header */}
  4524. <div className="flex items-center gap-2 mb-2">
  4525. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4526. {t('printers.controls')}
  4527. </span>
  4528. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4529. </div>
  4530. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4531. {/* Left: Secondary controls */}
  4532. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4533. <button
  4534. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4535. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4536. className={`${iconControlClass} ${
  4537. status.chamber_light
  4538. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4539. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4540. }`}
  4541. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4542. >
  4543. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4544. </button>
  4545. {/* Airduct Mode (P2S / X2D / H2*) */}
  4546. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4547. const isHeating = status.airduct_mode === 1;
  4548. const Icon = isHeating ? Flame : Snowflake;
  4549. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4550. 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';
  4551. return (
  4552. <div className="relative">
  4553. <button
  4554. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4555. disabled={!hasPermission('printers:control')}
  4556. className={`${iconControlClass} ${bg}`}
  4557. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4558. >
  4559. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4560. </button>
  4561. {showAirductMenu === printer.id && (
  4562. <>
  4563. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4564. <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]">
  4565. {([
  4566. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4567. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4568. ] as const).map(({ mode, label, modeId }) => (
  4569. <button
  4570. key={mode}
  4571. onClick={() => {
  4572. airductMutation.mutate(mode);
  4573. setShowAirductMenu(null);
  4574. }}
  4575. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4576. status.airduct_mode === modeId
  4577. ? 'text-bambu-green bg-bambu-green/10'
  4578. : 'text-white hover:bg-bambu-dark-tertiary'
  4579. }`}
  4580. >
  4581. {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)]" />}
  4582. {label}
  4583. </button>
  4584. ))}
  4585. </div>
  4586. </>
  4587. )}
  4588. </div>
  4589. );
  4590. })()}
  4591. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4592. {(() => {
  4593. const canControl = hasPermission('printers:control');
  4594. const disabled = isPrinting || !canControl;
  4595. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  4596. 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';
  4597. const requestZJog = (direction: 1 | -1) => {
  4598. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  4599. // The jog never disables the soft endstops (#2579), so it's always
  4600. // safe: the firmware clamps the move at the travel limit, or refuses
  4601. // it if the printer isn't homed. No not-homed bypass to gate.
  4602. bedJogMutation.mutate({ distance: signed });
  4603. };
  4604. const requestXyJog = (x: number, y: number) => {
  4605. xyJogMutation.mutate({ x, y });
  4606. };
  4607. const requestExtruderJog = (distance: number) => {
  4608. extruderJogMutation.mutate(distance);
  4609. };
  4610. return (
  4611. <div className="relative">
  4612. <button
  4613. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4614. disabled={disabled}
  4615. className={`${iconControlClass} ${
  4616. disabled
  4617. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4618. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4619. }`}
  4620. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4621. >
  4622. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4623. </button>
  4624. {showBedJogMenu === printer.id && (
  4625. <>
  4626. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4627. <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">
  4628. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4629. {t('printers.bedJog.title')}
  4630. </div>
  4631. <div className="h-px bg-bambu-dark-tertiary" />
  4632. {/* #2579: Bambu firmware does not enforce soft endstops on
  4633. G-code sent over MQTT, so manual moves can drive past the
  4634. travel limits and cause a collision. Not fixable from our
  4635. side — warn prominently. */}
  4636. <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">
  4637. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4638. <span>{t('printers.bedJog.limitWarning')}</span>
  4639. </div>
  4640. <div className="h-px bg-bambu-dark-tertiary" />
  4641. <div className="flex justify-center px-3 py-2.5">
  4642. <div className="flex items-center justify-center gap-3">
  4643. <div className="grid grid-cols-3 gap-1">
  4644. <div />
  4645. <button
  4646. onClick={() => requestXyJog(0, bedJogStep)}
  4647. disabled={xyJogMutation.isPending}
  4648. className={jogButtonClass}
  4649. aria-label="Move Y forward"
  4650. >
  4651. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4652. </button>
  4653. <div />
  4654. <button
  4655. onClick={() => requestXyJog(-bedJogStep, 0)}
  4656. disabled={xyJogMutation.isPending}
  4657. className={jogButtonClass}
  4658. aria-label="Move X left"
  4659. >
  4660. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4661. </button>
  4662. <button
  4663. onClick={() => {
  4664. setShowBedJogMenu(null);
  4665. homeAxesMutation.mutate('all');
  4666. }}
  4667. disabled={homeAxesMutation.isPending}
  4668. className={jogButtonClass}
  4669. aria-label={t('printers.bedJog.homeZ')}
  4670. >
  4671. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4672. </button>
  4673. <button
  4674. onClick={() => requestXyJog(bedJogStep, 0)}
  4675. disabled={xyJogMutation.isPending}
  4676. className={jogButtonClass}
  4677. aria-label="Move X right"
  4678. >
  4679. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4680. </button>
  4681. <div />
  4682. <button
  4683. onClick={() => requestXyJog(0, -bedJogStep)}
  4684. disabled={xyJogMutation.isPending}
  4685. className={jogButtonClass}
  4686. aria-label="Move Y back"
  4687. >
  4688. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4689. </button>
  4690. <div />
  4691. </div>
  4692. <div className="flex flex-col items-center gap-1">
  4693. <button
  4694. onClick={() => requestZJog(-1)}
  4695. disabled={bedJogMutation.isPending}
  4696. className={jogButtonClass}
  4697. aria-label={t('printers.bedJog.up')}
  4698. >
  4699. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4700. </button>
  4701. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4702. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4703. </div>
  4704. <button
  4705. onClick={() => requestZJog(1)}
  4706. disabled={bedJogMutation.isPending}
  4707. className={jogButtonClass}
  4708. aria-label={t('printers.bedJog.down')}
  4709. >
  4710. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4711. </button>
  4712. </div>
  4713. <div className="flex flex-col items-center gap-1">
  4714. <button
  4715. onClick={() => requestExtruderJog(-bedJogStep)}
  4716. disabled={extruderJogMutation.isPending}
  4717. className={jogButtonClass}
  4718. aria-label="Retract filament"
  4719. >
  4720. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4721. </button>
  4722. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4723. <span className="text-sm font-semibold leading-none">E</span>
  4724. </div>
  4725. <button
  4726. onClick={() => requestExtruderJog(bedJogStep)}
  4727. disabled={extruderJogMutation.isPending}
  4728. className={jogButtonClass}
  4729. aria-label="Extrude filament"
  4730. >
  4731. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4732. </button>
  4733. </div>
  4734. </div>
  4735. </div>
  4736. <div className="h-px bg-bambu-dark-tertiary" />
  4737. <div className="px-3 pt-2.5 pb-3">
  4738. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4739. {t('printers.bedJog.step')}
  4740. </div>
  4741. <div className="flex gap-1">
  4742. {[1, 10, 50].map((step) => (
  4743. <button
  4744. key={step}
  4745. onClick={() => setBedJogStep(step)}
  4746. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4747. bedJogStep === step
  4748. ? 'bg-bambu-green/20 text-bambu-green'
  4749. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4750. }`}
  4751. >
  4752. {step}
  4753. </button>
  4754. ))}
  4755. </div>
  4756. </div>
  4757. </div>
  4758. </>
  4759. )}
  4760. </div>
  4761. );
  4762. })()}
  4763. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4764. <button
  4765. onClick={handleTogglePlateDetection}
  4766. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4767. className={`${iconControlClass} rounded-r-none ${
  4768. printer.plate_detection_enabled
  4769. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4770. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4771. }`}
  4772. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4773. >
  4774. {plateDetectionMutation.isPending ? (
  4775. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4776. ) : (
  4777. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4778. )}
  4779. </button>
  4780. <button
  4781. onClick={handleOpenPlateManagement}
  4782. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4783. 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 ${
  4784. printer.plate_detection_enabled
  4785. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4786. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4787. }`}
  4788. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4789. >
  4790. {isCheckingPlate ? (
  4791. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4792. ) : (
  4793. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4794. )}
  4795. </button>
  4796. </div>
  4797. {/* Print Speed */}
  4798. {(() => (
  4799. <div className="relative">
  4800. <button
  4801. data-testid="speed-control"
  4802. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4803. disabled={!isPrinting || !hasPermission('printers:control')}
  4804. className={`${iconControlClass} ${
  4805. isPrinting
  4806. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4807. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4808. }`}
  4809. title={isPrinting ? t('printers.speed.title') : undefined}
  4810. >
  4811. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4812. </button>
  4813. {showSpeedMenu === printer.id && (
  4814. <>
  4815. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4816. <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]">
  4817. {([
  4818. { mode: 1, label: t('printers.speed.silent') },
  4819. { mode: 2, label: t('printers.speed.standard') },
  4820. { mode: 3, label: t('printers.speed.sport') },
  4821. { mode: 4, label: t('printers.speed.ludicrous') },
  4822. ] as const).map(({ mode, label }) => (
  4823. <button
  4824. key={mode}
  4825. onClick={() => {
  4826. printSpeedMutation.mutate(mode);
  4827. setShowSpeedMenu(null);
  4828. }}
  4829. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4830. status.speed_level === mode
  4831. ? 'text-bambu-green bg-bambu-green/10'
  4832. : 'text-white hover:bg-bambu-dark-tertiary'
  4833. }`}
  4834. >
  4835. {label}
  4836. </button>
  4837. ))}
  4838. </div>
  4839. </>
  4840. )}
  4841. </div>
  4842. ))()}
  4843. </div>
  4844. {/* Right: Print Control Buttons */}
  4845. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4846. {/* Pause/Resume button */}
  4847. {(() => {
  4848. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4849. return (
  4850. <button
  4851. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4852. disabled={pauseUnavailable}
  4853. className={`
  4854. ${printControlClass}
  4855. ${pauseUnavailable
  4856. ? unavailablePrintActionClass
  4857. : isPaused
  4858. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4859. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4860. }
  4861. `}
  4862. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4863. >
  4864. {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)]" />}
  4865. {isPaused ? t('printers.resume') : t('printers.pause')}
  4866. </button>
  4867. );
  4868. })()}
  4869. {/* Stop button */}
  4870. {(() => {
  4871. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4872. return (
  4873. <button
  4874. onClick={() => setShowStopConfirm(true)}
  4875. disabled={stopUnavailable}
  4876. className={`
  4877. ${printControlClass}
  4878. ${stopUnavailable
  4879. ? unavailablePrintActionClass
  4880. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4881. }
  4882. `}
  4883. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4884. >
  4885. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4886. {t('printers.stop')}
  4887. </button>
  4888. );
  4889. })()}
  4890. </div>
  4891. </div>
  4892. </div>
  4893. );
  4894. })()}
  4895. {/* AMS Units - 2-Column Grid Layout */}
  4896. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4897. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4898. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4899. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4900. // The external spool can only be hidden while some AMS remains to
  4901. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  4902. // filament section, so the toggle is not offered there and a stored
  4903. // preference from a printer that later lost its AMS cannot blank the
  4904. // row either — both read through canHideExternalSpool.
  4905. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  4906. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  4907. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4908. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  4909. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  4910. // floating point, and that lands verbatim in the DOM.
  4911. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  4912. // Deliberately NOT scaled with the body (#1848). These AMS cards
  4913. // already grow to fill the row, so the 3.5rem is a floor they sit
  4914. // well above in practice -- raising it just costs a unit its place
  4915. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  4916. // its line, and flex-grow stretches its single slot across the whole
  4917. // card. The AMS-HT's own width does scale, below, because its
  4918. // readings sit beside the slot rather than under it.
  4919. const slotMinWidth = '3.5rem';
  4920. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  4921. // The AMS-HT holds a single spool, and its slot is the only thing
  4922. // on that row able to grow -- so it swallowed every spare pixel and
  4923. // shoved the temperature and humidity hard against the card's edge.
  4924. // Capping it at roughly two ordinary slots keeps the readings clear
  4925. // of the edge; the cap scales because the text inside the slot does.
  4926. const htSlotStyle: React.CSSProperties = {
  4927. minWidth: slotMinWidth,
  4928. maxWidth: scaledRem(7.25),
  4929. };
  4930. const slotGridStyle = (columns: number): React.CSSProperties => ({
  4931. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  4932. });
  4933. // #1762 (comment 2): while a print is running/paused, overlay a small
  4934. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4935. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4936. // staged to a printer with mismatched filament: the wrong-slot pill
  4937. // is visible the instant printing starts.
  4938. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4939. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4940. ? status.ams_mapping
  4941. : [];
  4942. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4943. const boundedSlotCount = Math.max(1, slotCount);
  4944. const gapCount = Math.max(0, boundedSlotCount - 1);
  4945. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  4946. return {
  4947. flex: `1 1 ${minWidth}`,
  4948. minWidth,
  4949. };
  4950. };
  4951. return (
  4952. <div className="mt-3">
  4953. {/* Section Header */}
  4954. <div className="flex items-center gap-2 mb-2">
  4955. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4956. {t('printers.filaments')}
  4957. </span>
  4958. <AmsBackupBadge
  4959. state={status.ams_filament_backup}
  4960. onClick={() => setAmsBackupModalOpen(true)}
  4961. />
  4962. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4963. {/* Offered only when an AMS is present: on a printer that
  4964. feeds from the external spool alone, hiding it would
  4965. empty the row entirely (#1782). */}
  4966. {canHideExternalSpool && (
  4967. <>
  4968. <ExternalSpoolToggle
  4969. hidden={externalSpoolHidden}
  4970. onClick={toggleExternalSpool}
  4971. />
  4972. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  4973. </>
  4974. )}
  4975. </div>
  4976. {/* AMS Content */}
  4977. <div className="flex flex-wrap gap-2">
  4978. {/* Regular AMS units */}
  4979. {regularAms.map((ams) => {
  4980. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  4981. return (
  4982. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4983. {/* Header: Label + Stats (no icon) */}
  4984. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4985. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4986. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4987. <AmsNameHoverCard
  4988. ams={ams}
  4989. printerId={printer.id}
  4990. label={getAmsLabel(ams.id, ams.tray.length)}
  4991. amsLabels={amsLabels}
  4992. canEdit={hasPermission('printers:update')}
  4993. onSaved={refetchAmsLabels}
  4994. >
  4995. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  4996. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4997. </span>
  4998. </AmsNameHoverCard>
  4999. {sideBadge?.kind === 'inlet' ? (
  5000. <InletBadge
  5001. inlet={sideBadge.inlet}
  5002. title={t('printers.amsSwitchInletTooltip', {
  5003. inlet: sideBadge.inlet,
  5004. side: FTS_INLET_SIDE[sideBadge.inlet],
  5005. })}
  5006. />
  5007. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5008. <NozzleBadge side={sideBadge.side} />
  5009. ) : null}
  5010. </div>
  5011. {(ams.humidity != null || ams.temp != null) && (
  5012. <div className="flex shrink-0 items-center gap-1.5">
  5013. {ams.humidity != null && (
  5014. <HumidityIndicator
  5015. humidity={ams.humidity}
  5016. goodThreshold={amsThresholds?.humidityGood}
  5017. fairThreshold={amsThresholds?.humidityFair}
  5018. onClick={() => setAmsHistoryModal({
  5019. amsId: ams.id,
  5020. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5021. mode: 'humidity',
  5022. })}
  5023. compact
  5024. />
  5025. )}
  5026. {ams.temp != null && (
  5027. <div className="mr-1">
  5028. <TemperatureIndicator
  5029. temp={ams.temp}
  5030. goodThreshold={amsThresholds?.tempGood}
  5031. fairThreshold={amsThresholds?.tempFair}
  5032. onClick={() => setAmsHistoryModal({
  5033. amsId: ams.id,
  5034. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5035. mode: 'temperature',
  5036. })}
  5037. compact
  5038. />
  5039. </div>
  5040. )}
  5041. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  5042. Screen-only models (P1 series) keep the control but can't
  5043. be commanded: it stays disabled and says why (#2533). */}
  5044. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5045. <button
  5046. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  5047. onClick={(e) => {
  5048. if (ams.dry_time > 0) {
  5049. stopDryingMutation.mutate(ams.id);
  5050. } else if (dryingPopoverAmsId === ams.id) {
  5051. setDryingPopoverAmsId(null);
  5052. } else {
  5053. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5054. }
  5055. }}
  5056. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5057. ams.dry_time > 0
  5058. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5059. : status.drying_screen_only || ams.dry_sf_reason?.length
  5060. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5061. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5062. }`}
  5063. 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')}
  5064. >
  5065. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5066. </button>
  5067. )}
  5068. </div>
  5069. )}
  5070. </div>
  5071. {/* Drying status bar */}
  5072. {ams.dry_time > 0 && (
  5073. <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)]">
  5074. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5075. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  5076. {/* The temperature is only ever known from the target we
  5077. cached when sending the command — the filament can also
  5078. be read off a uniformly loaded unit, so it can outlive
  5079. the temperature (#2759). */}
  5080. {ams.dry_filament && (
  5081. <span className="text-amber-700/80 dark:text-amber-300/70">
  5082. {ams.dry_target_temp != null
  5083. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5084. : ams.dry_filament}
  5085. </span>
  5086. )}
  5087. <span className="text-amber-700/80 dark:text-amber-300/70">
  5088. {t('printers.drying.timeRemaining', {
  5089. time: ams.dry_time >= 60
  5090. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5091. : `${ams.dry_time}m`
  5092. })}
  5093. </span>
  5094. {/* A cycle on a screen-only model was started at the printer
  5095. and can only be stopped there (#2533). */}
  5096. {!status.drying_screen_only && (
  5097. <button
  5098. onClick={() => stopDryingMutation.mutate(ams.id)}
  5099. disabled={stopDryingMutation.isPending}
  5100. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  5101. title={t('printers.drying.stop')}
  5102. >
  5103. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5104. </button>
  5105. )}
  5106. </div>
  5107. )}
  5108. {/* Slots grid: 4 columns - always render 4 slots */}
  5109. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  5110. {[0, 1, 2, 3].map((slotIdx) => {
  5111. // Find tray data for this slot (may be undefined if data incomplete)
  5112. // Use array index if available, as tray.id may not always be set
  5113. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  5114. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5115. const isEmpty = !tray?.tray_type;
  5116. const emptyKind = getEmptySlotKind(tray);
  5117. // Check if this is the currently loaded tray
  5118. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  5119. const globalTrayId = ams.id * 4 + slotIdx;
  5120. const isActive = effectiveTrayNow === globalTrayId;
  5121. // Runout guidance (#2587): the slot the paused print now
  5122. // expects filament in, and the slot that ran out.
  5123. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5124. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5125. // Get cloud preset info if available
  5126. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5127. // Get saved slot preset mapping (for user-configured slots)
  5128. const slotPreset = slotPresets?.[globalTrayId];
  5129. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5130. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  5131. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  5132. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  5133. // Slot-assigned-only spool fill (no tag link required)
  5134. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5135. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  5136. : undefined;
  5137. const slotSpoolForFill = slotAssignmentForFill
  5138. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  5139. : undefined;
  5140. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  5141. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  5142. : null;
  5143. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5144. const inventoryFill = (() => {
  5145. const sp = inventoryAssignment?.spool;
  5146. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5147. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5148. }
  5149. return null;
  5150. })();
  5151. // If inventory says 0% but AMS reports positive remain, prefer AMS
  5152. // (inventory weight_used may be stale or over-counted — #676)
  5153. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5154. ? null : inventoryFill;
  5155. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5156. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  5157. : resolvedInventoryFill !== null ? 'inventory' as const
  5158. : hasFillLevel ? 'ams' as const
  5159. : undefined;
  5160. // Build filament data for hover card
  5161. const filamentData = tray?.tray_type ? {
  5162. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5163. // Spoolman spool name wins over cloud lookup so a slot bound to
  5164. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  5165. // Design PLA") instead of whatever the printer's filament_id
  5166. // resolves to in the cloud catalog (often "Generic PLA" for
  5167. // P-prefix local presets). Spoolman's filament.name is just the
  5168. // material+subtype ("PLA Basic"); prepend the spool's brand so
  5169. // the hover card shows "Devil Design PLA Basic" rather than the
  5170. // vendor-less form. Strip the "@<printer>..." suffix that
  5171. // BambuStudio appends to user-preset names.
  5172. 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,
  5173. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5174. colorHex: tray.tray_color || null,
  5175. kFactor: formatKValue(tray.k),
  5176. fillLevel: effectiveFill,
  5177. trayUuid: tray.tray_uuid || null,
  5178. tagUid: tray.tag_uid || null,
  5179. fillSource,
  5180. } : null;
  5181. // Check if this specific slot is being refreshed
  5182. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  5183. refreshingSlot?.slotId === slotIdx;
  5184. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  5185. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5186. const activePrintSlotLabel = activePrintSlotIdx >= 0
  5187. ? `P${activePrintSlotIdx + 1}`
  5188. : null;
  5189. // Slot visual content (goes inside hover card)
  5190. const slotVisual = (
  5191. <div
  5192. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5193. isExpectedSlot
  5194. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5195. : isRanOutSlot
  5196. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5197. : isActive
  5198. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5199. : ''
  5200. }`}
  5201. >
  5202. {isExpectedSlot && (
  5203. <span
  5204. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  5205. title={t('printers.expectedSlot.title')}
  5206. 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"
  5207. >
  5208. </span>
  5209. )}
  5210. {activePrintSlotLabel && (
  5211. <span
  5212. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  5213. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  5214. 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"
  5215. >
  5216. {activePrintSlotLabel}
  5217. </span>
  5218. )}
  5219. {/* Filament color circle with 1-based slot number centered inside */}
  5220. <FilamentSlotCircle
  5221. trayColor={tray?.tray_color}
  5222. trayType={tray?.tray_type}
  5223. isEmpty={isEmpty}
  5224. emptyKind={emptyKind}
  5225. slotNumber={slotIdx + 1}
  5226. />
  5227. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5228. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5229. </div>
  5230. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5231. {/* Fill bar */}
  5232. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5233. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  5234. <div
  5235. className="h-full rounded-full transition-all"
  5236. style={{
  5237. width: `${effectiveFill}%`,
  5238. backgroundColor: getFillBarColor(effectiveFill),
  5239. }}
  5240. />
  5241. )}
  5242. </div>
  5243. </div>
  5244. );
  5245. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  5246. return (
  5247. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  5248. {/* Loading overlay during RFID re-read */}
  5249. {isRefreshing && (
  5250. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5251. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5252. </div>
  5253. )}
  5254. {/* Hover card wraps only the visual content */}
  5255. {filamentData ? (
  5256. <FilamentHoverCard
  5257. data={filamentData}
  5258. actions={renderAmsSlotActions({
  5259. amsId: ams.id,
  5260. slotId: slotIdx,
  5261. loadTrayId: ams.id * 4 + slotIdx,
  5262. isRefreshing,
  5263. })}
  5264. spoolman={{
  5265. enabled: spoolmanEnabled,
  5266. // #1457: slot assignment is the user's most explicit action — it must
  5267. // outrank the tag-link, which can be stale when a non-RFID slot's
  5268. // fallback tag is still attached to a previous spool in Spoolman.
  5269. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  5270. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  5271. spoolmanUrl,
  5272. syncMode: spoolmanSyncMode,
  5273. // Suppress Link button when slot is already occupied by ANY assignment
  5274. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  5275. // suppressed for Spoolman; the maintainer screenshot shows the badge
  5276. // still appearing on slots with a local Devil Design PLA assigned.
  5277. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  5278. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  5279. setLinkSpoolModal({
  5280. tagUid: filamentData.tagUid || linkTag,
  5281. trayUuid: filamentData.trayUuid || '',
  5282. printerId: printer.id,
  5283. amsId: ams.id,
  5284. trayId: slotIdx,
  5285. });
  5286. } : undefined,
  5287. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  5288. }}
  5289. inventory={(() => {
  5290. if (spoolmanEnabled) {
  5291. if (spoolmanLoading) return undefined;
  5292. const slotAssignment = slotAssignmentForFill;
  5293. const spoolmanSpool = slotSpoolForFill;
  5294. return {
  5295. assignedSpool: spoolmanSpool ? {
  5296. id: spoolmanSpool.id,
  5297. material: spoolmanSpool.material,
  5298. brand: spoolmanSpool.brand ?? null,
  5299. color_name: spoolmanSpool.color_name ?? null,
  5300. remainingWeightGrams: spoolmanSpool.label_weight
  5301. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5302. : undefined,
  5303. } : null,
  5304. onAssignSpool: () => setAssignSpoolModal({
  5305. printerId: printer.id,
  5306. amsId: ams.id,
  5307. trayId: slotIdx,
  5308. trayInfo: {
  5309. type: tray?.tray_type || filamentData.profile,
  5310. material: tray?.tray_type ?? undefined,
  5311. profile: filamentData.profile,
  5312. color: filamentData.colorHex || '',
  5313. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5314. },
  5315. }),
  5316. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5317. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5318. };
  5319. }
  5320. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  5321. return {
  5322. assignedSpool: assignment?.spool ? {
  5323. id: assignment.spool.id,
  5324. material: assignment.spool.material,
  5325. brand: assignment.spool.brand,
  5326. color_name: assignment.spool.color_name,
  5327. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5328. } : null,
  5329. onAssignSpool: () => setAssignSpoolModal({
  5330. printerId: printer.id,
  5331. amsId: ams.id,
  5332. trayId: slotIdx,
  5333. trayInfo: {
  5334. type: tray?.tray_type || filamentData.profile,
  5335. material: tray?.tray_type ?? undefined,
  5336. profile: filamentData.profile,
  5337. color: filamentData.colorHex || '',
  5338. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5339. },
  5340. }),
  5341. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  5342. isAssigned: !!assignment || isBambuLabSpool(tray),
  5343. };
  5344. })()}
  5345. configureSlot={{
  5346. enabled: hasPermission('printers:control'),
  5347. onConfigure: () => setConfigureSlotModal({
  5348. amsId: ams.id,
  5349. trayId: slotIdx,
  5350. trayCount: ams.tray.length,
  5351. trayType: tray?.tray_type || undefined,
  5352. trayColor: tray?.tray_color || undefined,
  5353. traySubBrands: tray?.tray_sub_brands || undefined,
  5354. trayInfoIdx: tray?.tray_info_idx || undefined,
  5355. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5356. caliIdx: tray?.cali_idx,
  5357. savedPresetId: slotPreset?.preset_id,
  5358. }),
  5359. }}
  5360. >
  5361. {slotVisual}
  5362. </FilamentHoverCard>
  5363. ) : (
  5364. <EmptySlotHoverCard
  5365. kind={emptyKind ?? undefined}
  5366. actions={renderAmsSlotActions({
  5367. amsId: ams.id,
  5368. slotId: slotIdx,
  5369. loadTrayId: ams.id * 4 + slotIdx,
  5370. isRefreshing,
  5371. })}
  5372. configureSlot={{
  5373. enabled: hasPermission('printers:control'),
  5374. onConfigure: () => setConfigureSlotModal({
  5375. amsId: ams.id,
  5376. trayId: slotIdx,
  5377. trayCount: ams.tray.length,
  5378. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5379. }),
  5380. }}
  5381. onAssignSpool={() => setAssignSpoolModal({
  5382. printerId: printer.id,
  5383. amsId: ams.id,
  5384. trayId: slotIdx,
  5385. trayInfo: {
  5386. type: '',
  5387. material: undefined,
  5388. profile: '',
  5389. color: '',
  5390. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5391. },
  5392. })}
  5393. >
  5394. {slotVisual}
  5395. </EmptySlotHoverCard>
  5396. )}
  5397. </div>
  5398. );
  5399. })}
  5400. </div>
  5401. </div>
  5402. );
  5403. })}
  5404. {/* HT AMS units */}
  5405. {htAms.map((ams) => {
  5406. const sideBadge = amsSideBadge(ams.id, amsExtruderMap, amsSwitchInlet, ftsInstalled);
  5407. const tray = ams.tray[0];
  5408. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5409. const isEmpty = !tray?.tray_type;
  5410. const emptyKind = getEmptySlotKind(tray);
  5411. // Check if this is the currently loaded tray
  5412. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5413. const isActive = effectiveTrayNow === globalTrayId;
  5414. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5415. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5416. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5417. // Get cloud preset info if available
  5418. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5419. // Get saved slot preset mapping (for user-configured slots)
  5420. const slotPreset = slotPresets?.[globalTrayId];
  5421. const htSlotId = tray?.id ?? 0;
  5422. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5423. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5424. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5425. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5426. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5427. const htInventoryFill = (() => {
  5428. const sp = htInventoryAssignment?.spool;
  5429. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5430. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5431. }
  5432. return null;
  5433. })();
  5434. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5435. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5436. ? null : htInventoryFill;
  5437. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5438. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5439. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5440. : undefined;
  5441. const htSlotSpoolForFill = htSlotAssignmentForFill
  5442. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5443. : undefined;
  5444. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5445. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5446. : null;
  5447. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5448. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5449. : htResolvedInventoryFill !== null ? 'inventory' as const
  5450. : hasFillLevel ? 'ams' as const
  5451. : undefined;
  5452. // Build filament data for hover card
  5453. const filamentData = tray?.tray_type ? {
  5454. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5455. 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,
  5456. colorName: getColorName(tray.tray_color || '', tray.tray_sub_brands),
  5457. colorHex: tray.tray_color || null,
  5458. kFactor: formatKValue(tray.k),
  5459. fillLevel: htEffectiveFill,
  5460. trayUuid: tray.tray_uuid || null,
  5461. tagUid: tray.tag_uid || null,
  5462. fillSource: htFillSource,
  5463. } : null;
  5464. // Check if this specific slot is being refreshed
  5465. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5466. refreshingSlot?.slotId === htSlotId;
  5467. // #1762 (comment 2): active print-slot index for this HT slot.
  5468. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5469. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5470. ? `P${htActivePrintSlotIdx + 1}`
  5471. : null;
  5472. // Slot visual content (goes inside hover card)
  5473. const slotVisual = (
  5474. <div
  5475. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5476. isExpectedSlot
  5477. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5478. : isRanOutSlot
  5479. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5480. : isActive
  5481. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5482. : ''
  5483. }`}
  5484. >
  5485. {isExpectedSlot && (
  5486. <span
  5487. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5488. title={t('printers.expectedSlot.title')}
  5489. 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"
  5490. >
  5491. </span>
  5492. )}
  5493. {htActivePrintSlotLabel && (
  5494. <span
  5495. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5496. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5497. 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"
  5498. >
  5499. {htActivePrintSlotLabel}
  5500. </span>
  5501. )}
  5502. {/* Filament color circle with 1-based slot number centered inside */}
  5503. <FilamentSlotCircle
  5504. trayColor={tray?.tray_color}
  5505. trayType={tray?.tray_type}
  5506. isEmpty={isEmpty}
  5507. emptyKind={emptyKind}
  5508. slotNumber={1}
  5509. />
  5510. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5511. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5512. </div>
  5513. <KValueLine k={filamentData ? tray?.k : null} reserve={anySlotHasKValue} />
  5514. {/* Fill bar */}
  5515. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5516. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5517. <div
  5518. className="h-full rounded-full transition-all"
  5519. style={{
  5520. width: `${htEffectiveFill}%`,
  5521. backgroundColor: getFillBarColor(htEffectiveFill),
  5522. }}
  5523. />
  5524. )}
  5525. </div>
  5526. </div>
  5527. );
  5528. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5529. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5530. // Without this override, the L view squishes HT into a sliver next to the
  5531. // 4-slot AMS neighbors.
  5532. // 11rem holds one slot plus the temperature/humidity
  5533. // column beside it; both grow with the body scale.
  5534. const htCardWidth = scaledRem(11);
  5535. const htCardStyle: React.CSSProperties = {
  5536. flex: `1 1 ${htCardWidth}`,
  5537. minWidth: htCardWidth,
  5538. // An AMS-HT is never wider than a full AMS. Without a
  5539. // ceiling, a unit that wraps onto a line of its own is
  5540. // the only flex item there and grow stretches its single
  5541. // slot across the entire card, leaving the readings
  5542. // stranded at the far edge.
  5543. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5544. };
  5545. return (
  5546. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5547. {/* Row 1: Label + Nozzle + Drying */}
  5548. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5549. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5550. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5551. <AmsNameHoverCard
  5552. ams={ams}
  5553. printerId={printer.id}
  5554. label={getAmsLabel(ams.id, ams.tray.length)}
  5555. amsLabels={amsLabels}
  5556. canEdit={hasPermission('printers:update')}
  5557. onSaved={refetchAmsLabels}
  5558. >
  5559. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5560. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5561. </span>
  5562. </AmsNameHoverCard>
  5563. {sideBadge?.kind === 'inlet' ? (
  5564. <InletBadge
  5565. inlet={sideBadge.inlet}
  5566. title={t('printers.amsSwitchInletTooltip', {
  5567. inlet: sideBadge.inlet,
  5568. side: FTS_INLET_SIDE[sideBadge.inlet],
  5569. })}
  5570. />
  5571. ) : isDualNozzle && sideBadge?.kind === 'nozzle' ? (
  5572. <NozzleBadge side={sideBadge.side} />
  5573. ) : null}
  5574. </div>
  5575. {/* Drying button for HT AMS */}
  5576. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5577. <div className="relative ml-auto">
  5578. <button
  5579. disabled={status.drying_screen_only}
  5580. onClick={(e) => {
  5581. if (ams.dry_time > 0) {
  5582. stopDryingMutation.mutate(ams.id);
  5583. } else if (dryingPopoverAmsId === ams.id) {
  5584. setDryingPopoverAmsId(null);
  5585. } else {
  5586. openDryingPopover(ams, e.currentTarget as HTMLElement);
  5587. }
  5588. }}
  5589. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5590. ams.dry_time > 0
  5591. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5592. : status.drying_screen_only
  5593. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5594. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5595. }`}
  5596. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5597. >
  5598. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5599. </button>
  5600. </div>
  5601. )}
  5602. </div>
  5603. {/* HT AMS drying status bar */}
  5604. {ams.dry_time > 0 && (
  5605. <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)]">
  5606. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5607. {ams.dry_filament && (
  5608. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5609. {ams.dry_target_temp != null
  5610. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5611. : ams.dry_filament}
  5612. </span>
  5613. )}
  5614. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5615. {ams.dry_time >= 60
  5616. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5617. : `${ams.dry_time}m`}
  5618. </span>
  5619. {!status.drying_screen_only && (
  5620. <button
  5621. onClick={() => stopDryingMutation.mutate(ams.id)}
  5622. disabled={stopDryingMutation.isPending}
  5623. 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"
  5624. title={t('printers.drying.stop')}
  5625. >
  5626. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5627. </button>
  5628. )}
  5629. </div>
  5630. )}
  5631. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5632. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5633. {/* Slot wrapper with loading overlay */}
  5634. <div className="relative group flex-1" style={htSlotStyle}>
  5635. {/* Loading overlay during RFID re-read */}
  5636. {isHtRefreshing && (
  5637. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5638. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5639. </div>
  5640. )}
  5641. {/* Hover card wraps only the visual content */}
  5642. {filamentData ? (
  5643. <FilamentHoverCard
  5644. data={filamentData}
  5645. actions={renderAmsSlotActions({
  5646. amsId: ams.id,
  5647. slotId: htSlotId,
  5648. loadTrayId: ams.id * 4 + htSlotId,
  5649. isRefreshing: isHtRefreshing,
  5650. })}
  5651. spoolman={{
  5652. enabled: spoolmanEnabled,
  5653. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5654. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5655. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5656. spoolmanUrl,
  5657. syncMode: spoolmanSyncMode,
  5658. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5659. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5660. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5661. setLinkSpoolModal({
  5662. tagUid: filamentData.tagUid || linkTag,
  5663. trayUuid: filamentData.trayUuid || '',
  5664. printerId: printer.id,
  5665. amsId: ams.id,
  5666. trayId: htSlotId,
  5667. });
  5668. } : undefined,
  5669. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5670. }}
  5671. inventory={(() => {
  5672. if (spoolmanEnabled) {
  5673. if (spoolmanLoading) return undefined;
  5674. const slotAssignment = htSlotAssignmentForFill;
  5675. const spoolmanSpool = htSlotSpoolForFill;
  5676. return {
  5677. assignedSpool: spoolmanSpool ? {
  5678. id: spoolmanSpool.id,
  5679. material: spoolmanSpool.material,
  5680. brand: spoolmanSpool.brand ?? null,
  5681. color_name: spoolmanSpool.color_name ?? null,
  5682. remainingWeightGrams: spoolmanSpool.label_weight
  5683. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5684. : undefined,
  5685. } : null,
  5686. onAssignSpool: () => setAssignSpoolModal({
  5687. printerId: printer.id,
  5688. amsId: ams.id,
  5689. trayId: htSlotId,
  5690. trayInfo: {
  5691. type: tray?.tray_type || filamentData.profile,
  5692. material: tray?.tray_type ?? undefined,
  5693. profile: filamentData.profile,
  5694. color: filamentData.colorHex || '',
  5695. location: getAmsLabel(ams.id, ams.tray.length),
  5696. },
  5697. }),
  5698. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5699. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5700. };
  5701. }
  5702. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5703. return {
  5704. assignedSpool: assignment?.spool ? {
  5705. id: assignment.spool.id,
  5706. material: assignment.spool.material,
  5707. brand: assignment.spool.brand,
  5708. color_name: assignment.spool.color_name,
  5709. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5710. } : null,
  5711. onAssignSpool: () => setAssignSpoolModal({
  5712. printerId: printer.id,
  5713. amsId: ams.id,
  5714. trayId: htSlotId,
  5715. trayInfo: {
  5716. type: tray?.tray_type || filamentData.profile,
  5717. material: tray?.tray_type ?? undefined,
  5718. profile: filamentData.profile,
  5719. color: filamentData.colorHex || '',
  5720. location: getAmsLabel(ams.id, ams.tray.length),
  5721. },
  5722. }),
  5723. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5724. isAssigned: !!assignment || isBambuLabSpool(tray),
  5725. };
  5726. })()}
  5727. configureSlot={{
  5728. enabled: hasPermission('printers:control'),
  5729. onConfigure: () => setConfigureSlotModal({
  5730. amsId: ams.id,
  5731. trayId: htSlotId,
  5732. trayCount: ams.tray.length,
  5733. trayType: tray?.tray_type || undefined,
  5734. trayColor: tray?.tray_color || undefined,
  5735. traySubBrands: tray?.tray_sub_brands || undefined,
  5736. trayInfoIdx: tray?.tray_info_idx || undefined,
  5737. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5738. caliIdx: tray?.cali_idx,
  5739. savedPresetId: slotPreset?.preset_id,
  5740. }),
  5741. }}
  5742. >
  5743. {slotVisual}
  5744. </FilamentHoverCard>
  5745. ) : (
  5746. <EmptySlotHoverCard
  5747. kind={emptyKind ?? undefined}
  5748. actions={renderAmsSlotActions({
  5749. amsId: ams.id,
  5750. slotId: htSlotId,
  5751. loadTrayId: ams.id * 4 + htSlotId,
  5752. isRefreshing: isHtRefreshing,
  5753. })}
  5754. configureSlot={{
  5755. enabled: hasPermission('printers:control'),
  5756. onConfigure: () => setConfigureSlotModal({
  5757. amsId: ams.id,
  5758. trayId: htSlotId,
  5759. trayCount: ams.tray.length,
  5760. extruderId: resolveSlotExtruder(ams.id, tray?.id ?? 0, amsExtruderMap, amsSwitchInlet),
  5761. }),
  5762. }}
  5763. onAssignSpool={() => setAssignSpoolModal({
  5764. printerId: printer.id,
  5765. amsId: ams.id,
  5766. trayId: htSlotId,
  5767. trayInfo: {
  5768. type: '',
  5769. material: undefined,
  5770. profile: '',
  5771. color: '',
  5772. location: getAmsLabel(ams.id, ams.tray.length),
  5773. },
  5774. })}
  5775. >
  5776. {slotVisual}
  5777. </EmptySlotHoverCard>
  5778. )}
  5779. </div>
  5780. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5781. {(ams.humidity != null || ams.temp != null) && (
  5782. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5783. {ams.temp != null && (
  5784. <TemperatureIndicator
  5785. temp={ams.temp}
  5786. goodThreshold={amsThresholds?.tempGood}
  5787. fairThreshold={amsThresholds?.tempFair}
  5788. onClick={() => setAmsHistoryModal({
  5789. amsId: ams.id,
  5790. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5791. mode: 'temperature',
  5792. })}
  5793. compact
  5794. />
  5795. )}
  5796. {ams.humidity != null && (
  5797. <HumidityIndicator
  5798. humidity={ams.humidity}
  5799. goodThreshold={amsThresholds?.humidityGood}
  5800. fairThreshold={amsThresholds?.humidityFair}
  5801. onClick={() => setAmsHistoryModal({
  5802. amsId: ams.id,
  5803. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5804. mode: 'humidity',
  5805. })}
  5806. compact
  5807. />
  5808. )}
  5809. </div>
  5810. )}
  5811. </div>
  5812. </div>
  5813. );
  5814. })}
  5815. {/* External spool(s) - grouped in one card like regular AMS */}
  5816. {status.vt_tray.length > 0 && showExternalSpool && (
  5817. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5818. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5819. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  5820. </div>
  5821. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  5822. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5823. const extTrayId = extTray.id ?? 254;
  5824. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5825. // generically — use active_extruder to determine L vs R:
  5826. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5827. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5828. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5829. (extTrayId === 255 && status.active_extruder === 0)
  5830. : effectiveTrayNow === extTrayId;
  5831. const slotTrayId = extTrayId - 254; // 0 or 1
  5832. const extLabel = isDualNozzle
  5833. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5834. : '';
  5835. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5836. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5837. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5838. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5839. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5840. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5841. const extInventoryFill = (() => {
  5842. const sp = extInventoryAssignment?.spool;
  5843. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5844. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5845. }
  5846. return null;
  5847. })();
  5848. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5849. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5850. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5851. ? null : extInventoryFill;
  5852. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5853. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5854. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5855. : undefined;
  5856. const extSlotSpoolForFill = extSlotAssignmentForFill
  5857. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5858. : undefined;
  5859. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5860. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5861. : null;
  5862. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5863. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5864. : extResolvedInventoryFill !== null ? 'inventory' as const
  5865. : extHasFillLevel ? 'ams' as const
  5866. : undefined;
  5867. const extFilamentData = {
  5868. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5869. 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',
  5870. colorName: getColorName(extTray.tray_color || '', extTray.tray_sub_brands),
  5871. colorHex: extTray.tray_color || null,
  5872. kFactor: formatKValue(extTray.k),
  5873. fillLevel: extEffectiveFill,
  5874. trayUuid: extTray.tray_uuid || null,
  5875. tagUid: extTray.tag_uid || null,
  5876. fillSource: extFillSource,
  5877. };
  5878. const isEmpty = !extTray.tray_type;
  5879. const emptyKind = getEmptySlotKind(extTray);
  5880. const extSlotContent = (
  5881. <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' : ''}`}>
  5882. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5883. the separate Ext-L/Ext-R caption that made the row taller than
  5884. regular AMS slots), 1-based slot number on single-nozzle. */}
  5885. <FilamentSlotCircle
  5886. trayColor={extTray.tray_color}
  5887. trayType={extTray.tray_type}
  5888. isEmpty={isEmpty}
  5889. emptyKind={emptyKind}
  5890. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5891. />
  5892. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5893. {extTray.tray_type || t('ams.slotEmpty')}
  5894. </div>
  5895. <KValueLine k={isEmpty ? null : extTray.k} reserve={anySlotHasKValue} />
  5896. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5897. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5898. <div
  5899. className="h-full rounded-full transition-all"
  5900. style={{
  5901. width: `${extEffectiveFill}%`,
  5902. backgroundColor: getFillBarColor(extEffectiveFill),
  5903. }}
  5904. />
  5905. )}
  5906. </div>
  5907. </div>
  5908. );
  5909. return (
  5910. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  5911. {!isEmpty ? (
  5912. <FilamentHoverCard
  5913. data={extFilamentData}
  5914. actions={renderAmsSlotActions({
  5915. amsId: 255,
  5916. slotId: slotTrayId,
  5917. loadTrayId: extTrayId,
  5918. includeRfid: false,
  5919. })}
  5920. spoolman={{
  5921. enabled: spoolmanEnabled,
  5922. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5923. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5924. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5925. spoolmanUrl,
  5926. syncMode: spoolmanSyncMode,
  5927. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5928. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5929. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5930. setLinkSpoolModal({
  5931. tagUid: extFilamentData.tagUid || linkTag,
  5932. trayUuid: extFilamentData.trayUuid || '',
  5933. printerId: printer.id,
  5934. amsId: 255,
  5935. trayId: slotTrayId,
  5936. });
  5937. } : undefined,
  5938. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5939. }}
  5940. inventory={(() => {
  5941. if (spoolmanEnabled) {
  5942. if (spoolmanLoading) return undefined;
  5943. const slotAssignment = extSlotAssignmentForFill;
  5944. const spoolmanSpool = extSlotSpoolForFill;
  5945. return {
  5946. assignedSpool: spoolmanSpool ? {
  5947. id: spoolmanSpool.id,
  5948. material: spoolmanSpool.material,
  5949. brand: spoolmanSpool.brand ?? null,
  5950. color_name: spoolmanSpool.color_name ?? null,
  5951. remainingWeightGrams: spoolmanSpool.label_weight
  5952. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5953. : undefined,
  5954. } : null,
  5955. onAssignSpool: () => setAssignSpoolModal({
  5956. printerId: printer.id,
  5957. amsId: 255,
  5958. trayId: slotTrayId,
  5959. trayInfo: {
  5960. type: extTray.tray_type || extFilamentData.profile,
  5961. material: extTray.tray_type ?? undefined,
  5962. profile: extFilamentData.profile,
  5963. color: extFilamentData.colorHex || '',
  5964. location: extLabel || t('printers.external'),
  5965. },
  5966. }),
  5967. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5968. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5969. };
  5970. }
  5971. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5972. return {
  5973. assignedSpool: assignment?.spool ? {
  5974. id: assignment.spool.id,
  5975. material: assignment.spool.material,
  5976. brand: assignment.spool.brand,
  5977. color_name: assignment.spool.color_name,
  5978. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5979. } : null,
  5980. onAssignSpool: () => setAssignSpoolModal({
  5981. printerId: printer.id,
  5982. amsId: 255,
  5983. trayId: slotTrayId,
  5984. trayInfo: {
  5985. type: extTray.tray_type || extFilamentData.profile,
  5986. material: extTray.tray_type ?? undefined,
  5987. profile: extFilamentData.profile,
  5988. color: extFilamentData.colorHex || '',
  5989. location: extLabel || t('printers.external'),
  5990. },
  5991. }),
  5992. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5993. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5994. };
  5995. })()}
  5996. configureSlot={{
  5997. enabled: hasPermission('printers:control'),
  5998. onConfigure: () => setConfigureSlotModal({
  5999. amsId: 255,
  6000. trayId: slotTrayId,
  6001. trayCount: 1,
  6002. trayType: extTray.tray_type || undefined,
  6003. trayColor: extTray.tray_color || undefined,
  6004. traySubBrands: extTray.tray_sub_brands || undefined,
  6005. trayInfoIdx: extTray.tray_info_idx || undefined,
  6006. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6007. caliIdx: extTray.cali_idx,
  6008. savedPresetId: extSlotPreset?.preset_id,
  6009. }),
  6010. }}
  6011. >
  6012. {extSlotContent}
  6013. </FilamentHoverCard>
  6014. ) : (
  6015. <EmptySlotHoverCard
  6016. kind={emptyKind ?? undefined}
  6017. actions={renderAmsSlotActions({
  6018. amsId: 255,
  6019. slotId: slotTrayId,
  6020. loadTrayId: extTrayId,
  6021. includeRfid: false,
  6022. })}
  6023. configureSlot={{
  6024. enabled: hasPermission('printers:control'),
  6025. onConfigure: () => setConfigureSlotModal({
  6026. amsId: 255,
  6027. trayId: slotTrayId,
  6028. trayCount: 1,
  6029. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  6030. }),
  6031. }}
  6032. onAssignSpool={() => setAssignSpoolModal({
  6033. printerId: printer.id,
  6034. amsId: 255,
  6035. trayId: slotTrayId,
  6036. trayInfo: {
  6037. type: '',
  6038. material: undefined,
  6039. profile: '',
  6040. color: '',
  6041. location: `External Slot ${slotTrayId + 1}`,
  6042. },
  6043. })}
  6044. >
  6045. {extSlotContent}
  6046. </EmptySlotHoverCard>
  6047. )}
  6048. </div>
  6049. );
  6050. })}
  6051. </div>
  6052. </div>
  6053. )}
  6054. </div>
  6055. </div>
  6056. );
  6057. })()}
  6058. </>
  6059. )}
  6060. {/* Powered-down printer with a dirty plate: the status block above renders
  6061. nothing without a live connection, so the plate-clear control gets its own
  6062. slot here. Auto Power Off makes this the ordinary end-of-print state, and
  6063. the gate is Bambuddy-side — releasing it never touches the printer (#2864). */}
  6064. {printer.is_active !== false && !status?.connected && viewMode === 'expanded' && showClearPlateButton && (
  6065. expandedClearPlateButton
  6066. )}
  6067. {/* Bottom block (power row + action bar). Wrapped together so the
  6068. power row hugs the action bar at the card bottom instead of
  6069. floating up when there's less filament content above. */}
  6070. {viewMode === 'expanded' && (
  6071. <div className="mt-auto">
  6072. {smartPlug && (
  6073. <div className="pt-3">
  6074. <div className="flex items-center gap-2 mb-2">
  6075. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  6076. {t('printers.power', 'Power')}
  6077. </span>
  6078. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6079. </div>
  6080. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  6081. {/* Plug name + current power */}
  6082. <div className="flex items-center gap-2 min-w-0 pl-1">
  6083. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  6084. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  6085. <span
  6086. 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"
  6087. title={t('smartPlugs.power')}
  6088. >
  6089. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  6090. </span>
  6091. </div>
  6092. {/* Spacer */}
  6093. <div className="flex-1" />
  6094. <div className="flex items-center gap-2">
  6095. {/* Auto-off */}
  6096. <button
  6097. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  6098. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  6099. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  6100. 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 ${
  6101. !hasPermission('smart_plugs:control')
  6102. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6103. : smartPlug.auto_off || smartPlug.auto_off_executed
  6104. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6105. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6106. }`}
  6107. >
  6108. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6109. </button>
  6110. <button
  6111. onClick={() => {
  6112. if (plugStatus?.state === 'ON') {
  6113. setShowPowerOffConfirm(true);
  6114. } else {
  6115. setShowPowerOnConfirm(true);
  6116. }
  6117. }}
  6118. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  6119. 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 ${
  6120. !hasPermission('smart_plugs:control')
  6121. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  6122. : plugStatus?.state === 'ON'
  6123. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  6124. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  6125. }`}
  6126. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  6127. >
  6128. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6129. </button>
  6130. </div>
  6131. </div>
  6132. {/* HA entity buttons row */}
  6133. {scriptPlugs && scriptPlugs.length > 0 && (
  6134. <div className="flex items-center gap-2 mt-2">
  6135. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  6136. <span className="text-xs text-bambu-gray">HA:</span>
  6137. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  6138. <div className="flex flex-wrap gap-1">
  6139. {scriptPlugs.map(script => {
  6140. const isScript = script.ha_entity_id?.startsWith('script.');
  6141. return (
  6142. <button
  6143. key={script.id}
  6144. onClick={() => {
  6145. if (isScript) {
  6146. runScriptMutation.mutate({ id: script.id, action: 'on' });
  6147. } else {
  6148. setHaToggleConfirm(script);
  6149. }
  6150. }}
  6151. disabled={runScriptMutation.isPending}
  6152. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  6153. 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"
  6154. >
  6155. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  6156. {script.name}
  6157. </button>
  6158. );
  6159. })}
  6160. </div>
  6161. </div>
  6162. )}
  6163. </div>
  6164. )}
  6165. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  6166. a printer can have an enclosure door contact without having a plug,
  6167. and nesting it there would hide the row on exactly those setups. */}
  6168. <PrinterHASensorRow printerId={printer.id} />
  6169. {/* Connection Info & Actions */}
  6170. <div className="pt-4">
  6171. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  6172. <div className="flex items-center justify-between gap-2">
  6173. {printerActionsMenu}
  6174. <div className="flex items-center justify-end gap-2 flex-wrap">
  6175. {/* Camera split button: the icon opens whichever view was used
  6176. last, the caret picks between the two and remembers it.
  6177. Replaces the old Settings > General > Camera switch, which
  6178. made choosing between an overlay and a window a trip to
  6179. another page for something you decide per camera. */}
  6180. <div className="flex items-center flex-shrink-0">
  6181. <Button
  6182. variant="secondary"
  6183. size="sm"
  6184. onClick={() => openCameraIn(cameraViewMode)}
  6185. disabled={!status?.connected || !hasPermission('camera:view')}
  6186. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  6187. className={`${footerIconButtonClass} !rounded-r-none`}
  6188. >
  6189. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6190. </Button>
  6191. <Button
  6192. variant="secondary"
  6193. size="sm"
  6194. onClick={(e) => {
  6195. // No open/close toggle: the menu's own outside-mousedown
  6196. // handler has already dismissed it by the time this lands.
  6197. const rect = e.currentTarget.getBoundingClientRect();
  6198. setCameraMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
  6199. }}
  6200. disabled={!status?.connected || !hasPermission('camera:view')}
  6201. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : t('settings.cameraViewMode')}
  6202. aria-label={t('settings.cameraViewMode')}
  6203. // Not footerIconButtonClass plus an override: both widths
  6204. // would carry !important and the stylesheet's own order,
  6205. // not this one, would decide which won.
  6206. className="!h-8 !min-h-8 !w-6 !px-0 !py-0 !rounded-l-none border-l border-bambu-dark"
  6207. >
  6208. <ChevronDown className="w-3 h-3" />
  6209. </Button>
  6210. </div>
  6211. {cameraMenuAnchor && (
  6212. <ContextMenu
  6213. x={cameraMenuAnchor.x}
  6214. y={cameraMenuAnchor.y}
  6215. items={cameraViewModeMenuItems}
  6216. onClose={() => setCameraMenuAnchor(null)}
  6217. />
  6218. )}
  6219. <Button
  6220. variant="secondary"
  6221. size="sm"
  6222. onClick={() => setShowFileManager(true)}
  6223. disabled={!hasPermission('printers:files')}
  6224. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  6225. className={footerIconButtonClass}
  6226. >
  6227. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6228. </Button>
  6229. {/* Shown whatever the printer is doing (#2849): this uploads a
  6230. file and queues it, which a busy or offline printer is no
  6231. reason to refuse -- it only means the item waits. Hiding it
  6232. while the drop zone accepted the same file would have left
  6233. the two routes into this flow disagreeing. */}
  6234. <Button
  6235. size="sm"
  6236. onClick={() => setShowUploadForPrint(true)}
  6237. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  6238. title={
  6239. !hasPermission('library:upload')
  6240. ? t('fileManager.noPermissionUpload')
  6241. : !hasPermission('queue:create')
  6242. ? t('fileManager.noPermissionAddToQueue')
  6243. : t('common.print')
  6244. }
  6245. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  6246. >
  6247. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  6248. {t('common.print')}
  6249. </Button>
  6250. </div>
  6251. </div>
  6252. </div>
  6253. </div>
  6254. )}
  6255. {/* Scheduled Drying Banner -- inside CardContent so it picks up the
  6256. card's horizontal padding instead of running full-bleed into the
  6257. rounded bottom edge. */}
  6258. <ScheduledDryingBanner
  6259. printerId={printer.id}
  6260. dryingActive={amsData.some(a => (a.dry_time ?? 0) > 0)}
  6261. timeFormat={timeFormat}
  6262. />
  6263. </CardContent>
  6264. {/* File Manager Modal */}
  6265. {showFileManager && (
  6266. <FileManagerModal
  6267. printerId={printer.id}
  6268. printerName={printer.name}
  6269. onClose={() => setShowFileManager(false)}
  6270. />
  6271. )}
  6272. {/* Upload for Print Modal */}
  6273. {showUploadForPrint && (
  6274. <FileUploadModal
  6275. folderId={null}
  6276. onClose={() => setShowUploadForPrint(false)}
  6277. onUploadComplete={() => {}}
  6278. autoUpload
  6279. accept=".gcode,.3mf"
  6280. validateFile={(file) => {
  6281. const lower = file.name.toLowerCase();
  6282. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  6283. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  6284. }
  6285. }}
  6286. onFileUploaded={(uploadedFile) => {
  6287. // Check printer compatibility if sliced_for_model is available in metadata
  6288. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  6289. const printerModel = mapModelCode(printer.model);
  6290. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  6291. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  6292. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  6293. }
  6294. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  6295. }}
  6296. />
  6297. )}
  6298. {/* Print Modal (after upload) */}
  6299. {printAfterUpload && (
  6300. <PrintModal
  6301. mode="create"
  6302. libraryFileId={printAfterUpload.id}
  6303. archiveName={printAfterUpload.filename}
  6304. initialSelectedPrinterIds={[printer.id]}
  6305. onClose={() => setPrintAfterUpload(null)}
  6306. onSuccess={() => setPrintAfterUpload(null)}
  6307. cleanupLibraryAfterDispatch
  6308. />
  6309. )}
  6310. {/* MQTT Debug Modal */}
  6311. {showMQTTDebug && (
  6312. <MQTTDebugModal
  6313. printerId={printer.id}
  6314. printerName={printer.name}
  6315. onClose={() => setShowMQTTDebug(false)}
  6316. />
  6317. )}
  6318. {showDiagnostic && (
  6319. <ConnectionDiagnosticModal
  6320. printerId={printer.id}
  6321. printerName={printer.name}
  6322. onClose={() => setShowDiagnostic(false)}
  6323. />
  6324. )}
  6325. {showPrinterInfo && (
  6326. <PrinterInfoModal
  6327. printer={printer}
  6328. status={status}
  6329. totalPrintHours={maintenanceInfo?.total_print_hours}
  6330. onClose={closePrinterInfo}
  6331. />
  6332. )}
  6333. {/* Plate Check Result Modal */}
  6334. {plateCheckResult && (
  6335. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  6336. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  6337. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  6338. <div className="flex items-center gap-2">
  6339. {plateCheckResult.needs_calibration ? (
  6340. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  6341. ) : plateCheckResult.is_empty ? (
  6342. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  6343. ) : (
  6344. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  6345. )}
  6346. <h2 className="text-lg font-semibold text-white">
  6347. Build Plate Check
  6348. </h2>
  6349. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  6350. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  6351. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  6352. </span>
  6353. )}
  6354. </div>
  6355. <button
  6356. onClick={() => closePlateCheckModal()}
  6357. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  6358. >
  6359. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  6360. </button>
  6361. </div>
  6362. <div className="p-4 space-y-4">
  6363. {plateCheckResult.needs_calibration ? (
  6364. <>
  6365. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  6366. <p className="font-medium text-blue-700 dark:text-blue-400">
  6367. {t('printers.plateDetection.calibrationRequired')}
  6368. </p>
  6369. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  6370. </div>
  6371. <div className="text-sm text-bambu-gray space-y-2">
  6372. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  6373. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  6374. </div>
  6375. </>
  6376. ) : (
  6377. <>
  6378. <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'}`}>
  6379. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  6380. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6381. </p>
  6382. <p className="text-sm text-bambu-gray mt-1">
  6383. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6384. </p>
  6385. </div>
  6386. {plateCheckResult.debug_image_url && (
  6387. <div>
  6388. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6389. <img
  6390. src={plateCheckResult.debug_image_url}
  6391. alt={t('printers.plateDetection.analysisPreview')}
  6392. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6393. />
  6394. <p className="text-xs text-bambu-gray mt-2">
  6395. {t('printers.plateDetection.analysisLegend')}
  6396. </p>
  6397. </div>
  6398. )}
  6399. <p className="text-xs text-bambu-gray">
  6400. {plateCheckResult.message}
  6401. </p>
  6402. </>
  6403. )}
  6404. {/* Saved References Grid */}
  6405. {plateReferences && plateReferences.references.length > 0 && (
  6406. <div className="mt-4">
  6407. <div className="flex items-center gap-2 mb-2">
  6408. <p className="text-sm font-medium text-white shrink-0">
  6409. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6410. </p>
  6411. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6412. </div>
  6413. <div className="grid grid-cols-5 gap-2">
  6414. {plateReferences.references.map((ref) => (
  6415. <div key={ref.index} className="relative group">
  6416. <img
  6417. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6418. alt={ref.label || `Reference ${ref.index + 1}`}
  6419. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6420. />
  6421. {/* Delete button */}
  6422. <button
  6423. onClick={() => handleDeleteRef(ref.index)}
  6424. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded can-hover:opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity"
  6425. title={t('printers.plateDetection.deleteReference')}
  6426. >
  6427. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6428. </button>
  6429. {/* Label */}
  6430. {editingRefLabel?.index === ref.index ? (
  6431. <input
  6432. type="text"
  6433. value={editingRefLabel.label}
  6434. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6435. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6436. onKeyDown={(e) => {
  6437. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6438. if (e.key === 'Escape') setEditingRefLabel(null);
  6439. }}
  6440. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6441. autoFocus
  6442. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6443. />
  6444. ) : (
  6445. <p
  6446. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6447. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6448. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6449. >
  6450. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6451. </p>
  6452. )}
  6453. {/* Timestamp */}
  6454. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6455. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6456. </p>
  6457. </div>
  6458. ))}
  6459. </div>
  6460. </div>
  6461. )}
  6462. {/* ROI Editor */}
  6463. {!plateCheckResult.needs_calibration && (
  6464. <div className="mt-4">
  6465. <div className="flex items-center justify-between mb-2">
  6466. <div className="flex min-w-0 flex-1 items-center gap-2">
  6467. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6468. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6469. </div>
  6470. {!editingRoi ? (
  6471. <Button
  6472. variant="ghost"
  6473. size="sm"
  6474. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6475. >
  6476. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6477. {t('common.edit')}
  6478. </Button>
  6479. ) : (
  6480. <div className="flex gap-1">
  6481. <Button
  6482. variant="ghost"
  6483. size="sm"
  6484. onClick={() => setEditingRoi(null)}
  6485. disabled={isSavingRoi}
  6486. >
  6487. {t('common.cancel')}
  6488. </Button>
  6489. <Button
  6490. size="sm"
  6491. onClick={handleSaveRoi}
  6492. disabled={isSavingRoi}
  6493. >
  6494. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6495. </Button>
  6496. </div>
  6497. )}
  6498. </div>
  6499. {editingRoi ? (
  6500. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6501. <div className="grid grid-cols-2 gap-3">
  6502. <div>
  6503. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6504. <input
  6505. type="range"
  6506. min="0"
  6507. max="0.9"
  6508. step="0.01"
  6509. value={editingRoi.x}
  6510. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6511. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6512. />
  6513. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6514. </div>
  6515. <div>
  6516. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6517. <input
  6518. type="range"
  6519. min="0"
  6520. max="0.9"
  6521. step="0.01"
  6522. value={editingRoi.y}
  6523. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6524. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6525. />
  6526. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6527. </div>
  6528. <div>
  6529. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6530. <input
  6531. type="range"
  6532. min="0.1"
  6533. max="1"
  6534. step="0.01"
  6535. value={editingRoi.w}
  6536. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6537. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6538. />
  6539. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6540. </div>
  6541. <div>
  6542. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6543. <input
  6544. type="range"
  6545. min="0.1"
  6546. max="1"
  6547. step="0.01"
  6548. value={editingRoi.h}
  6549. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6550. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6551. />
  6552. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6553. </div>
  6554. </div>
  6555. <p className="text-xs text-bambu-gray">
  6556. {t('printers.roi.instruction')}
  6557. </p>
  6558. </div>
  6559. ) : (
  6560. <p className="text-xs text-bambu-gray">
  6561. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6562. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6563. </p>
  6564. )}
  6565. </div>
  6566. )}
  6567. </div>
  6568. <div className="flex justify-end gap-2 p-4">
  6569. {plateCheckResult.needs_calibration ? (
  6570. <>
  6571. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6572. {t('common.cancel')}
  6573. </Button>
  6574. <Button
  6575. onClick={() => handleCalibratePlate()}
  6576. disabled={isCalibrating}
  6577. >
  6578. {isCalibrating ? (
  6579. <>
  6580. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6581. Calibrating...
  6582. </>
  6583. ) : (
  6584. 'Calibrate Empty Plate'
  6585. )}
  6586. </Button>
  6587. </>
  6588. ) : (
  6589. <>
  6590. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6591. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6592. </Button>
  6593. <Button onClick={() => closePlateCheckModal()}>
  6594. Close
  6595. </Button>
  6596. </>
  6597. )}
  6598. </div>
  6599. </div>
  6600. </div>
  6601. )}
  6602. {/* Power On Confirmation */}
  6603. {showPowerOnConfirm && smartPlug && (
  6604. <ConfirmModal
  6605. title={t('printers.confirm.powerOnTitle')}
  6606. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6607. confirmText={t('printers.confirm.powerOnButton')}
  6608. variant="default"
  6609. onConfirm={() => {
  6610. powerControlMutation.mutate('on');
  6611. setShowPowerOnConfirm(false);
  6612. }}
  6613. onCancel={() => setShowPowerOnConfirm(false)}
  6614. />
  6615. )}
  6616. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6617. disconnects MQTT, which stops progress tracking + completion
  6618. notifications for the in-flight job. Idle / FINISH / FAILED states
  6619. skip this dialog and toggle directly. */}
  6620. {confirmMaintenanceEnter && (
  6621. <ConfirmModal
  6622. title={t('printers.maintenance.confirmMidPrintTitle')}
  6623. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6624. confirmText={t('printers.maintenance.menuEnter')}
  6625. variant="danger"
  6626. onConfirm={() => {
  6627. maintenanceMutation.mutate(false);
  6628. setConfirmMaintenanceEnter(false);
  6629. }}
  6630. onCancel={() => setConfirmMaintenanceEnter(false)}
  6631. />
  6632. )}
  6633. {/* Power Off Confirmation */}
  6634. {showPowerOffConfirm && smartPlug && (
  6635. <ConfirmModal
  6636. title={t('printers.confirm.powerOffTitle')}
  6637. message={
  6638. status?.state === 'RUNNING'
  6639. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6640. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6641. }
  6642. confirmText={t('printers.confirm.powerOffButton')}
  6643. variant="danger"
  6644. onConfirm={() => {
  6645. powerControlMutation.mutate('off');
  6646. setShowPowerOffConfirm(false);
  6647. }}
  6648. onCancel={() => setShowPowerOffConfirm(false)}
  6649. />
  6650. )}
  6651. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6652. {haToggleConfirm && (
  6653. <ConfirmModal
  6654. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6655. message={
  6656. status?.state === 'RUNNING'
  6657. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6658. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6659. }
  6660. confirmText={t('printers.confirm.haToggleButton')}
  6661. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6662. onConfirm={() => {
  6663. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6664. setHaToggleConfirm(null);
  6665. }}
  6666. onCancel={() => setHaToggleConfirm(null)}
  6667. />
  6668. )}
  6669. {/* Stop Print Confirmation */}
  6670. {showStopConfirm && (
  6671. <ConfirmModal
  6672. title={t('printers.confirm.stopTitle')}
  6673. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6674. confirmText={t('printers.confirm.stopButton')}
  6675. variant="danger"
  6676. onConfirm={() => {
  6677. stopPrintMutation.mutate();
  6678. setShowStopConfirm(false);
  6679. }}
  6680. onCancel={() => setShowStopConfirm(false)}
  6681. />
  6682. )}
  6683. {/* Pause Print Confirmation */}
  6684. {showPauseConfirm && (
  6685. <ConfirmModal
  6686. title={t('printers.confirm.pauseTitle')}
  6687. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6688. confirmText={t('printers.confirm.pauseButton')}
  6689. variant="default"
  6690. onConfirm={() => {
  6691. pausePrintMutation.mutate();
  6692. setShowPauseConfirm(false);
  6693. }}
  6694. onCancel={() => setShowPauseConfirm(false)}
  6695. />
  6696. )}
  6697. {/* Resume Print Confirmation */}
  6698. {showResumeConfirm && (
  6699. <ConfirmModal
  6700. title={t('printers.confirm.resumeTitle')}
  6701. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6702. confirmText={t('printers.confirm.resumeButton')}
  6703. variant="default"
  6704. onConfirm={() => {
  6705. resumePrintMutation.mutate();
  6706. setShowResumeConfirm(false);
  6707. }}
  6708. onCancel={() => setShowResumeConfirm(false)}
  6709. />
  6710. )}
  6711. {/* Skip Objects Modal */}
  6712. <SkipObjectsModal
  6713. printerId={printer.id}
  6714. isOpen={showSkipObjectsModal}
  6715. onClose={() => setShowSkipObjectsModal(false)}
  6716. />
  6717. {/* HMS Error Modal */}
  6718. {showHMSModal && (
  6719. <HMSErrorModal
  6720. printerName={printer.name}
  6721. errors={status?.hms_errors || []}
  6722. onClose={() => setShowHMSModal(false)}
  6723. printerId={printer.id}
  6724. hasPermission={hasPermission}
  6725. runoutGuidance={runoutGuidance}
  6726. />
  6727. )}
  6728. {/* AI failure detection modal (#1546) */}
  6729. {showAiModal && (
  6730. <AiDetectionModal
  6731. printerName={printer.name}
  6732. detection={aiDetection}
  6733. lastError={aiLastError}
  6734. onClose={() => setShowAiModal(false)}
  6735. />
  6736. )}
  6737. {/* AMS Filament Backup status / control modal (#1762) */}
  6738. {amsBackupModalOpen && status && (
  6739. <AmsBackupModal
  6740. isOpen={amsBackupModalOpen}
  6741. state={status.ams_filament_backup}
  6742. amsUnits={status.ams}
  6743. amsExtruderMap={status.ams_extruder_map}
  6744. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6745. canToggle={hasPermission('printers:control')}
  6746. pending={setAmsBackupMutation.isPending}
  6747. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6748. onClose={() => setAmsBackupModalOpen(false)}
  6749. />
  6750. )}
  6751. {/* AMS History Modal */}
  6752. {amsHistoryModal && (
  6753. <AMSHistoryModal
  6754. isOpen={!!amsHistoryModal}
  6755. onClose={() => setAmsHistoryModal(null)}
  6756. printerId={printer.id}
  6757. printerName={printer.name}
  6758. amsId={amsHistoryModal.amsId}
  6759. amsLabel={amsHistoryModal.amsLabel}
  6760. initialMode={amsHistoryModal.mode}
  6761. thresholds={amsThresholds}
  6762. />
  6763. )}
  6764. {/* Heater History Modal (nozzle / bed / chamber) */}
  6765. {heaterHistoryModal && (
  6766. <HeaterHistoryModal
  6767. isOpen={!!heaterHistoryModal}
  6768. onClose={() => setHeaterHistoryModal(null)}
  6769. printerId={printer.id}
  6770. printerName={printer.name}
  6771. initialKind={heaterHistoryModal.initialKind}
  6772. availableKinds={heaterHistoryModal.availableKinds}
  6773. />
  6774. )}
  6775. {/* Link Spool Modal */}
  6776. {linkSpoolModal && (
  6777. <LinkSpoolModal
  6778. isOpen={!!linkSpoolModal}
  6779. onClose={() => setLinkSpoolModal(null)}
  6780. tagUid={linkSpoolModal.tagUid}
  6781. trayUuid={linkSpoolModal.trayUuid}
  6782. printerId={linkSpoolModal.printerId}
  6783. amsId={linkSpoolModal.amsId}
  6784. trayId={linkSpoolModal.trayId}
  6785. />
  6786. )}
  6787. {/* Assign Spool Modal */}
  6788. {assignSpoolModal && (
  6789. <AssignSpoolModal
  6790. isOpen={!!assignSpoolModal}
  6791. onClose={() => setAssignSpoolModal(null)}
  6792. printerId={assignSpoolModal.printerId}
  6793. amsId={assignSpoolModal.amsId}
  6794. trayId={assignSpoolModal.trayId}
  6795. trayInfo={assignSpoolModal.trayInfo}
  6796. spoolmanEnabled={!!spoolmanEnabled}
  6797. />
  6798. )}
  6799. {/* Configure AMS Slot Modal */}
  6800. {configureSlotModal && (
  6801. <ConfigureAmsSlotModal
  6802. isOpen={!!configureSlotModal}
  6803. onClose={() => setConfigureSlotModal(null)}
  6804. printerId={printer.id}
  6805. slotInfo={configureSlotModal}
  6806. printerModel={mapModelCode(printer.model) || undefined}
  6807. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6808. onSuccess={() => {
  6809. // Refresh slot presets to show updated profile name
  6810. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6811. // Printer status will update automatically via WebSocket when AMS data changes
  6812. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6813. }}
  6814. />
  6815. )}
  6816. {/* Edit Printer Modal */}
  6817. {showEditModal && (
  6818. <EditPrinterModal
  6819. printer={printer}
  6820. onClose={() => setShowEditModal(false)}
  6821. />
  6822. )}
  6823. {/* Firmware Update Modal */}
  6824. {showFirmwareModal && firmwareInfo && (
  6825. <FirmwareUpdateModal
  6826. printer={printer}
  6827. firmwareInfo={firmwareInfo}
  6828. onClose={() => setShowFirmwareModal(false)}
  6829. />
  6830. )}
  6831. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6832. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6833. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6834. const sliderMin = 35;
  6835. const sliderMax = maxTemp + 10;
  6836. return (
  6837. <>
  6838. {/* Backdrop */}
  6839. <div
  6840. className="fixed inset-0 z-[100]"
  6841. data-testid="drying-popover-backdrop"
  6842. onMouseDown={() => {
  6843. // The click that dismisses the native datetime picker lands
  6844. // here; it must not close the popover. The input is still
  6845. // focused at mousedown, so remember that and swallow the
  6846. // matching click.
  6847. dryingBackdropSkipCloseRef.current =
  6848. dryingAtTimeInputRef.current !== null &&
  6849. document.activeElement === dryingAtTimeInputRef.current;
  6850. }}
  6851. onClick={() => {
  6852. if (dryingBackdropSkipCloseRef.current) {
  6853. dryingBackdropSkipCloseRef.current = false;
  6854. return;
  6855. }
  6856. setDryingPopoverAmsId(null);
  6857. }}
  6858. />
  6859. {/* An 'above' popover is anchored by its bottom edge (CSS
  6860. bottom) so late-appearing content grows it upward, staying on
  6861. screen and glued to the trigger. maxHeight caps to the space
  6862. on the anchored side; when the viewport is too short the body
  6863. scrolls and the footer stays pinned. dvh so iOS Safari's
  6864. bottom toolbar doesn't clip the footer. */}
  6865. <div
  6866. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6867. style={{
  6868. left: dryingPopoverPos.left,
  6869. ...(dryingPopoverPos.placement === 'above'
  6870. ? {
  6871. bottom: `calc(100dvh - ${dryingPopoverPos.anchorY}px)`,
  6872. maxHeight: `${dryingPopoverPos.anchorY - 8}px`,
  6873. }
  6874. : {
  6875. top: dryingPopoverPos.top,
  6876. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6877. }),
  6878. }}
  6879. onClick={e => e.stopPropagation()}
  6880. >
  6881. {/* Header */}
  6882. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6883. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  6884. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6885. </div>
  6886. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6887. {/* Body */}
  6888. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6889. {/* Filament type select */}
  6890. <div>
  6891. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6892. <ToolbarDropdown
  6893. value={dryingFilament}
  6894. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6895. onChange={fil => {
  6896. setDryingFilament(fil);
  6897. const preset = dryingPresets[fil];
  6898. if (preset) {
  6899. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6900. setDryingTemp(preset[key]);
  6901. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6902. }
  6903. }}
  6904. fullWidth
  6905. />
  6906. </div>
  6907. {/* Temperature */}
  6908. <div>
  6909. <div className="flex items-center justify-between mb-1">
  6910. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6911. <div className="flex items-center gap-1">
  6912. <input
  6913. type="number"
  6914. min={45}
  6915. max={maxTemp}
  6916. value={dryingTemp}
  6917. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6918. 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"
  6919. />
  6920. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  6921. </div>
  6922. </div>
  6923. <input
  6924. type="range"
  6925. min={sliderMin}
  6926. max={sliderMax}
  6927. value={dryingTemp}
  6928. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6929. className="w-full h-1 accent-bambu-green cursor-pointer"
  6930. />
  6931. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6932. <span>45°C</span>
  6933. <span>{maxTemp}°C</span>
  6934. </div>
  6935. </div>
  6936. {/* Duration */}
  6937. <div>
  6938. <div className="flex items-center justify-between mb-1">
  6939. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6940. <div className="flex items-center gap-1">
  6941. <input
  6942. type="number"
  6943. min={1}
  6944. max={24}
  6945. value={dryingDuration}
  6946. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6947. 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"
  6948. />
  6949. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  6950. </div>
  6951. </div>
  6952. <input
  6953. type="range"
  6954. min={1}
  6955. max={24}
  6956. value={dryingDuration}
  6957. onChange={e => setDryingDuration(Number(e.target.value))}
  6958. className="w-full h-1 accent-bambu-green cursor-pointer"
  6959. />
  6960. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6961. <span>1h</span>
  6962. <span>24h</span>
  6963. </div>
  6964. </div>
  6965. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6966. filament threaded out into the feed tube. The whole AMS
  6967. rotates as one mechanism (all 4 spools turn together), so a
  6968. single loaded slot locks the entire unit. Bambu per-tray
  6969. `state`: 9 = empty, 10 = spool present but not loaded
  6970. (rotation possible), 11 = loaded into tube (rotation impossible).
  6971. Catches both mid-print (active feed) AND idle-with-threaded-
  6972. filament — the H2D's post-print state leaves filament in the
  6973. tube but tray_now resets to 255, which a tray_now-only check
  6974. would silently miss. */}
  6975. {(() => {
  6976. const targetAms = dryingPopoverAmsId !== null
  6977. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6978. : undefined;
  6979. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6980. tray => tray.state === 11,
  6981. );
  6982. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6983. return (
  6984. <button
  6985. type="button"
  6986. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6987. aria-pressed={rotateChecked}
  6988. disabled={trayLoadedInThisAms}
  6989. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6990. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6991. rotateChecked
  6992. ? 'bg-bambu-green border-bambu-green text-white'
  6993. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6994. }`}
  6995. >
  6996. {t('printers.drying.rotateTray')}
  6997. </button>
  6998. );
  6999. })()}
  7000. {/* Start mode: now / after delay / at time (#2638) */}
  7001. <div>
  7002. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.drying.startMode')}</label>
  7003. <div className="grid grid-cols-3 gap-1">
  7004. {(['now', 'delay', 'at_time'] as const).map(mode => (
  7005. <button
  7006. key={mode}
  7007. type="button"
  7008. onClick={() => setDryingStartMode(mode)}
  7009. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7010. dryingStartMode === mode
  7011. ? 'bg-bambu-green border-bambu-green text-white'
  7012. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7013. }`}
  7014. >
  7015. {t(mode === 'now' ? 'printers.drying.modeNow' : mode === 'delay' ? 'printers.drying.modeDelay' : 'printers.drying.modeAtTime')}
  7016. </button>
  7017. ))}
  7018. </div>
  7019. {dryingStartMode === 'delay' && (
  7020. // Inline chips: a dropdown menu would be clipped by
  7021. // the popover's scrollable body.
  7022. <div className="mt-1.5 grid grid-cols-4 gap-1">
  7023. {DRYING_DELAY_OPTIONS.map(min => (
  7024. <button
  7025. key={min}
  7026. type="button"
  7027. aria-pressed={dryingDelayMinutes === min}
  7028. onClick={() => setDryingDelayMinutes(min)}
  7029. className={`py-1 rounded-lg border text-[10px] font-medium transition-colors ${
  7030. dryingDelayMinutes === min
  7031. ? 'bg-bambu-green border-bambu-green text-white'
  7032. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  7033. }`}
  7034. >
  7035. {formatDurationFromHours(min / 60)}
  7036. </button>
  7037. ))}
  7038. </div>
  7039. )}
  7040. {dryingStartMode === 'at_time' && (
  7041. <input
  7042. ref={dryingAtTimeInputRef}
  7043. type="datetime-local"
  7044. data-testid="drying-start-at"
  7045. value={dryingStartAt}
  7046. onChange={e => setDryingStartAt(e.target.value)}
  7047. 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]"
  7048. />
  7049. )}
  7050. </div>
  7051. </div>
  7052. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  7053. {/* Footer */}
  7054. <div className="shrink-0 px-3 pt-2.5 pb-3">
  7055. <button
  7056. onClick={() => {
  7057. if (dryingPopoverAmsId !== null) {
  7058. // Clamp rotateTray off when any tray in this AMS is loaded into
  7059. // the tube — the rotate UI is disabled there, but the state may
  7060. // linger as `true` from a previous AMS, or a print may have
  7061. // started while the popover was open. Without this clamp the
  7062. // Start payload would carry rotate_tray=true and firmware would
  7063. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  7064. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  7065. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  7066. tray => tray.state === 11,
  7067. );
  7068. const rotate = dryingRotateTray && !trayLoadedInThisAms;
  7069. if (dryingStartMode === 'now') {
  7070. startDryingMutation.mutate({
  7071. amsId: dryingPopoverAmsId,
  7072. temp: dryingTemp,
  7073. duration: dryingDuration,
  7074. filament: dryingFilament,
  7075. rotateTray: rotate,
  7076. });
  7077. } else {
  7078. const startAfter = computeStartAfter(dryingStartMode, dryingDelayMinutes, dryingStartAt);
  7079. if (startAfter) {
  7080. scheduleDryingMutation.mutate({
  7081. amsId: dryingPopoverAmsId,
  7082. temp: dryingTemp,
  7083. duration: dryingDuration,
  7084. filament: dryingFilament,
  7085. rotateTray: rotate,
  7086. startAfter,
  7087. });
  7088. }
  7089. }
  7090. }
  7091. }}
  7092. disabled={startDryingMutation.isPending || scheduleDryingMutation.isPending || (dryingStartMode === 'at_time' && !dryingStartAt)}
  7093. data-testid="drying-start-confirm"
  7094. 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"
  7095. >
  7096. {dryingStartMode === 'now'
  7097. ? (startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start'))
  7098. : t('printers.drying.schedule')}
  7099. </button>
  7100. </div>
  7101. </div>
  7102. {/* Anchor arrow pointing at the flame button; a fixed sibling
  7103. since the popover clips its own overflow. */}
  7104. <div
  7105. className="fixed z-[102] w-2.5 h-2.5 rotate-45 bg-bambu-dark-secondary border-bambu-dark-tertiary pointer-events-none"
  7106. style={{
  7107. left: dryingPopoverPos.left + dryingPopoverPos.arrowLeft - 5,
  7108. top: dryingPopoverPos.anchorY - 5,
  7109. ...(dryingPopoverPos.placement === 'above'
  7110. ? { borderRightWidth: 1, borderBottomWidth: 1 }
  7111. : { borderLeftWidth: 1, borderTopWidth: 1 }),
  7112. }}
  7113. />
  7114. </>
  7115. );
  7116. })()}
  7117. </Card>
  7118. );
  7119. }
  7120. export function AddPrinterModal({
  7121. onClose,
  7122. onAdd,
  7123. existingSerials,
  7124. }: {
  7125. onClose: () => void;
  7126. onAdd: (data: PrinterCreate) => void;
  7127. existingSerials: string[];
  7128. }) {
  7129. const { t } = useTranslation();
  7130. const [form, setForm] = useState<PrinterCreate>({
  7131. name: '',
  7132. serial_number: '',
  7133. ip_address: '',
  7134. access_code: '',
  7135. model: '',
  7136. location: '',
  7137. auto_archive: true,
  7138. });
  7139. // Discovery state
  7140. const [discovering, setDiscovering] = useState(false);
  7141. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  7142. const [discoveryError, setDiscoveryError] = useState('');
  7143. const [hasScanned, setHasScanned] = useState(false);
  7144. const [isDocker, setIsDocker] = useState(false);
  7145. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  7146. const [subnet, setSubnet] = useState('');
  7147. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  7148. // text input so users can scan a subnet Bambuddy isn't directly on
  7149. // (printer behind a router on a different L3 segment — SSDP multicast
  7150. // won't cross that boundary, only an active unicast scan will). #1564
  7151. const [customSubnet, setCustomSubnet] = useState('');
  7152. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  7153. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  7154. const [showDiagnostic, setShowDiagnostic] = useState(false);
  7155. // Setup-time pre-flight: run the connection diagnostic on save and warn
  7156. // (not block) when checks fail, so the user doesn't add a printer that
  7157. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  7158. // failed result awaiting an explicit "save anyway".
  7159. const [checkingSave, setCheckingSave] = useState(false);
  7160. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7161. // Fetch discovery info on mount + restore the last custom CIDR the user
  7162. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  7163. // time they open this modal).
  7164. useEffect(() => {
  7165. discoveryApi.getInfo().then(info => {
  7166. setIsDocker(info.is_docker);
  7167. if (info.subnets.length > 0) {
  7168. setDetectedSubnets(info.subnets);
  7169. setSubnet(info.subnets[0]);
  7170. }
  7171. }).catch(() => {
  7172. // Ignore errors, assume not Docker
  7173. });
  7174. try {
  7175. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  7176. if (saved) setCustomSubnet(saved);
  7177. } catch {
  7178. // localStorage unavailable (private mode, quota); recall is opportunistic
  7179. }
  7180. }, []);
  7181. // Filter out already-added printers
  7182. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  7183. const handleAddSubmit = async (e: React.FormEvent) => {
  7184. e.preventDefault();
  7185. setCheckingSave(true);
  7186. try {
  7187. const result = await api.diagnoseConnection({
  7188. ip_address: form.ip_address.trim(),
  7189. serial_number: form.serial_number.trim() || undefined,
  7190. access_code: form.access_code || undefined,
  7191. });
  7192. if (result.checks.some((c) => c.status === 'fail')) {
  7193. setSaveWarning(result);
  7194. return;
  7195. }
  7196. } catch {
  7197. // Diagnostic infrastructure failed — never block the save on it.
  7198. } finally {
  7199. setCheckingSave(false);
  7200. }
  7201. onAdd(form);
  7202. };
  7203. const startDiscovery = async () => {
  7204. setDiscoveryError('');
  7205. setDiscovered([]);
  7206. setDiscovering(true);
  7207. setHasScanned(false);
  7208. setScanProgress({ scanned: 0, total: 0 });
  7209. // Native installs fall back to subnet scanning when the user picks
  7210. // "Custom" — SSDP can't reach a printer on a different L3 segment
  7211. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  7212. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  7213. const wantsSubnetScan = isDocker || useCustomSubnet;
  7214. if (wantsSubnetScan && useCustomSubnet) {
  7215. try {
  7216. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  7217. } catch {
  7218. // localStorage write best-effort; user just retypes next time
  7219. }
  7220. }
  7221. try {
  7222. if (wantsSubnetScan) {
  7223. await discoveryApi.startSubnetScan(scanCidr);
  7224. // Poll for scan status and results
  7225. const pollInterval = setInterval(async () => {
  7226. try {
  7227. const status = await discoveryApi.getScanStatus();
  7228. setScanProgress({ scanned: status.scanned, total: status.total });
  7229. const printers = await discoveryApi.getDiscoveredPrinters();
  7230. setDiscovered(printers);
  7231. if (!status.running) {
  7232. clearInterval(pollInterval);
  7233. setDiscovering(false);
  7234. setHasScanned(true);
  7235. }
  7236. } catch (e) {
  7237. console.error('Failed to get scan status:', e);
  7238. }
  7239. }, 500);
  7240. } else {
  7241. // Use SSDP discovery for native installs
  7242. await discoveryApi.startDiscovery(10);
  7243. // Poll for discovered printers every second
  7244. const pollInterval = setInterval(async () => {
  7245. try {
  7246. const printers = await discoveryApi.getDiscoveredPrinters();
  7247. setDiscovered(printers);
  7248. } catch (e) {
  7249. console.error('Failed to get discovered printers:', e);
  7250. }
  7251. }, 1000);
  7252. // Stop after 10 seconds
  7253. setTimeout(async () => {
  7254. clearInterval(pollInterval);
  7255. try {
  7256. await discoveryApi.stopDiscovery();
  7257. } catch {
  7258. // Ignore stop errors
  7259. }
  7260. setDiscovering(false);
  7261. setHasScanned(true);
  7262. // Final fetch
  7263. try {
  7264. const printers = await discoveryApi.getDiscoveredPrinters();
  7265. setDiscovered(printers);
  7266. } catch (e) {
  7267. console.error('Failed to get final discovered printers:', e);
  7268. }
  7269. }, 10000);
  7270. }
  7271. } catch (e) {
  7272. console.error('Failed to start discovery:', e);
  7273. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  7274. setDiscovering(false);
  7275. setHasScanned(true);
  7276. }
  7277. };
  7278. // Reuse module-level mapModelCode
  7279. const selectPrinter = (printer: DiscoveredPrinter) => {
  7280. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  7281. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  7282. setForm({
  7283. ...form,
  7284. name: printer.name || '',
  7285. serial_number: serialNumber,
  7286. ip_address: printer.ip_address,
  7287. model: mapModelCode(printer.model),
  7288. });
  7289. // Clear discovery results after selection
  7290. setDiscovered([]);
  7291. };
  7292. // Cleanup discovery on unmount
  7293. useEffect(() => {
  7294. return () => {
  7295. discoveryApi.stopDiscovery().catch(() => {});
  7296. discoveryApi.stopSubnetScan().catch(() => {});
  7297. };
  7298. }, []);
  7299. // Close on Escape key
  7300. useEffect(() => {
  7301. const handleKeyDown = (e: KeyboardEvent) => {
  7302. if (e.key === 'Escape') onClose();
  7303. };
  7304. window.addEventListener('keydown', handleKeyDown);
  7305. return () => window.removeEventListener('keydown', handleKeyDown);
  7306. }, [onClose]);
  7307. return (
  7308. <>
  7309. <div
  7310. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7311. onClick={onClose}
  7312. >
  7313. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7314. <CardContent>
  7315. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  7316. {/* Discovery Section */}
  7317. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  7318. {/* Subnet picker — always visible. The dropdown lists detected
  7319. interface subnets and a "Custom..." sentinel that reveals
  7320. a CIDR text input for printers on a different L3 segment
  7321. (router, VLAN, etc.). #1564 */}
  7322. <div className="mb-3">
  7323. <label className="block text-sm text-bambu-gray mb-1">
  7324. {t('printers.discovery.subnetToScan')}
  7325. </label>
  7326. {detectedSubnets.length > 0 ? (
  7327. <select
  7328. 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"
  7329. value={useCustomSubnet ? '__custom__' : subnet}
  7330. onChange={(e) => {
  7331. if (e.target.value === '__custom__') {
  7332. setUseCustomSubnet(true);
  7333. } else {
  7334. setUseCustomSubnet(false);
  7335. setSubnet(e.target.value);
  7336. }
  7337. }}
  7338. disabled={discovering}
  7339. >
  7340. {detectedSubnets.map(s => (
  7341. <option key={s} value={s}>{s}</option>
  7342. ))}
  7343. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  7344. </select>
  7345. ) : (
  7346. <input
  7347. type="text"
  7348. 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"
  7349. value={subnet}
  7350. onChange={(e) => setSubnet(e.target.value)}
  7351. placeholder="192.168.1.0/24"
  7352. disabled={discovering}
  7353. />
  7354. )}
  7355. {useCustomSubnet && (
  7356. <input
  7357. type="text"
  7358. aria-label={t('printers.discovery.customSubnetLabel')}
  7359. 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"
  7360. value={customSubnet}
  7361. onChange={(e) => setCustomSubnet(e.target.value)}
  7362. placeholder="10.1.1.0/24"
  7363. disabled={discovering}
  7364. />
  7365. )}
  7366. <p className="mt-1 text-xs text-bambu-gray">
  7367. {isDocker
  7368. ? t('printers.discovery.dockerNote')
  7369. : t('printers.discovery.customSubnetNote')}
  7370. </p>
  7371. </div>
  7372. <Button
  7373. type="button"
  7374. variant="secondary"
  7375. onClick={startDiscovery}
  7376. disabled={discovering}
  7377. className="w-full"
  7378. >
  7379. {discovering ? (
  7380. <>
  7381. <Loader2 className="w-4 h-4 animate-spin" />
  7382. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  7383. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  7384. : t('printers.discovery.scanning')}
  7385. </>
  7386. ) : (
  7387. <>
  7388. <Search className="w-4 h-4" />
  7389. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  7390. </>
  7391. )}
  7392. </Button>
  7393. {discoveryError && (
  7394. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  7395. )}
  7396. {newPrinters.length > 0 && (
  7397. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  7398. {newPrinters.map((printer) => (
  7399. <div
  7400. key={printer.serial}
  7401. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  7402. onClick={() => selectPrinter(printer)}
  7403. >
  7404. <div className="min-w-0 flex-1">
  7405. <p className="font-medium text-white text-sm truncate">
  7406. {printer.name || printer.serial}
  7407. </p>
  7408. <p className="text-xs text-bambu-gray truncate">
  7409. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  7410. {printer.serial.startsWith('unknown-') && (
  7411. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  7412. )}
  7413. </p>
  7414. </div>
  7415. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  7416. </div>
  7417. ))}
  7418. </div>
  7419. )}
  7420. {discovering && (
  7421. <p className="mt-2 text-sm text-bambu-gray text-center">
  7422. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  7423. </p>
  7424. )}
  7425. {hasScanned && !discovering && discovered.length === 0 && (
  7426. <p className="mt-2 text-sm text-bambu-gray text-center">
  7427. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  7428. </p>
  7429. )}
  7430. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  7431. <p className="mt-2 text-sm text-bambu-gray text-center">
  7432. {t('printers.discovery.allConfigured')}
  7433. </p>
  7434. )}
  7435. </div>
  7436. <form onSubmit={handleAddSubmit} className="space-y-4">
  7437. <div>
  7438. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7439. <input
  7440. type="text"
  7441. required
  7442. 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"
  7443. value={form.name}
  7444. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7445. placeholder={t('printers.modal.myPrinter')}
  7446. />
  7447. </div>
  7448. <div>
  7449. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7450. <input
  7451. type="text"
  7452. required
  7453. 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])?)*)"
  7454. 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"
  7455. value={form.ip_address}
  7456. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7457. placeholder="192.168.1.100 or printer.local"
  7458. />
  7459. </div>
  7460. <div>
  7461. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7462. <input
  7463. type="text"
  7464. required
  7465. 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"
  7466. value={form.serial_number}
  7467. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  7468. placeholder="01P00A000000000"
  7469. />
  7470. </div>
  7471. <div>
  7472. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7473. <input
  7474. type="password"
  7475. required
  7476. 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"
  7477. value={form.access_code}
  7478. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7479. placeholder={t('printers.modal.fromPrinterSettings')}
  7480. />
  7481. </div>
  7482. <div>
  7483. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7484. <select
  7485. 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"
  7486. value={form.model || ''}
  7487. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7488. >
  7489. <option value="">{t('printers.modal.selectModel')}</option>
  7490. <optgroup label="A1 Series">
  7491. <option value="A1">A1</option>
  7492. <option value="A1 Mini">A1 Mini</option>
  7493. </optgroup>
  7494. <optgroup label="A2 Series">
  7495. <option value="A2L">A2L</option>
  7496. </optgroup>
  7497. <optgroup label="H2 Series">
  7498. <option value="H2C">H2C</option>
  7499. <option value="H2D">H2D</option>
  7500. <option value="H2D Pro">H2D Pro</option>
  7501. <option value="H2S">H2S</option>
  7502. </optgroup>
  7503. <optgroup label="P Series">
  7504. <option value="P1P">P1P</option>
  7505. <option value="P1S">P1S</option>
  7506. <option value="P2S">P2S</option>
  7507. </optgroup>
  7508. <optgroup label="X1 Series">
  7509. <option value="X1">X1</option>
  7510. <option value="X1C">X1 Carbon</option>
  7511. <option value="X1E">X1E</option>
  7512. </optgroup>
  7513. <optgroup label="X2 Series">
  7514. <option value="X2D">X2D</option>
  7515. </optgroup>
  7516. </select>
  7517. </div>
  7518. <div>
  7519. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7520. <input
  7521. type="text"
  7522. 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"
  7523. value={form.location || ''}
  7524. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7525. placeholder={t('printers.modal.locationPlaceholder')}
  7526. />
  7527. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7528. </div>
  7529. <div className="flex items-center gap-2">
  7530. <input
  7531. type="checkbox"
  7532. id="auto_archive"
  7533. checked={form.auto_archive}
  7534. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7535. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7536. />
  7537. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7538. {t('printers.modal.autoArchiveLabel')}
  7539. </label>
  7540. </div>
  7541. <button
  7542. type="button"
  7543. onClick={() => setShowDiagnostic(true)}
  7544. disabled={!form.ip_address.trim()}
  7545. 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"
  7546. >
  7547. <Stethoscope className="w-4 h-4" />
  7548. {t('diagnostic.runButton')}
  7549. </button>
  7550. {saveWarning ? (
  7551. <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">
  7552. <div className="flex items-start gap-2">
  7553. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7554. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7555. </div>
  7556. <DiagnosticChecklist result={saveWarning} />
  7557. <div className="flex gap-3">
  7558. <Button
  7559. type="button"
  7560. variant="secondary"
  7561. onClick={() => setSaveWarning(null)}
  7562. className="flex-1"
  7563. >
  7564. {t('printers.addPreflight.back')}
  7565. </Button>
  7566. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7567. {t('printers.addPreflight.saveAnyway')}
  7568. </Button>
  7569. </div>
  7570. </div>
  7571. ) : (
  7572. <div className="flex gap-3 pt-2">
  7573. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7574. {t('common.cancel')}
  7575. </Button>
  7576. <Button type="submit" disabled={checkingSave} className="flex-1">
  7577. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7578. </Button>
  7579. </div>
  7580. )}
  7581. </form>
  7582. </CardContent>
  7583. </Card>
  7584. </div>
  7585. {showDiagnostic && (
  7586. <ConnectionDiagnosticModal
  7587. connection={{
  7588. ip_address: form.ip_address.trim(),
  7589. serial_number: form.serial_number.trim() || undefined,
  7590. access_code: form.access_code || undefined,
  7591. }}
  7592. printerName={form.name || null}
  7593. onClose={() => setShowDiagnostic(false)}
  7594. />
  7595. )}
  7596. </>
  7597. );
  7598. }
  7599. function FirmwareUpdateModal({
  7600. printer,
  7601. firmwareInfo,
  7602. onClose,
  7603. }: {
  7604. printer: Printer;
  7605. firmwareInfo: FirmwareUpdateInfo;
  7606. onClose: () => void;
  7607. }) {
  7608. const { t } = useTranslation();
  7609. const queryClient = useQueryClient();
  7610. const { showToast } = useToast();
  7611. const { hasPermission } = useAuth();
  7612. const canUpdate = hasPermission('firmware:update');
  7613. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7614. const [isUploading, setIsUploading] = useState(false);
  7615. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7616. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7617. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7618. );
  7619. // Prepare check query — runs when a version is selected and user can update
  7620. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7621. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7622. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7623. staleTime: 30000,
  7624. enabled: !!selectedVersion && canUpdate && !isUploading,
  7625. });
  7626. // Start upload mutation
  7627. const uploadMutation = useMutation({
  7628. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7629. onSuccess: () => {
  7630. setIsUploading(true);
  7631. // Start polling for status
  7632. const interval = setInterval(async () => {
  7633. try {
  7634. const status = await firmwareApi.getUploadStatus(printer.id);
  7635. setUploadStatus(status);
  7636. if (status.status === 'complete' || status.status === 'error') {
  7637. clearInterval(interval);
  7638. setPollInterval(null);
  7639. setIsUploading(false);
  7640. if (status.status === 'complete') {
  7641. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7642. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7643. }
  7644. }
  7645. } catch {
  7646. // Ignore errors during polling
  7647. }
  7648. }, 2000);
  7649. setPollInterval(interval);
  7650. },
  7651. onError: (error: Error) => {
  7652. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7653. setIsUploading(false);
  7654. },
  7655. });
  7656. // Cleanup on unmount
  7657. useEffect(() => {
  7658. return () => {
  7659. if (pollInterval) clearInterval(pollInterval);
  7660. };
  7661. }, [pollInterval]);
  7662. const handleStartUpload = () => {
  7663. setUploadStatus(null);
  7664. uploadMutation.mutate();
  7665. };
  7666. return (
  7667. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7668. <Card className="w-full max-w-md mx-4">
  7669. <CardContent>
  7670. <div className="flex items-start gap-3 mb-4">
  7671. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7672. {firmwareInfo.update_available
  7673. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7674. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7675. </div>
  7676. <div className="flex-1">
  7677. <h3 className="text-lg font-semibold text-white">
  7678. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7679. </h3>
  7680. <p className="text-sm text-bambu-gray mt-1">
  7681. {printer.name}
  7682. </p>
  7683. </div>
  7684. </div>
  7685. {/* Version Info */}
  7686. {(() => {
  7687. const selectedEntry = selectedVersion
  7688. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7689. : null;
  7690. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7691. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7692. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7693. return (
  7694. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7695. <div className="flex justify-between items-center text-sm">
  7696. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7697. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7698. {firmwareInfo.current_version || t('common.unknown')}
  7699. </span>
  7700. </div>
  7701. {showSecondLine && (
  7702. <div className="flex justify-between items-center text-sm mt-1">
  7703. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7704. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7705. </div>
  7706. )}
  7707. {displayNotes && (
  7708. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7709. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7710. {t('printers.firmwareModal.releaseNotes')}
  7711. </summary>
  7712. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7713. {displayNotes}
  7714. </div>
  7715. </details>
  7716. )}
  7717. </div>
  7718. );
  7719. })()}
  7720. {/* Available versions list */}
  7721. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7722. <div className="mb-4">
  7723. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7724. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7725. {firmwareInfo.available_versions.map((v) => {
  7726. const isCurrent = firmwareInfo.current_version === v.version;
  7727. const isSelected = selectedVersion === v.version;
  7728. const cmp = firmwareInfo.current_version
  7729. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7730. : 0;
  7731. const relLabel = isCurrent
  7732. ? t('printers.firmwareModal.currentBadge')
  7733. : cmp > 0
  7734. ? t('printers.firmwareModal.newerBadge')
  7735. : t('printers.firmwareModal.olderBadge');
  7736. const relClass = isCurrent
  7737. ? 'text-bambu-gray'
  7738. : cmp > 0
  7739. ? 'text-orange-700 dark:text-orange-400'
  7740. : 'text-blue-700 dark:text-blue-400';
  7741. return (
  7742. <button
  7743. key={v.version}
  7744. type="button"
  7745. disabled={!v.file_available || !canUpdate || isCurrent}
  7746. onClick={() => setSelectedVersion(v.version)}
  7747. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7748. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7749. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7750. >
  7751. <div className="flex items-center gap-2 min-w-0">
  7752. <span className="font-mono text-white">{v.version}</span>
  7753. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7754. </div>
  7755. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7756. isCurrent
  7757. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7758. : v.file_available
  7759. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7760. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7761. }`}>
  7762. {isCurrent
  7763. ? t('printers.firmwareModal.installed')
  7764. : v.file_available
  7765. ? t('printers.firmwareModal.usable')
  7766. : t('printers.firmwareModal.unavailable')}
  7767. </span>
  7768. </button>
  7769. );
  7770. })}
  7771. </div>
  7772. </div>
  7773. )}
  7774. {/* Status / Progress (only when a version is selected) */}
  7775. {!selectedVersion ? null : isPreparing ? (
  7776. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7777. <Loader2 className="w-4 h-4 animate-spin" />
  7778. {t('printers.firmwareModal.checkingPrereqs')}
  7779. </div>
  7780. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7781. <div className="mb-4">
  7782. {prepareInfo.can_proceed ? (
  7783. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7784. <Box className="w-4 h-4" />
  7785. {t('printers.firmwareModal.sdCardReady')}
  7786. </div>
  7787. ) : (
  7788. <div className="space-y-1">
  7789. {prepareInfo.errors.map((error, i) => (
  7790. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7791. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7792. {error}
  7793. </div>
  7794. ))}
  7795. </div>
  7796. )}
  7797. </div>
  7798. ) : null}
  7799. {/* Upload Progress */}
  7800. {(isUploading || uploadStatus) && uploadStatus && (
  7801. <div className="mb-4">
  7802. <div className="flex items-center justify-between text-sm mb-1">
  7803. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  7804. <span className="text-white">{uploadStatus.progress}%</span>
  7805. </div>
  7806. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  7807. <div
  7808. className={`h-2 rounded-full transition-all ${
  7809. uploadStatus.status === 'error' ? 'bg-status-error' :
  7810. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  7811. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  7812. style={{ width: `${uploadStatus.progress}%` }}
  7813. />
  7814. </div>
  7815. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  7816. {uploadStatus.error && (
  7817. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  7818. )}
  7819. </div>
  7820. )}
  7821. {/* Success Message */}
  7822. {uploadStatus?.status === 'complete' && (
  7823. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  7824. <p className="text-sm text-bambu-green font-medium mb-2">
  7825. {t('printers.firmwareModal.uploadedSuccess')}
  7826. </p>
  7827. <p className="text-xs text-bambu-gray">
  7828. {t('printers.firmwareModal.applyInstructions')}
  7829. </p>
  7830. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  7831. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  7832. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  7833. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  7834. <li>{t('printers.firmwareModal.step4')}</li>
  7835. </ol>
  7836. </div>
  7837. )}
  7838. {/* Buttons */}
  7839. <div className="flex gap-2 justify-end">
  7840. <Button variant="secondary" onClick={onClose}>
  7841. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  7842. </Button>
  7843. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  7844. <Button
  7845. onClick={handleStartUpload}
  7846. disabled={uploadMutation.isPending}
  7847. >
  7848. {uploadMutation.isPending ? (
  7849. <>
  7850. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  7851. {t('printers.firmwareModal.starting')}
  7852. </>
  7853. ) : (
  7854. <>
  7855. <Download className="w-4 h-4 mr-2" />
  7856. {t('printers.firmwareModal.uploadFirmware')}
  7857. </>
  7858. )}
  7859. </Button>
  7860. )}
  7861. </div>
  7862. </CardContent>
  7863. </Card>
  7864. </div>
  7865. );
  7866. }
  7867. function EditPrinterModal({
  7868. printer,
  7869. onClose,
  7870. }: {
  7871. printer: Printer;
  7872. onClose: () => void;
  7873. }) {
  7874. const { t } = useTranslation();
  7875. const queryClient = useQueryClient();
  7876. const { showToast } = useToast();
  7877. const [form, setForm] = useState({
  7878. name: printer.name,
  7879. ip_address: printer.ip_address,
  7880. access_code: '',
  7881. model: printer.model || '',
  7882. location: printer.location || '',
  7883. auto_archive: printer.auto_archive,
  7884. is_active: printer.is_active,
  7885. });
  7886. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7887. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7888. const [checkingSave, setCheckingSave] = useState(false);
  7889. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7890. const updateMutation = useMutation({
  7891. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7892. onSuccess: () => {
  7893. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7894. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7895. onClose();
  7896. },
  7897. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7898. });
  7899. // Close on Escape key
  7900. useEffect(() => {
  7901. const handleKeyDown = (e: KeyboardEvent) => {
  7902. if (e.key === 'Escape') onClose();
  7903. };
  7904. window.addEventListener('keydown', handleKeyDown);
  7905. return () => window.removeEventListener('keydown', handleKeyDown);
  7906. }, [onClose]);
  7907. const doSave = () => {
  7908. const data: Partial<PrinterCreate> = {
  7909. name: form.name,
  7910. ip_address: form.ip_address,
  7911. model: form.model || undefined,
  7912. location: form.location || undefined,
  7913. auto_archive: form.auto_archive,
  7914. is_active: form.is_active,
  7915. };
  7916. // Only include access_code if it was changed
  7917. if (form.access_code) {
  7918. data.access_code = form.access_code;
  7919. }
  7920. updateMutation.mutate(data);
  7921. };
  7922. const handleSubmit = async (e: React.FormEvent) => {
  7923. e.preventDefault();
  7924. setCheckingSave(true);
  7925. try {
  7926. const result = await api.diagnoseConnection({
  7927. ip_address: form.ip_address.trim(),
  7928. serial_number: printer.serial_number,
  7929. access_code: form.access_code || undefined,
  7930. });
  7931. if (result.checks.some((c) => c.status === 'fail')) {
  7932. setSaveWarning(result);
  7933. return;
  7934. }
  7935. } catch {
  7936. // Diagnostic infrastructure failed — never block the save on it.
  7937. } finally {
  7938. setCheckingSave(false);
  7939. }
  7940. doSave();
  7941. };
  7942. return (
  7943. <div
  7944. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7945. onClick={onClose}
  7946. >
  7947. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7948. <CardContent>
  7949. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7950. <form onSubmit={handleSubmit} className="space-y-4">
  7951. <div>
  7952. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7953. <input
  7954. type="text"
  7955. required
  7956. 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"
  7957. value={form.name}
  7958. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7959. placeholder={t('printers.modal.myPrinter')}
  7960. />
  7961. </div>
  7962. <div>
  7963. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7964. <input
  7965. type="text"
  7966. required
  7967. 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])?)*)"
  7968. 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"
  7969. value={form.ip_address}
  7970. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7971. placeholder="192.168.1.100 or printer.local"
  7972. />
  7973. </div>
  7974. <div>
  7975. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7976. <input
  7977. type="text"
  7978. disabled
  7979. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7980. value={printer.serial_number}
  7981. />
  7982. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7983. </div>
  7984. <div>
  7985. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7986. <input
  7987. type="password"
  7988. 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"
  7989. value={form.access_code}
  7990. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7991. placeholder={t('printers.accessCodePlaceholder')}
  7992. />
  7993. </div>
  7994. <div>
  7995. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7996. <select
  7997. 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"
  7998. value={form.model}
  7999. onChange={(e) => setForm({ ...form, model: e.target.value })}
  8000. >
  8001. <option value="">{t('printers.modal.selectModel')}</option>
  8002. <optgroup label="A1 Series">
  8003. <option value="A1">A1</option>
  8004. <option value="A1 Mini">A1 Mini</option>
  8005. </optgroup>
  8006. <optgroup label="A2 Series">
  8007. <option value="A2L">A2L</option>
  8008. </optgroup>
  8009. <optgroup label="H2 Series">
  8010. <option value="H2C">H2C</option>
  8011. <option value="H2D">H2D</option>
  8012. <option value="H2D Pro">H2D Pro</option>
  8013. <option value="H2S">H2S</option>
  8014. </optgroup>
  8015. <optgroup label="P Series">
  8016. <option value="P1P">P1P</option>
  8017. <option value="P1S">P1S</option>
  8018. <option value="P2S">P2S</option>
  8019. </optgroup>
  8020. <optgroup label="X1 Series">
  8021. <option value="X1">X1</option>
  8022. <option value="X1C">X1 Carbon</option>
  8023. <option value="X1E">X1E</option>
  8024. </optgroup>
  8025. <optgroup label="X2 Series">
  8026. <option value="X2D">X2D</option>
  8027. </optgroup>
  8028. </select>
  8029. </div>
  8030. <div>
  8031. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  8032. <input
  8033. type="text"
  8034. 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"
  8035. value={form.location}
  8036. onChange={(e) => setForm({ ...form, location: e.target.value })}
  8037. placeholder={t('printers.modal.locationPlaceholder')}
  8038. />
  8039. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  8040. </div>
  8041. <div className="flex items-center gap-2">
  8042. <input
  8043. type="checkbox"
  8044. id="edit_auto_archive"
  8045. checked={form.auto_archive}
  8046. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  8047. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  8048. />
  8049. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  8050. {t('printers.modal.autoArchiveLabel')}
  8051. </label>
  8052. </div>
  8053. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  8054. is_active because the user-facing concept is "is this printer
  8055. in maintenance" not "is it active". */}
  8056. <div>
  8057. <div className="flex items-center gap-2">
  8058. <input
  8059. type="checkbox"
  8060. id="edit_maintenance_mode"
  8061. checked={!form.is_active}
  8062. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  8063. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  8064. />
  8065. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  8066. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  8067. {t('printers.maintenance.editFieldLabel')}
  8068. </label>
  8069. </div>
  8070. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  8071. {t('printers.maintenance.editFieldHelp')}
  8072. </p>
  8073. </div>
  8074. {saveWarning ? (
  8075. <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">
  8076. <div className="flex items-start gap-2">
  8077. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  8078. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  8079. </div>
  8080. <DiagnosticChecklist result={saveWarning} />
  8081. <div className="flex gap-3">
  8082. <Button
  8083. type="button"
  8084. variant="secondary"
  8085. onClick={() => setSaveWarning(null)}
  8086. className="flex-1"
  8087. >
  8088. {t('printers.addPreflight.back')}
  8089. </Button>
  8090. <Button
  8091. type="button"
  8092. onClick={doSave}
  8093. className="flex-1"
  8094. disabled={updateMutation.isPending}
  8095. >
  8096. {t('printers.addPreflight.saveAnyway')}
  8097. </Button>
  8098. </div>
  8099. </div>
  8100. ) : (
  8101. <div className="flex gap-3 pt-4">
  8102. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  8103. {t('common.cancel')}
  8104. </Button>
  8105. <Button
  8106. type="submit"
  8107. className="flex-1"
  8108. disabled={updateMutation.isPending || checkingSave}
  8109. >
  8110. {checkingSave
  8111. ? t('printers.addPreflight.checking')
  8112. : updateMutation.isPending
  8113. ? t('common.saving')
  8114. : t('printers.modal.saveChanges')}
  8115. </Button>
  8116. </div>
  8117. )}
  8118. </form>
  8119. </CardContent>
  8120. </Card>
  8121. </div>
  8122. );
  8123. }
  8124. // Component to check if a printer is offline (for power dropdown)
  8125. function usePrinterOfflineStatus(printerId: number) {
  8126. const { data: status } = useQuery({
  8127. queryKey: ['printerStatus', printerId],
  8128. queryFn: () => api.getPrinterStatus(printerId),
  8129. refetchInterval: 30000,
  8130. });
  8131. return !status?.connected;
  8132. }
  8133. // Power dropdown item for an offline printer
  8134. function PowerDropdownItem({
  8135. printer,
  8136. plug,
  8137. onPowerOn,
  8138. isPowering,
  8139. }: {
  8140. printer: Printer;
  8141. plug: { id: number; name: string };
  8142. onPowerOn: (plugId: number) => void;
  8143. isPowering: boolean;
  8144. }) {
  8145. const isOffline = usePrinterOfflineStatus(printer.id);
  8146. // Fetch plug status
  8147. const { data: plugStatus } = useQuery({
  8148. queryKey: ['smartPlugStatus', plug.id],
  8149. queryFn: () => api.getSmartPlugStatus(plug.id),
  8150. refetchInterval: 10000,
  8151. });
  8152. // Only show if printer is offline
  8153. if (!isOffline) {
  8154. return null;
  8155. }
  8156. return (
  8157. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  8158. <div className="flex items-center gap-2 min-w-0">
  8159. <span className="text-sm text-white truncate">{printer.name}</span>
  8160. {plugStatus && (
  8161. <span
  8162. className={`text-xs px-1.5 py-0.5 rounded ${
  8163. plugStatus.state === 'ON'
  8164. ? 'bg-bambu-green/20 text-bambu-green'
  8165. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  8166. }`}
  8167. >
  8168. {plugStatus.state || '?'}
  8169. </span>
  8170. )}
  8171. </div>
  8172. <button
  8173. onClick={() => onPowerOn(plug.id)}
  8174. disabled={isPowering || plugStatus?.state === 'ON'}
  8175. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  8176. plugStatus?.state === 'ON'
  8177. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  8178. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  8179. }`}
  8180. >
  8181. <Power className="w-3 h-3" />
  8182. {isPowering ? '...' : 'On'}
  8183. </button>
  8184. </div>
  8185. );
  8186. }
  8187. export function PrintersPage() {
  8188. const { t } = useTranslation();
  8189. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  8190. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  8191. const accentButtonClass = {
  8192. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  8193. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  8194. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  8195. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  8196. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  8197. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  8198. }[activeAccent];
  8199. const [showAddModal, setShowAddModal] = useState(false);
  8200. const [hideDisconnected, setHideDisconnected] = useState(() => {
  8201. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  8202. });
  8203. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  8204. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  8205. const [sortBy, setSortBy] = useState<SortOption>(() => {
  8206. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  8207. });
  8208. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  8209. return localStorage.getItem('printerSortAsc') !== 'false';
  8210. });
  8211. // Card size: 1=small, 2=medium, 3=large, 4=xl
  8212. const [cardSize, setCardSize] = useState<number>(() => {
  8213. const saved = localStorage.getItem('printerCardSize');
  8214. return saved ? parseInt(saved, 10) : 2; // Default to medium
  8215. });
  8216. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  8217. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  8218. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  8219. });
  8220. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  8221. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  8222. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  8223. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  8224. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  8225. });
  8226. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  8227. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  8228. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  8229. });
  8230. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  8231. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  8232. // Defaulting to 'full' because the cards already show this info — users who
  8233. // pick cam-wall view still want to glance the same details without flipping.
  8234. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  8235. const saved = localStorage.getItem('camWallStatusMode');
  8236. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  8237. });
  8238. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  8239. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  8240. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  8241. const scrollPrinterIntoView = useCallback((printerId: number) => {
  8242. requestAnimationFrame(() => {
  8243. requestAnimationFrame(() => {
  8244. const card = document.getElementById(`printer-card-${printerId}`);
  8245. if (!card) return;
  8246. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  8247. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  8248. window.scrollTo({
  8249. top: Math.max(0, top),
  8250. behavior: 'smooth',
  8251. });
  8252. });
  8253. });
  8254. }, []);
  8255. const openCompactCard = useCallback((printerId: number) => {
  8256. setCompactDrilldownPrinterId(printerId);
  8257. setCardSize(2);
  8258. localStorage.setItem('printerCardSize', '2');
  8259. scrollPrinterIntoView(printerId);
  8260. }, [scrollPrinterIntoView]);
  8261. const returnToCompactCards = useCallback(() => {
  8262. const printerId = compactDrilldownPrinterId;
  8263. setCompactDrilldownPrinterId(null);
  8264. setCardSize(1);
  8265. localStorage.setItem('printerCardSize', '1');
  8266. if (printerId != null) {
  8267. scrollPrinterIntoView(printerId);
  8268. }
  8269. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  8270. const [search, setSearch] = useState('');
  8271. // Both filters persist like every other preference on this page (#2833).
  8272. // `search` deliberately does not: a box that silently refills itself on
  8273. // return is more surprising than a dropdown that remembers.
  8274. const [statusFilter, setStatusFilter] = useState<string>(() => {
  8275. // Validated on read: a value the dropdown no longer offers would filter
  8276. // every printer out, and nothing would explain why.
  8277. const saved = localStorage.getItem('printerStatusFilter');
  8278. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  8279. });
  8280. const [locationFilter, setLocationFilter] = useState<string>(
  8281. () => localStorage.getItem('printerLocationFilter') || 'all'
  8282. );
  8283. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  8284. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  8285. try {
  8286. const saved = localStorage.getItem('printerCollapsedSections');
  8287. return saved ? JSON.parse(saved) : {};
  8288. } catch { return {}; }
  8289. });
  8290. const queryClient = useQueryClient();
  8291. const { showToast } = useToast();
  8292. const { hasPermission } = useAuth();
  8293. // Which way the camera buttons open a stream. Chosen per click from the
  8294. // button's own menu; null until this browser has made a choice, so the
  8295. // stored setting below can act as the default a fresh browser starts from.
  8296. const [chosenCameraViewMode, setChosenCameraViewMode] = useState<CameraViewMode | null>(
  8297. () => readStoredCameraViewMode()
  8298. );
  8299. // Embedded camera viewer state - supports multiple simultaneous viewers
  8300. // Persisted to localStorage so cameras reopen after navigation
  8301. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  8302. const saved = localStorage.getItem('openEmbeddedCameras');
  8303. if (saved) {
  8304. try {
  8305. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  8306. return new Map(cameras.map(c => [c.id, c]));
  8307. } catch {
  8308. return new Map();
  8309. }
  8310. }
  8311. return new Map();
  8312. });
  8313. // Persist open cameras to localStorage when they change
  8314. useEffect(() => {
  8315. const cameras = Array.from(embeddedCameraPrinters.values());
  8316. if (cameras.length > 0) {
  8317. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  8318. } else {
  8319. localStorage.removeItem('openEmbeddedCameras');
  8320. }
  8321. }, [embeddedCameraPrinters]);
  8322. const { data: printers, isLoading } = useQuery({
  8323. queryKey: ['printers'],
  8324. queryFn: api.getPrinters,
  8325. });
  8326. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  8327. // so users with printers:read but no settings:read still get the values needed
  8328. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  8329. const { data: settings } = useQuery({
  8330. queryKey: ['ui-preferences'],
  8331. queryFn: api.getUiPreferences,
  8332. });
  8333. // Parse user-configured temperature/fan presets once, with defensive fallback
  8334. // to built-in defaults on parse failure (validators on the backend already
  8335. // reject malformed writes, so this is just forward-compat).
  8336. const effectiveNozzleTempPresets = useMemo(
  8337. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  8338. [settings?.nozzle_temp_presets],
  8339. );
  8340. const effectiveBedTempPresets = useMemo(
  8341. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  8342. [settings?.bed_temp_presets],
  8343. );
  8344. const effectiveChamberTempPresets = useMemo(
  8345. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  8346. [settings?.chamber_temp_presets],
  8347. );
  8348. const effectiveFanSpeedPresets = useMemo(
  8349. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  8350. [settings?.fan_speed_presets],
  8351. );
  8352. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  8353. const effectiveDryingPresets = useMemo(() => {
  8354. if (settings?.drying_presets) {
  8355. try {
  8356. const userPresets = JSON.parse(settings.drying_presets);
  8357. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  8358. return { ...DRYING_PRESETS, ...userPresets };
  8359. }
  8360. } catch { /* ignore parse errors, use defaults */ }
  8361. }
  8362. return DRYING_PRESETS;
  8363. }, [settings?.drying_presets]);
  8364. // The local choice wins over the stored one: someone without settings:update
  8365. // cannot write their pick back, and a preference that silently reverted on
  8366. // the next render would be worse than none at all.
  8367. const cameraViewMode: CameraViewMode =
  8368. chosenCameraViewMode ?? (settings?.camera_view_mode === 'embedded' ? 'embedded' : 'window');
  8369. const selectCameraViewMode = useCallback((mode: CameraViewMode) => {
  8370. storeCameraViewMode(mode);
  8371. setChosenCameraViewMode(mode);
  8372. // Best effort, and only a default for other browsers -- the choice is
  8373. // already in effect here. Users below settings:update simply keep theirs
  8374. // locally, which is why the failure is logged rather than surfaced.
  8375. if (hasPermission('settings:update')) {
  8376. api.updateSettings({ camera_view_mode: mode })
  8377. .then(() => queryClient.invalidateQueries({ queryKey: ['ui-preferences'] }))
  8378. .catch((err) => console.warn('Could not save camera view mode as the default:', err));
  8379. }
  8380. }, [hasPermission, queryClient]);
  8381. // Fetch all smart plugs to know which printers have them
  8382. const { data: smartPlugs } = useQuery({
  8383. queryKey: ['smart-plugs'],
  8384. queryFn: api.getSmartPlugs,
  8385. });
  8386. // Fetch maintenance overview for all printers to show badges
  8387. const { data: maintenanceOverview } = useQuery({
  8388. queryKey: ['maintenanceOverview'],
  8389. queryFn: api.getMaintenanceOverview,
  8390. staleTime: 60 * 1000, // 1 minute
  8391. });
  8392. // Live AI failure detection state for the card badges (#1546). Matches the
  8393. // 10s refetch of the Failure Detection settings panel.
  8394. const { data: obicoPrinterStatus } = useQuery({
  8395. queryKey: ['obico-printer-status'],
  8396. queryFn: api.getObicoPrinterStatus,
  8397. refetchInterval: 10000,
  8398. });
  8399. // Badge visibility: detection enabled AND this printer in the monitored set
  8400. // (monitored_printers null = all). Live per-print state is passed separately.
  8401. const isAiMonitored = useCallback(
  8402. (printerId: number) =>
  8403. obicoPrinterStatus?.enabled === true &&
  8404. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  8405. [obicoPrinterStatus],
  8406. );
  8407. // Fetch Spoolman status to enable link spool feature
  8408. const { data: spoolmanStatus } = useQuery({
  8409. queryKey: ['spoolman-status'],
  8410. queryFn: api.getSpoolmanStatus,
  8411. staleTime: 60 * 1000, // 1 minute
  8412. });
  8413. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  8414. // Fetch Spoolman settings to get sync mode
  8415. const { data: spoolmanSettings } = useQuery({
  8416. queryKey: ['spoolman-settings'],
  8417. queryFn: api.getSpoolmanSettings,
  8418. enabled: !!spoolmanEnabled,
  8419. staleTime: 60 * 1000, // 1 minute
  8420. });
  8421. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  8422. // Fetch unlinked spools to know if link button should be enabled
  8423. const { data: unlinkedSpools } = useQuery({
  8424. queryKey: ['unlinked-spools'],
  8425. queryFn: api.getUnlinkedSpools,
  8426. enabled: !!spoolmanEnabled,
  8427. staleTime: 30 * 1000, // 30 seconds
  8428. });
  8429. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  8430. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  8431. const { data: linkedSpoolsData } = useQuery({
  8432. queryKey: ['linked-spools'],
  8433. queryFn: api.getLinkedSpools,
  8434. enabled: !!spoolmanEnabled,
  8435. staleTime: 30 * 1000, // 30 seconds
  8436. });
  8437. const linkedSpools = linkedSpoolsData?.linked;
  8438. // Fetch spool assignments for inventory feature
  8439. const { data: spoolAssignments } = useQuery({
  8440. queryKey: ['spool-assignments'],
  8441. queryFn: () => api.getAssignments(),
  8442. enabled: hasPermission('inventory:view_assignments'),
  8443. staleTime: 30 * 1000,
  8444. });
  8445. const unassignMutation = useMutation({
  8446. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  8447. api.unassignSpool(printerId, amsId, trayId),
  8448. onSuccess: () => {
  8449. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  8450. },
  8451. });
  8452. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  8453. queryKey: ['spoolman-inventory-spools'],
  8454. queryFn: () => api.getSpoolmanInventorySpools(false),
  8455. enabled: !!spoolmanEnabled,
  8456. staleTime: 30 * 1000,
  8457. });
  8458. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  8459. queryKey: ['spoolman-slot-assignments'],
  8460. queryFn: () => api.getSpoolmanSlotAssignments(),
  8461. enabled: !!spoolmanEnabled,
  8462. staleTime: 30 * 1000,
  8463. });
  8464. const unassignSpoolmanMutation = useMutation({
  8465. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  8466. onSuccess: () => {
  8467. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  8468. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  8469. },
  8470. });
  8471. // Helper to find assignment for a specific slot
  8472. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  8473. return spoolAssignments?.find(
  8474. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  8475. );
  8476. };
  8477. // Create a map of printer_id -> maintenance info for quick lookup
  8478. const maintenanceByPrinter = maintenanceOverview?.reduce(
  8479. (acc, overview) => {
  8480. acc[overview.printer_id] = {
  8481. due_count: overview.due_count,
  8482. warning_count: overview.warning_count,
  8483. total_print_hours: overview.total_print_hours,
  8484. };
  8485. return acc;
  8486. },
  8487. {} as Record<number, PrinterMaintenanceInfo>
  8488. ) || {};
  8489. // Create a map of printer_id -> smart plug
  8490. const smartPlugByPrinter = smartPlugs?.reduce(
  8491. (acc, plug) => {
  8492. if (plug.printer_id) {
  8493. acc[plug.printer_id] = plug;
  8494. }
  8495. return acc;
  8496. },
  8497. {} as Record<number, typeof smartPlugs[0]>
  8498. ) || {};
  8499. const addMutation = useMutation({
  8500. mutationFn: api.createPrinter,
  8501. onSuccess: () => {
  8502. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8503. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8504. setShowAddModal(false);
  8505. },
  8506. onError: (error: Error) => {
  8507. // Localized message when the backend returns a stable error code;
  8508. // the raw message is an English fallback for non-UI clients.
  8509. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8510. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8511. return;
  8512. }
  8513. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8514. },
  8515. });
  8516. const powerOnMutation = useMutation({
  8517. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8518. onSuccess: () => {
  8519. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8520. setPoweringOn(null);
  8521. },
  8522. onError: () => {
  8523. setPoweringOn(null);
  8524. },
  8525. });
  8526. // Bulk selection state
  8527. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8528. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8529. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8530. const [bulkActionPending, setBulkActionPending] = useState(false);
  8531. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8532. const toggleSelect = useCallback((id: number) => {
  8533. setSelectedPrinterIds(prev => {
  8534. const next = new Set(prev);
  8535. if (next.has(id)) next.delete(id);
  8536. else next.add(id);
  8537. return next;
  8538. });
  8539. }, []);
  8540. const clearSelection = useCallback(() => {
  8541. setSelectedPrinterIds(new Set());
  8542. setIsSelectionMode(false);
  8543. }, []);
  8544. // Escape key exits selection mode
  8545. useEffect(() => {
  8546. const handleKeyDown = (e: KeyboardEvent) => {
  8547. if (e.key === 'Escape' && selectionMode) {
  8548. clearSelection();
  8549. }
  8550. };
  8551. window.addEventListener('keydown', handleKeyDown);
  8552. return () => window.removeEventListener('keydown', handleKeyDown);
  8553. }, [selectionMode, clearSelection]);
  8554. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8555. setBulkActionPending(true);
  8556. const ids = Array.from(selectedPrinterIds);
  8557. // Filter to only applicable printers based on cached state
  8558. const applicableIds = ids.filter(id => {
  8559. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8560. // clearPlate is checked before the connection filter: it only releases a
  8561. // Bambuddy-side gate, so it applies to a printer Auto Power Off has shut
  8562. // down — every other action here needs to reach the machine (#2864).
  8563. if (action === 'clearPlate') return !!(status as { awaiting_plate_clear?: boolean } | undefined)?.awaiting_plate_clear;
  8564. if (!status?.connected) return false;
  8565. switch (action) {
  8566. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8567. case 'pause': return status.state === 'RUNNING';
  8568. case 'resume': return status.state === 'PAUSE';
  8569. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8570. default: return false;
  8571. }
  8572. });
  8573. if (applicableIds.length === 0) {
  8574. showToast(t('printers.bulk.noneApplicable'), 'error');
  8575. setBulkActionPending(false);
  8576. setBulkConfirmAction(null);
  8577. return;
  8578. }
  8579. const apiCall = {
  8580. stop: api.stopPrint,
  8581. pause: api.pausePrint,
  8582. resume: api.resumePrint,
  8583. clearPlate: api.clearPlate,
  8584. clearHMS: api.clearHMSErrors,
  8585. }[action];
  8586. const results = await Promise.allSettled(
  8587. applicableIds.map(id => apiCall(id))
  8588. );
  8589. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8590. const failed = results.filter(r => r.status === 'rejected').length;
  8591. if (failed === 0) {
  8592. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8593. } else {
  8594. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8595. }
  8596. // Invalidate status queries for affected printers
  8597. applicableIds.forEach(id => {
  8598. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8599. });
  8600. setBulkActionPending(false);
  8601. setBulkConfirmAction(null);
  8602. }, [selectedPrinterIds, queryClient, showToast, t]);
  8603. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8604. // Actions that need confirmation
  8605. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8606. setBulkConfirmAction(action);
  8607. } else {
  8608. executeBulkAction(action);
  8609. }
  8610. }, [executeBulkAction]);
  8611. const toggleHideDisconnected = () => {
  8612. const newValue = !hideDisconnected;
  8613. setHideDisconnected(newValue);
  8614. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8615. };
  8616. const handleSortChange = (newSort: SortOption) => {
  8617. setSortBy(newSort);
  8618. localStorage.setItem('printerSortBy', newSort);
  8619. };
  8620. const handleStatusFilterChange = (value: string) => {
  8621. setStatusFilter(value);
  8622. localStorage.setItem('printerStatusFilter', value);
  8623. };
  8624. const handleLocationFilterChange = (value: string) => {
  8625. setLocationFilter(value);
  8626. localStorage.setItem('printerLocationFilter', value);
  8627. };
  8628. const toggleSortDirection = () => {
  8629. const newAsc = !sortAsc;
  8630. setSortAsc(newAsc);
  8631. localStorage.setItem('printerSortAsc', String(newAsc));
  8632. };
  8633. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8634. const getGridClasses = () => {
  8635. switch (cardSize) {
  8636. 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
  8637. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8638. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8639. case 4: return 'grid-cols-1'; // XL: single column, full width
  8640. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8641. }
  8642. };
  8643. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8644. // Increment version counter whenever a printer status cache entry is updated so
  8645. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8646. useEffect(() => {
  8647. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8648. if (
  8649. event.type === 'updated' &&
  8650. Array.isArray(event.query.queryKey) &&
  8651. event.query.queryKey[0] === 'printerStatus'
  8652. ) {
  8653. setStatusCacheVersion(v => v + 1);
  8654. }
  8655. });
  8656. return unsubscribe;
  8657. }, [queryClient]);
  8658. // Filter printers by search term, status, and location
  8659. const filteredPrinters = useMemo(() => {
  8660. if (!printers) return [];
  8661. let result = printers;
  8662. // Text search
  8663. if (search.trim()) {
  8664. const q = search.trim().toLowerCase();
  8665. result = result.filter(p =>
  8666. p.name.toLowerCase().includes(q) ||
  8667. (p.model || '').toLowerCase().includes(q) ||
  8668. (p.location || '').toLowerCase().includes(q) ||
  8669. (p.serial_number || '').toLowerCase().includes(q)
  8670. );
  8671. }
  8672. // Location filter
  8673. if (locationFilter !== 'all') {
  8674. result = result.filter(p => (p.location || '') === locationFilter);
  8675. }
  8676. // Status filter
  8677. if (statusFilter !== 'all') {
  8678. result = result.filter(p => {
  8679. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8680. if (!status?.connected) return statusFilter === 'offline';
  8681. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8682. switch (statusFilter) {
  8683. case 'printing': return status.state === 'RUNNING';
  8684. case 'paused': return status.state === 'PAUSE';
  8685. case 'finished': return status.state === 'FINISH';
  8686. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8687. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8688. case 'offline': return false; // Connected printers are never offline
  8689. default: return true;
  8690. }
  8691. });
  8692. }
  8693. return result;
  8694. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8695. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8696. // Derive unique locations for the location filter dropdown
  8697. const availableLocations = useMemo(() => {
  8698. if (!printers) return [];
  8699. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8700. }, [printers]);
  8701. // A saved location can outlive what it matched -- renamed, cleared, or the
  8702. // only printer that had it deleted. The dropdown is rendered only while some
  8703. // printer has a location, so a stale one would hide every printer *and* the
  8704. // control to undo it, leaving an empty page and no way back (#2833).
  8705. // Deliberately waits for `printers`: it is undefined while the query is in
  8706. // flight, and acting on the empty list that produces would throw the saved
  8707. // filter away every time the page loads.
  8708. useEffect(() => {
  8709. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8710. setLocationFilter('all');
  8711. localStorage.setItem('printerLocationFilter', 'all');
  8712. }, [printers, availableLocations, locationFilter]);
  8713. // Sort printers based on selected option
  8714. const sortedPrinters = useMemo(() => {
  8715. const sorted = [...filteredPrinters];
  8716. switch (sortBy) {
  8717. case 'name':
  8718. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8719. break;
  8720. case 'model':
  8721. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8722. break;
  8723. case 'location':
  8724. // Sort by location, with ungrouped printers last
  8725. sorted.sort((a, b) => {
  8726. const locA = a.location || '';
  8727. const locB = b.location || '';
  8728. if (!locA && locB) return 1;
  8729. if (locA && !locB) return -1;
  8730. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8731. });
  8732. break;
  8733. case 'status':
  8734. // Sort by status: HMS errors > printing > idle > offline
  8735. sorted.sort((a, b) => {
  8736. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8737. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8738. const getPriority = (s: typeof statusA) => {
  8739. if (!s?.connected) return 3; // offline
  8740. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8741. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8742. if (s.state === 'RUNNING') return 1; // printing
  8743. return 2; // idle
  8744. };
  8745. return getPriority(statusA) - getPriority(statusB);
  8746. });
  8747. break;
  8748. case 'eta':
  8749. sorted.sort((a, b) => {
  8750. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8751. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8752. const tier = (s: typeof statusA) => {
  8753. if (!s?.connected) return 3; // offline last
  8754. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8755. if (s.state === 'RUNNING') return 1; // printing without ETA
  8756. return 2; // idle
  8757. };
  8758. const ta = tier(statusA);
  8759. const tb = tier(statusB);
  8760. if (ta !== tb) return ta - tb;
  8761. if (ta === 0) {
  8762. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8763. if (diff !== 0) return diff;
  8764. }
  8765. return a.name.localeCompare(b.name);
  8766. });
  8767. break;
  8768. }
  8769. // Apply ascending/descending
  8770. if (!sortAsc) {
  8771. sorted.reverse();
  8772. }
  8773. return sorted;
  8774. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8775. const selectAll = useCallback(() => {
  8776. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8777. setIsSelectionMode(true);
  8778. }, [sortedPrinters]);
  8779. const selectByState = useCallback((state: PrinterState) => {
  8780. setSelectedPrinterIds(prev => {
  8781. const next = new Set(prev);
  8782. sortedPrinters.forEach(p => {
  8783. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8784. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8785. });
  8786. return next;
  8787. });
  8788. setIsSelectionMode(true);
  8789. }, [sortedPrinters, queryClient]);
  8790. const selectByLocation = useCallback((location: string) => {
  8791. setSelectedPrinterIds(prev => {
  8792. const next = new Set(prev);
  8793. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  8794. return next;
  8795. });
  8796. setIsSelectionMode(true);
  8797. }, [sortedPrinters]);
  8798. const selectByModel = useCallback((model: string) => {
  8799. setSelectedPrinterIds(prev => {
  8800. const next = new Set(prev);
  8801. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  8802. return next;
  8803. });
  8804. setIsSelectionMode(true);
  8805. }, [sortedPrinters]);
  8806. const toggleSectionCollapse = useCallback((key: string) => {
  8807. setCollapsedSections(prev => {
  8808. const next = { ...prev, [key]: !prev[key] };
  8809. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  8810. return next;
  8811. });
  8812. }, []);
  8813. // Group printers when sorted by location, status, or model
  8814. const groupedPrinters = useMemo(() => {
  8815. if (sortBy === 'name' || sortBy === 'eta') return null;
  8816. const groups: Record<string, typeof sortedPrinters> = {};
  8817. if (sortBy === 'location') {
  8818. sortedPrinters.forEach(printer => {
  8819. const location = printer.location || 'Ungrouped';
  8820. if (!groups[location]) groups[location] = [];
  8821. groups[location].push(printer);
  8822. });
  8823. } else if (sortBy === 'model') {
  8824. sortedPrinters.forEach(printer => {
  8825. const model = printer.model || 'Unknown';
  8826. if (!groups[model]) groups[model] = [];
  8827. groups[model].push(printer);
  8828. });
  8829. } else if (sortBy === 'status') {
  8830. sortedPrinters.forEach(printer => {
  8831. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  8832. const group = classifyPrinterStatus(status);
  8833. if (!groups[group]) groups[group] = [];
  8834. groups[group].push(printer);
  8835. });
  8836. }
  8837. return groups;
  8838. // 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
  8839. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  8840. const toolbarRef = useRef<HTMLDivElement>(null);
  8841. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  8842. const expandedToolbarWidthRef = useRef(0);
  8843. const [compactToolbar, setCompactToolbar] = useState(false);
  8844. const measureToolbar = useCallback(() => {
  8845. const toolbar = toolbarRef.current;
  8846. if (!toolbar) return;
  8847. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  8848. if (measuredControlsWidth) {
  8849. expandedToolbarWidthRef.current = measuredControlsWidth;
  8850. }
  8851. const searchMinimumWidth = 220;
  8852. const gapWidth = 8;
  8853. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  8854. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  8855. }, []);
  8856. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  8857. useLayoutEffect(() => {
  8858. measureToolbar();
  8859. const toolbar = toolbarRef.current;
  8860. if (!toolbar) return;
  8861. if (typeof ResizeObserver === 'undefined') {
  8862. window.addEventListener('resize', measureToolbar);
  8863. return () => window.removeEventListener('resize', measureToolbar);
  8864. }
  8865. const resizeObserver = new ResizeObserver(() => measureToolbar());
  8866. resizeObserver.observe(toolbar);
  8867. window.addEventListener('resize', measureToolbar);
  8868. return () => {
  8869. resizeObserver.disconnect();
  8870. window.removeEventListener('resize', measureToolbar);
  8871. };
  8872. }, [
  8873. measureToolbar,
  8874. printers?.length,
  8875. availableLocations.length,
  8876. hideDisconnected,
  8877. smartPlugCount,
  8878. ]);
  8879. const renderFilterControls = (inMenu = false) => (
  8880. <>
  8881. {/* Status filter */}
  8882. {printers && printers.length > 0 && (
  8883. <ToolbarDropdown
  8884. value={statusFilter}
  8885. onChange={handleStatusFilterChange}
  8886. fullWidth={inMenu}
  8887. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  8888. />
  8889. )}
  8890. {/* Location filter — only shown when at least one printer has a location */}
  8891. {printers && printers.length > 0 && availableLocations.length > 0 && (
  8892. <ToolbarDropdown
  8893. value={locationFilter}
  8894. onChange={handleLocationFilterChange}
  8895. fullWidth={inMenu}
  8896. options={[
  8897. { value: 'all', label: t('printers.filter.allLocations') },
  8898. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  8899. ]}
  8900. />
  8901. )}
  8902. <button
  8903. type="button"
  8904. onClick={toggleHideDisconnected}
  8905. aria-pressed={hideDisconnected}
  8906. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  8907. hideDisconnected
  8908. ? 'bg-bambu-green border-bambu-green text-white'
  8909. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8910. }`}
  8911. >
  8912. {t('printers.hideOffline')}
  8913. </button>
  8914. </>
  8915. );
  8916. const renderViewControls = (inMenu = false) => (
  8917. <>
  8918. {/* Sort dropdown */}
  8919. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8920. <ToolbarDropdown<SortOption>
  8921. value={sortBy}
  8922. onChange={handleSortChange}
  8923. fullWidth={inMenu}
  8924. options={[
  8925. { value: 'name', label: t('printers.sort.name') },
  8926. { value: 'status', label: t('printers.sort.status') },
  8927. { value: 'model', label: t('printers.sort.model') },
  8928. { value: 'location', label: t('printers.sort.location') },
  8929. { value: 'eta', label: t('printers.sort.eta') },
  8930. ]}
  8931. />
  8932. <button
  8933. onClick={toggleSortDirection}
  8934. 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"
  8935. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8936. >
  8937. {sortAsc ? (
  8938. <ArrowUp className="w-4 h-4 text-white" />
  8939. ) : (
  8940. <ArrowDown className="w-4 h-4 text-white" />
  8941. )}
  8942. </button>
  8943. </div>
  8944. {/* Page view toggle: Cards / Cam Wall */}
  8945. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8946. <button
  8947. type="button"
  8948. onClick={() => {
  8949. setPageView('cards');
  8950. localStorage.setItem('printerPageView', 'cards');
  8951. }}
  8952. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8953. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8954. }`}
  8955. title={t('printers.pageView.cards')}
  8956. aria-pressed={pageView === 'cards'}
  8957. >
  8958. <LayoutGrid className="w-3.5 h-3.5" />
  8959. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8960. </button>
  8961. <button
  8962. type="button"
  8963. onClick={() => {
  8964. setPageView('camwall');
  8965. localStorage.setItem('printerPageView', 'camwall');
  8966. }}
  8967. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8968. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8969. }`}
  8970. title={t('printers.pageView.camWall')}
  8971. aria-pressed={pageView === 'camwall'}
  8972. disabled={!hasPermission('camera:view')}
  8973. >
  8974. <MonitorPlay className="w-3.5 h-3.5" />
  8975. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8976. </button>
  8977. </div>
  8978. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8979. view, and the page a kiosk token points at. Only offered once the wall
  8980. is the active view, so it doesn't compete with the toggle above. */}
  8981. {pageView === 'camwall' && hasPermission('camera:view') && (
  8982. <RouterLink
  8983. to="/camwall"
  8984. 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' : ''}`}
  8985. title={t('printers.pageView.openCamWallPage')}
  8986. >
  8987. <ExternalLink className="w-3.5 h-3.5" />
  8988. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8989. </RouterLink>
  8990. )}
  8991. {/* Card size selector */}
  8992. <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' : ''}`}>
  8993. {cardSizeLabels.map((label, index) => {
  8994. const size = index + 1;
  8995. const isSelected = cardSize === size;
  8996. return (
  8997. <button
  8998. key={label}
  8999. onClick={() => {
  9000. setCompactDrilldownPrinterId(null);
  9001. setCardSize(size);
  9002. localStorage.setItem('printerCardSize', String(size));
  9003. }}
  9004. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  9005. index === 0 ? 'rounded-l-lg' : ''
  9006. } ${
  9007. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  9008. } ${
  9009. isSelected
  9010. ? 'bg-bambu-green text-white'
  9011. : 'text-white hover:bg-bambu-dark-tertiary'
  9012. }`}
  9013. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  9014. >
  9015. {label}
  9016. </button>
  9017. );
  9018. })}
  9019. </div>
  9020. </>
  9021. );
  9022. const renderActionControls = (inMenu = false) => (
  9023. <>
  9024. {/* Bulk select toggle */}
  9025. <button
  9026. onClick={() => {
  9027. if (selectionMode) clearSelection();
  9028. else setIsSelectionMode(true);
  9029. }}
  9030. 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' : ''} ${
  9031. selectionMode
  9032. ? 'bg-bambu-green border-bambu-green text-white'
  9033. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9034. }`}
  9035. title={t('printers.bulk.select')}
  9036. disabled={!hasPermission('printers:control')}
  9037. >
  9038. <CheckSquare className="w-4 h-4" />
  9039. {inMenu && <span>{t('printers.bulk.select')}</span>}
  9040. </button>
  9041. {/* Power dropdown for offline printers with smart plugs */}
  9042. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  9043. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  9044. <button
  9045. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  9046. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  9047. inMenu
  9048. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  9049. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  9050. }`}
  9051. >
  9052. <span className="flex items-center gap-1.5">
  9053. <Power className="w-4 h-4" />
  9054. {t('printers.powerOn')}
  9055. </span>
  9056. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  9057. </button>
  9058. {showPowerDropdown && (
  9059. <>
  9060. {/* Backdrop to close dropdown */}
  9061. <div
  9062. className="fixed inset-0 z-10"
  9063. onClick={() => setShowPowerDropdown(false)}
  9064. />
  9065. <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">
  9066. <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">
  9067. {t('printers.offlinePrintersWithPlugs')}
  9068. </div>
  9069. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  9070. <PowerDropdownItem
  9071. key={printer.id}
  9072. printer={printer}
  9073. plug={smartPlugByPrinter[printer.id]}
  9074. onPowerOn={(plugId) => {
  9075. setPoweringOn(plugId);
  9076. powerOnMutation.mutate(plugId);
  9077. }}
  9078. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  9079. />
  9080. ))}
  9081. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  9082. <div className="px-3 py-2 text-sm text-bambu-gray">
  9083. No printers with smart plugs
  9084. </div>
  9085. )}
  9086. </div>
  9087. </>
  9088. )}
  9089. </div>
  9090. )}
  9091. <Button
  9092. onClick={() => setShowAddModal(true)}
  9093. disabled={!hasPermission('printers:create')}
  9094. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9095. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  9096. >
  9097. <Plus className="w-4 h-4" />
  9098. {t('printers.addPrinter')}
  9099. </Button>
  9100. </>
  9101. );
  9102. return (
  9103. <div className="p-4 md:p-8">
  9104. <div className="space-y-3 mb-6">
  9105. <div>
  9106. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  9107. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  9108. {t('printers.title')}
  9109. </h1>
  9110. <StatusSummaryBar printers={printers} />
  9111. </div>
  9112. <div ref={toolbarRef} className="relative flex items-center gap-2">
  9113. {/* Only show search bar when printers exist */}
  9114. {printers && printers.length > 0 && (
  9115. <div className="relative min-w-0 flex-1">
  9116. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  9117. <input
  9118. type="search"
  9119. name="printer-search"
  9120. autoComplete="off"
  9121. data-1p-ignore
  9122. data-lpignore="true"
  9123. value={search}
  9124. onChange={(e) => setSearch(e.target.value)}
  9125. placeholder={t('printers.search')}
  9126. aria-label={t('printers.search')}
  9127. 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"
  9128. />
  9129. {search && (
  9130. <button
  9131. type="button"
  9132. aria-label={t('common.clear')}
  9133. onClick={() => setSearch('')}
  9134. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  9135. >
  9136. <X className="w-4 h-4" />
  9137. </button>
  9138. )}
  9139. </div>
  9140. )}
  9141. <div
  9142. ref={expandedToolbarControlsRef}
  9143. aria-hidden={compactToolbar}
  9144. inert={compactToolbar}
  9145. 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`}
  9146. >
  9147. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9148. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  9149. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9150. <div className="flex items-center gap-2">{renderViewControls()}</div>
  9151. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  9152. <div className="flex items-center gap-2">{renderActionControls()}</div>
  9153. </div>
  9154. {compactToolbar && (
  9155. <div className="ml-auto flex items-center justify-end gap-1">
  9156. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  9157. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  9158. </ToolbarMenu>
  9159. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  9160. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  9161. </ToolbarMenu>
  9162. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  9163. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  9164. </ToolbarMenu>
  9165. </div>
  9166. )}
  9167. </div>
  9168. </div>
  9169. {isLoading ? (
  9170. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  9171. ) : printers?.length === 0 ? (
  9172. <Card>
  9173. <CardContent className="text-center py-12">
  9174. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  9175. <Button
  9176. onClick={() => setShowAddModal(true)}
  9177. disabled={!hasPermission('printers:create')}
  9178. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  9179. >
  9180. <Plus className="w-4 h-4" />
  9181. {t('printers.addPrinter')}
  9182. </Button>
  9183. </CardContent>
  9184. </Card>
  9185. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  9186. <Card>
  9187. <CardContent className="text-center py-12">
  9188. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  9189. </CardContent>
  9190. </Card>
  9191. ) : pageView === 'camwall' ? (
  9192. <CameraWall
  9193. printers={sortedPrinters}
  9194. maxLive={camWallMaxLive}
  9195. snapshotIntervalSec={camWallSnapshotSec}
  9196. onTileClick={(id, name) => {
  9197. // A wall tile has no room for a split button, so it follows the
  9198. // mode the card buttons last chose.
  9199. if (cameraViewMode === 'embedded') {
  9200. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  9201. } else {
  9202. openCameraWindow(id);
  9203. }
  9204. }}
  9205. statusMode={camWallStatusMode}
  9206. onChangeMaxLive={(next) => {
  9207. setCamWallMaxLive(next);
  9208. localStorage.setItem('camWallMaxLive', String(next));
  9209. }}
  9210. onChangeSnapshotIntervalSec={(next) => {
  9211. setCamWallSnapshotSec(next);
  9212. localStorage.setItem('camWallSnapshotSec', String(next));
  9213. }}
  9214. onChangeStatusMode={(next) => {
  9215. setCamWallStatusMode(next);
  9216. localStorage.setItem('camWallStatusMode', next);
  9217. }}
  9218. />
  9219. ) : groupedPrinters ? (
  9220. /* Grouped view (location, status, or model) */
  9221. <div className="space-y-6">
  9222. {(() => {
  9223. const keys = sortBy === 'status'
  9224. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  9225. : Object.keys(groupedPrinters);
  9226. // For status grouping, asc/desc flips the fixed priority order
  9227. // (asc = error→offline, desc = offline→error). This matches the
  9228. // sort-toggle behaviour for other groupings.
  9229. return (sortAsc ? keys : [...keys].reverse());
  9230. })().map((groupKey) => {
  9231. const groupPrinters = groupedPrinters[groupKey];
  9232. const collapseKey = `${sortBy}:${groupKey}`;
  9233. const isOpen = !collapsedSections[collapseKey];
  9234. const dot = sortBy === 'status'
  9235. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  9236. : 'bg-bambu-green';
  9237. const label = sortBy === 'status'
  9238. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  9239. : groupKey;
  9240. return (
  9241. <Collapsible
  9242. key={groupKey}
  9243. open={isOpen}
  9244. onToggle={() => toggleSectionCollapse(collapseKey)}
  9245. summaryClassName="py-1"
  9246. summary={
  9247. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  9248. <span className={`w-2 h-2 rounded-full ${dot}`} />
  9249. {label}
  9250. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  9251. {selectionMode && (
  9252. <button
  9253. onClick={(e) => {
  9254. e.stopPropagation();
  9255. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  9256. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  9257. else if (sortBy === 'model') selectByModel(groupKey);
  9258. }}
  9259. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  9260. >
  9261. {t('printers.bulk.selectAll')}
  9262. </button>
  9263. )}
  9264. </h2>
  9265. }
  9266. >
  9267. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9268. {groupPrinters.map((printer) => (
  9269. <PrinterCard
  9270. key={printer.id}
  9271. printer={printer}
  9272. hideIfDisconnected={hideDisconnected}
  9273. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9274. viewMode={viewMode}
  9275. cardSize={cardSize}
  9276. amsThresholds={settings ? {
  9277. humidityGood: Number(settings.ams_humidity_good) || 40,
  9278. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9279. tempGood: Number(settings.ams_temp_good) || 28,
  9280. tempFair: Number(settings.ams_temp_fair) || 35,
  9281. } : undefined}
  9282. spoolmanEnabled={spoolmanEnabled}
  9283. hasUnlinkedSpools={hasUnlinkedSpools}
  9284. linkedSpools={linkedSpools}
  9285. spoolmanUrl={spoolmanStatus?.url}
  9286. spoolmanSyncMode={spoolmanSyncMode}
  9287. onGetAssignment={getAssignment}
  9288. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9289. spoolmanSpools={spoolmanSpools}
  9290. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9291. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9292. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9293. timeFormat={settings?.time_format || 'system'}
  9294. cameraViewMode={cameraViewMode}
  9295. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9296. onSelectCameraViewMode={selectCameraViewMode}
  9297. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9298. dryingPresets={effectiveDryingPresets}
  9299. nozzleTempPresets={effectiveNozzleTempPresets}
  9300. bedTempPresets={effectiveBedTempPresets}
  9301. chamberTempPresets={effectiveChamberTempPresets}
  9302. fanSpeedPresets={effectiveFanSpeedPresets}
  9303. requirePlateClear={settings?.require_plate_clear === true}
  9304. selectionMode={selectionMode}
  9305. isSelected={selectedPrinterIds.has(printer.id)}
  9306. onToggleSelect={toggleSelect}
  9307. onOpenCompactCard={openCompactCard}
  9308. aiDetectionEnabled={isAiMonitored(printer.id)}
  9309. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9310. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9311. />
  9312. ))}
  9313. </div>
  9314. </Collapsible>
  9315. );
  9316. })}
  9317. </div>
  9318. ) : (
  9319. /* Regular grid view */
  9320. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  9321. {sortedPrinters.map((printer) => (
  9322. <PrinterCard
  9323. key={printer.id}
  9324. printer={printer}
  9325. hideIfDisconnected={hideDisconnected}
  9326. maintenanceInfo={maintenanceByPrinter[printer.id]}
  9327. viewMode={viewMode}
  9328. cardSize={cardSize}
  9329. spoolmanEnabled={spoolmanEnabled}
  9330. hasUnlinkedSpools={hasUnlinkedSpools}
  9331. linkedSpools={linkedSpools}
  9332. spoolmanUrl={spoolmanStatus?.url}
  9333. spoolmanSyncMode={spoolmanSyncMode}
  9334. onGetAssignment={getAssignment}
  9335. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  9336. spoolmanSpools={spoolmanSpools}
  9337. spoolmanSlotAssignments={spoolmanSlotAssignments}
  9338. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  9339. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  9340. amsThresholds={settings ? {
  9341. humidityGood: Number(settings.ams_humidity_good) || 40,
  9342. humidityFair: Number(settings.ams_humidity_fair) || 60,
  9343. tempGood: Number(settings.ams_temp_good) || 28,
  9344. tempFair: Number(settings.ams_temp_fair) || 35,
  9345. } : undefined}
  9346. timeFormat={settings?.time_format || 'system'}
  9347. cameraViewMode={cameraViewMode}
  9348. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  9349. onSelectCameraViewMode={selectCameraViewMode}
  9350. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  9351. dryingPresets={effectiveDryingPresets}
  9352. nozzleTempPresets={effectiveNozzleTempPresets}
  9353. bedTempPresets={effectiveBedTempPresets}
  9354. chamberTempPresets={effectiveChamberTempPresets}
  9355. fanSpeedPresets={effectiveFanSpeedPresets}
  9356. requirePlateClear={settings?.require_plate_clear === true}
  9357. selectionMode={selectionMode}
  9358. isSelected={selectedPrinterIds.has(printer.id)}
  9359. onToggleSelect={toggleSelect}
  9360. onOpenCompactCard={openCompactCard}
  9361. aiDetectionEnabled={isAiMonitored(printer.id)}
  9362. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  9363. aiLastError={obicoPrinterStatus?.last_error ?? null}
  9364. />
  9365. ))}
  9366. </div>
  9367. )}
  9368. {cardSize === 2 && compactDrilldownPrinterId != null && (
  9369. <button
  9370. type="button"
  9371. onClick={returnToCompactCards}
  9372. 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}`}
  9373. title={t('common.back', 'Back')}
  9374. >
  9375. <ArrowLeft className="w-4 h-4" />
  9376. {t('common.back', 'Back')}
  9377. </button>
  9378. )}
  9379. {showAddModal && (
  9380. <AddPrinterModal
  9381. onClose={() => setShowAddModal(false)}
  9382. onAdd={(data) => addMutation.mutate(data)}
  9383. existingSerials={printers?.map(p => p.serial_number) || []}
  9384. />
  9385. )}
  9386. {/* Bulk selection toolbar */}
  9387. {selectionMode && printers && (
  9388. <BulkPrinterToolbar
  9389. selectedIds={selectedPrinterIds}
  9390. printers={printers}
  9391. onClose={clearSelection}
  9392. onSelectAll={selectAll}
  9393. onSelectByLocation={selectByLocation}
  9394. onSelectByState={selectByState}
  9395. onAction={handleBulkAction}
  9396. actionPending={bulkActionPending}
  9397. />
  9398. )}
  9399. {/* Bulk action confirmation modals */}
  9400. {bulkConfirmAction === 'stop' && (
  9401. <ConfirmModal
  9402. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  9403. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  9404. confirmText={t('printers.bulk.confirm.stopButton')}
  9405. variant="danger"
  9406. isLoading={bulkActionPending}
  9407. onConfirm={() => executeBulkAction('stop')}
  9408. onCancel={() => setBulkConfirmAction(null)}
  9409. />
  9410. )}
  9411. {bulkConfirmAction === 'pause' && (
  9412. <ConfirmModal
  9413. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  9414. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  9415. confirmText={t('printers.bulk.confirm.pauseButton')}
  9416. isLoading={bulkActionPending}
  9417. onConfirm={() => executeBulkAction('pause')}
  9418. onCancel={() => setBulkConfirmAction(null)}
  9419. />
  9420. )}
  9421. {bulkConfirmAction === 'clearPlate' && (
  9422. <ConfirmModal
  9423. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  9424. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  9425. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  9426. isLoading={bulkActionPending}
  9427. onConfirm={() => executeBulkAction('clearPlate')}
  9428. onCancel={() => setBulkConfirmAction(null)}
  9429. />
  9430. )}
  9431. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  9432. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  9433. <EmbeddedCameraViewer
  9434. key={camera.id}
  9435. printerId={camera.id}
  9436. printerName={camera.name}
  9437. viewerIndex={index}
  9438. onClose={() => setEmbeddedCameraPrinters(prev => {
  9439. const next = new Map(prev);
  9440. next.delete(camera.id);
  9441. return next;
  9442. })}
  9443. />
  9444. ))}
  9445. </div>
  9446. );
  9447. }