PrintersPage.tsx 434 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106
  1. import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';
  2. import { createPortal } from 'react-dom';
  3. import { compareFwVersions } from '../utils/firmwareVersion';
  4. import { formatPrintName } from '../utils/printName';
  5. import { computePopoverPosition } from '../utils/popoverPosition';
  6. import {
  7. BED_TEMP_DEFAULTS,
  8. CHAMBER_TEMP_DEFAULTS,
  9. FAN_SPEED_DEFAULTS,
  10. NOZZLE_TEMP_DEFAULTS,
  11. buildPresetOptions,
  12. parsePresetTriple,
  13. } from '../utils/temperatureFanPresets';
  14. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  15. // covers header + filament select + temp slider + duration + rotate-tray
  16. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  17. // earlier); under-estimating leaves the popover clipped off the bottom (the
  18. // original bug at #1447).
  19. const DRYING_POPOVER_WIDTH = 240;
  20. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  21. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  22. import { useTranslation } from 'react-i18next';
  23. import { useTheme } from '../contexts/ThemeContext';
  24. import { useAuth } from '../contexts/AuthContext';
  25. import {
  26. Plus,
  27. Link,
  28. Unlink,
  29. Signal,
  30. Clock,
  31. MoreVertical,
  32. Trash2,
  33. RefreshCw,
  34. RotateCw,
  35. Box,
  36. HardDrive,
  37. AlertTriangle,
  38. AlertCircle,
  39. Terminal,
  40. Power,
  41. Zap,
  42. Wrench,
  43. ChevronDown,
  44. Filter,
  45. Pencil,
  46. ArrowLeft,
  47. ArrowRight,
  48. ArrowUp,
  49. ArrowDown,
  50. Layers,
  51. Video,
  52. Search,
  53. Loader2,
  54. Square,
  55. Pause,
  56. Play,
  57. X,
  58. Fan,
  59. Wind,
  60. AirVent,
  61. Download,
  62. ScanSearch,
  63. CheckCircle,
  64. CheckSquare,
  65. XCircle,
  66. User,
  67. Home,
  68. Printer as PrinterIcon,
  69. Info,
  70. Cable,
  71. Flame,
  72. Repeat,
  73. Snowflake,
  74. Gauge,
  75. DoorOpen,
  76. DoorClosed,
  77. Move,
  78. LogIn,
  79. LogOut,
  80. MoreHorizontal,
  81. SlidersHorizontal,
  82. Stethoscope,
  83. ScanEye,
  84. LineChart as LineChartIcon,
  85. LayoutGrid,
  86. MonitorPlay,
  87. ExternalLink,
  88. } from 'lucide-react';
  89. // Aliased: lucide-react already exports a `Link` icon into this module.
  90. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  91. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  92. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  93. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  94. import { Card, CardContent } from '../components/Card';
  95. import { Button } from '../components/Button';
  96. import { ConfirmModal } from '../components/ConfirmModal';
  97. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  98. import { FileManagerModal } from '../components/FileManagerModal';
  99. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  100. import { CameraWall } from '../components/CameraWall';
  101. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  102. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  103. import { AiDetectionModal } from '../components/AiDetectionModal';
  104. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  105. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  106. import { AmsBackupModal } from '../components/AmsBackupModal';
  107. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  108. import type { HeaterSensorKind } from '../api/client';
  109. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  110. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  111. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  112. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  113. import { useToast } from '../contexts/ToastContext';
  114. import { ChamberLight } from '../components/icons/ChamberLight';
  115. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  116. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  117. import { FileUploadModal } from '../components/FileUploadModal';
  118. import { PrintModal } from '../components/PrintModal';
  119. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  120. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
  121. import { getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  122. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  123. import { Collapsible } from '../components/Collapsible';
  124. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  125. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  126. export interface SpoolmanSlotAssignmentRow {
  127. printer_id: number;
  128. ams_id: number;
  129. tray_id: number;
  130. spoolman_spool_id: number;
  131. }
  132. // Color names resolve via getColorName() which reads the backend color_catalog
  133. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  134. // Format K value with 3 decimal places, default to 0.020 if null
  135. function formatKValue(k: number | null | undefined): string {
  136. const value = k ?? 0.020;
  137. return value.toFixed(3);
  138. }
  139. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  140. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  141. const { mode } = useTheme();
  142. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  143. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  144. return (
  145. <span
  146. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  147. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  148. >
  149. {side}
  150. </span>
  151. );
  152. }
  153. // Expand nozzle type codes to material names
  154. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  155. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  156. function nozzleTypeName(type: string, t: (key: string) => string): string {
  157. if (!type) return '';
  158. // Full text names (from main nozzle info)
  159. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  160. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  161. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  162. // 4-char codes (e.g. "HS01"): last 2 digits = material
  163. if (type.length >= 4) {
  164. const material = type.slice(2, 4);
  165. if (material === '00') return t('printers.nozzleStainlessSteel');
  166. if (material === '01') return t('printers.nozzleHardenedSteel');
  167. if (material === '05') return t('printers.nozzleTungstenCarbide');
  168. }
  169. // 2-digit numeric codes
  170. if (type === '00') return t('printers.nozzleStainlessSteel');
  171. if (type === '01') return t('printers.nozzleHardenedSteel');
  172. if (type === '05') return t('printers.nozzleTungstenCarbide');
  173. // 2-char alpha codes: H prefix = hardened steel
  174. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  175. return type;
  176. }
  177. // Parse flow type from nozzle type code
  178. // HH = high flow, HS = standard/normal
  179. function nozzleFlowName(type: string, t: (key: string) => string): string {
  180. if (!type) return '';
  181. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  182. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  183. return '';
  184. }
  185. // Per-slot hover card for nozzle rack
  186. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  187. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  188. slot: import('../api/client').NozzleRackSlot;
  189. index: number;
  190. activeStatus?: boolean;
  191. filamentName?: string;
  192. children: React.ReactNode;
  193. }) {
  194. const { t } = useTranslation();
  195. const [isVisible, setIsVisible] = useState(false);
  196. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  197. const triggerRef = useRef<HTMLDivElement>(null);
  198. const cardRef = useRef<HTMLDivElement>(null);
  199. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  200. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  201. const isMounted = slot.stat === 1;
  202. useEffect(() => {
  203. if (isVisible && triggerRef.current && cardRef.current) {
  204. const triggerRect = triggerRef.current.getBoundingClientRect();
  205. const cardHeight = cardRef.current.offsetHeight;
  206. const headerHeight = 56;
  207. const spaceAbove = triggerRect.top - headerHeight;
  208. const spaceBelow = window.innerHeight - triggerRect.bottom;
  209. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  210. setPosition('bottom');
  211. } else {
  212. setPosition('top');
  213. }
  214. }
  215. }, [isVisible]);
  216. const handleMouseEnter = () => {
  217. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  218. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  219. };
  220. const handleMouseLeave = () => {
  221. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  222. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  223. };
  224. useEffect(() => {
  225. return () => {
  226. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  227. };
  228. }, []);
  229. const filamentCss = parseFilamentColor(slot.filament_color);
  230. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  231. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  232. return (
  233. <div
  234. ref={triggerRef}
  235. className="relative"
  236. onMouseEnter={handleMouseEnter}
  237. onMouseLeave={handleMouseLeave}
  238. >
  239. {children}
  240. {isVisible && (
  241. <div
  242. ref={cardRef}
  243. className={`
  244. absolute left-1/2 -translate-x-1/2 z-50
  245. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  246. animate-in fade-in-0 zoom-in-95 duration-150
  247. `}
  248. style={{ maxWidth: 'calc(100vw - 24px)' }}
  249. >
  250. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  251. {isEmpty ? (
  252. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  253. Slot {index + 1} — Empty
  254. </div>
  255. ) : (
  256. <div className="p-2.5 space-y-1.5">
  257. {/* Diameter */}
  258. <div className="flex items-center justify-between">
  259. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  260. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  261. </div>
  262. {/* Type */}
  263. {typeFull && (
  264. <div className="flex items-center justify-between">
  265. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  266. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  267. </div>
  268. )}
  269. {/* Flow (hide if empty) */}
  270. {flowFull && (
  271. <div className="flex items-center justify-between">
  272. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  273. <span className="text-xs text-white font-semibold">{flowFull}</span>
  274. </div>
  275. )}
  276. {/* Status badge */}
  277. <div className="flex items-center justify-between">
  278. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  279. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  280. activeStatus || isMounted
  281. ? 'bg-green-900/50 text-green-400'
  282. : 'bg-bambu-dark-tertiary text-bambu-gray'
  283. }`}>
  284. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  285. </span>
  286. </div>
  287. {/* Wear (hide if null) */}
  288. {slot.wear != null && (
  289. <div className="flex items-center justify-between">
  290. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  291. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  292. </div>
  293. )}
  294. {/* Max Temp (hide if 0) */}
  295. {slot.max_temp > 0 && (
  296. <div className="flex items-center justify-between">
  297. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  298. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  299. </div>
  300. )}
  301. {/* Serial (hide if empty) */}
  302. {slot.serial_number && (
  303. <div className="flex items-center justify-between">
  304. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  305. <span className="text-[10px] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  306. </div>
  307. )}
  308. {/* Filament: material type + color swatch (hide if no color) */}
  309. {(filamentCss || slot.filament_type) && (
  310. <div className="flex items-center justify-between">
  311. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  312. <div className="flex items-center gap-1">
  313. {filamentCss && (
  314. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  315. )}
  316. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  317. </div>
  318. </div>
  319. )}
  320. </div>
  321. )}
  322. </div>
  323. {/* Arrow pointer */}
  324. <div
  325. className={`
  326. absolute left-1/2 -translate-x-1/2 w-0 h-0
  327. border-l-[6px] border-l-transparent
  328. border-r-[6px] border-r-transparent
  329. ${position === 'top'
  330. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  331. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  332. `}
  333. />
  334. </div>
  335. )}
  336. </div>
  337. );
  338. }
  339. // Dual-nozzle hover card showing L and R nozzle details side by side
  340. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  341. leftSlot?: import('../api/client').NozzleRackSlot;
  342. rightSlot?: import('../api/client').NozzleRackSlot;
  343. activeNozzle: 'L' | 'R';
  344. filamentInfo?: Record<string, { name: string; k: number | null }>;
  345. children: React.ReactNode;
  346. }) {
  347. const { t } = useTranslation();
  348. const [isVisible, setIsVisible] = useState(false);
  349. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  350. const triggerRef = useRef<HTMLDivElement>(null);
  351. const cardRef = useRef<HTMLDivElement>(null);
  352. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  353. useEffect(() => {
  354. if (isVisible && triggerRef.current && cardRef.current) {
  355. const triggerRect = triggerRef.current.getBoundingClientRect();
  356. const cardHeight = cardRef.current.offsetHeight;
  357. const headerHeight = 56;
  358. const spaceAbove = triggerRect.top - headerHeight;
  359. const spaceBelow = window.innerHeight - triggerRect.bottom;
  360. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  361. setPosition('bottom');
  362. } else {
  363. setPosition('top');
  364. }
  365. }
  366. }, [isVisible]);
  367. const handleMouseEnter = () => {
  368. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  369. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  370. };
  371. const handleMouseLeave = () => {
  372. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  373. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  374. };
  375. useEffect(() => {
  376. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  377. }, []);
  378. if (!leftSlot && !rightSlot) return <>{children}</>;
  379. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  380. const isActive = activeNozzle === side;
  381. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  382. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  383. const filamentCss = parseFilamentColor(slot.filament_color);
  384. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  385. return (
  386. <div className="flex-1 space-y-1.5">
  387. <div className={`text-[10px] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  388. {side === 'L' ? t('common.left') : t('common.right')}
  389. </div>
  390. {slot.nozzle_diameter && (
  391. <div className="flex items-center justify-between">
  392. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  393. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  394. </div>
  395. )}
  396. {typeFull && (
  397. <div className="flex items-center justify-between">
  398. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleType')}</span>
  399. <span className="text-[10px] text-white font-semibold">{typeFull}</span>
  400. </div>
  401. )}
  402. {flowFull && (
  403. <div className="flex items-center justify-between">
  404. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  405. <span className="text-[10px] text-white font-semibold">{flowFull}</span>
  406. </div>
  407. )}
  408. <div className="flex items-center justify-between">
  409. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  410. <span className={`text-[10px] font-bold px-1.5 py-0.5 rounded ${
  411. isActive
  412. ? 'bg-green-900/50 text-green-400'
  413. : 'bg-bambu-dark-tertiary text-bambu-gray'
  414. }`}>
  415. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  416. </span>
  417. </div>
  418. {slot.wear != null && (
  419. <div className="flex items-center justify-between">
  420. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleWear')}</span>
  421. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  422. </div>
  423. )}
  424. {/* Serial and max temp only available on the right (removable) nozzle */}
  425. {side === 'R' && slot.max_temp > 0 && (
  426. <div className="flex items-center justify-between">
  427. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  428. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  429. </div>
  430. )}
  431. {side === 'R' && slot.serial_number && (
  432. <div className="flex items-center justify-between">
  433. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  434. <span className="text-[10px] text-white font-mono">{slot.serial_number}</span>
  435. </div>
  436. )}
  437. {(filamentCss || slot.filament_type || slot.filament_id) && (
  438. <div className="flex items-center justify-between">
  439. <span className="text-[10px] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  440. <div className="flex items-center gap-1">
  441. {filamentCss && (
  442. <div className="w-3 h-3 rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  443. )}
  444. <span className="text-[10px] text-white font-semibold truncate max-w-[100px]">
  445. {filamentName || slot.filament_type || slot.filament_id || ''}
  446. </span>
  447. </div>
  448. </div>
  449. )}
  450. </div>
  451. );
  452. };
  453. return (
  454. <div
  455. ref={triggerRef}
  456. className="relative flex-1"
  457. onMouseEnter={handleMouseEnter}
  458. onMouseLeave={handleMouseLeave}
  459. >
  460. {children}
  461. {isVisible && (
  462. <div
  463. ref={cardRef}
  464. className={`
  465. absolute left-1/2 -translate-x-1/2 z-50
  466. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  467. animate-in fade-in-0 zoom-in-95 duration-150
  468. `}
  469. style={{ maxWidth: 'calc(100vw - 24px)' }}
  470. >
  471. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  472. <div className="p-2.5 flex gap-3">
  473. {leftSlot && renderColumn(leftSlot, 'L')}
  474. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  475. {rightSlot && renderColumn(rightSlot, 'R')}
  476. </div>
  477. </div>
  478. {/* Arrow pointer */}
  479. <div
  480. className={`
  481. absolute left-1/2 -translate-x-1/2 w-0 h-0
  482. border-l-[6px] border-l-transparent
  483. border-r-[6px] border-r-transparent
  484. ${position === 'top'
  485. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  486. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  487. `}
  488. />
  489. </div>
  490. )}
  491. </div>
  492. );
  493. }
  494. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  495. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  496. const { t } = useTranslation();
  497. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  498. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  499. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  500. // base — computing it from min(present IDs) shifts everything left when slot 16
  501. // is the one currently mounted (#943).
  502. const rackNozzles = slots.filter(s => s.id >= 2);
  503. const RACK_SIZE = 6;
  504. const RACK_BASE_ID = 16;
  505. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  506. { length: RACK_SIZE },
  507. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  508. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  509. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  510. },
  511. );
  512. return (
  513. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[2_1_190px] flex flex-col justify-center">
  514. <p className="text-[9px] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  515. <div className="flex gap-[3px] justify-center">
  516. {rackSlots.map((slot, i) => {
  517. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  518. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  519. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  520. return (
  521. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  522. <div
  523. className={`w-7 h-7 rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  524. isEmpty
  525. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  526. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  527. }`}
  528. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  529. >
  530. <span className={`text-[10px] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  531. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  532. >
  533. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  534. </span>
  535. </div>
  536. </NozzleSlotHoverCard>
  537. );
  538. })}
  539. </div>
  540. </div>
  541. );
  542. }
  543. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  544. function WaterDropEmpty({ className }: { className?: string }) {
  545. return (
  546. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  547. <path d="M17.8131 0.00538C18.4463 -0.15091 20.3648 3.14642 20.8264 3.84781C25.4187 10.816 35.3089 26.9368 35.9383 34.8694C37.4182 53.5822 11.882 61.3357 2.53721 45.3789C-1.73471 38.0791 0.016 32.2049 3.178 25.0232C6.99221 16.3662 12.6411 7.90372 17.8131 0.00538ZM18.3738 7.24807L17.5881 7.48441C14.4452 12.9431 10.917 18.2341 8.19369 23.9368C4.6808 31.29 1.18317 38.5479 7.69403 45.5657C17.3058 55.9228 34.9847 46.8808 31.4604 32.8681C29.2558 24.0969 22.4207 15.2913 18.3776 7.24807H18.3738Z" fill="#C3C2C1"/>
  548. </svg>
  549. );
  550. }
  551. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  552. function WaterDropHalf({ className }: { className?: string }) {
  553. return (
  554. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  555. <path d="M17.3165 0.0038C17.932 -0.14959 19.7971 3.08645 20.2458 3.77481C24.7103 10.6135 34.3251 26.4346 34.937 34.2198C36.3757 52.5848 11.5505 60.1942 2.46584 44.534C-1.68714 37.3735 0.0148 31.6085 3.08879 24.5603C6.79681 16.0605 12.2884 7.75907 17.3165 0.0038ZM17.8615 7.11561L17.0977 7.34755C14.0423 12.7048 10.6124 17.8974 7.96483 23.4941C4.54975 30.7107 1.14949 37.8337 7.47908 44.721C16.8233 54.8856 34.01 46.0117 30.5838 32.2595C28.4405 23.6512 21.7957 15.0093 17.8652 7.11561H17.8615Z" fill="#C3C2C1"/>
  556. <path d="M5.03547 30.112C9.64453 30.4936 11.632 35.7985 16.4154 35.791C19.6339 35.7873 20.2161 33.2283 22.3853 31.6197C31.6776 24.7286 33.5835 37.4894 27.9881 44.4254C18.1878 56.5653 -1.16063 44.6013 5.03917 30.1158L5.03547 30.112Z" fill="#1F8FEB"/>
  557. </svg>
  558. );
  559. }
  560. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  561. function WaterDropFull({ className }: { className?: string }) {
  562. return (
  563. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  564. <path d="M17.9625 4.48059L4.77216 26.3154L2.08228 40.2175L10.0224 50.8414H23.1594L33.3246 42.1693V30.2455L17.9625 4.48059Z" fill="#1F8FEB"/>
  565. <path d="M17.7948 0.00538C18.4273 -0.15091 20.3438 3.14642 20.8048 3.84781C25.3921 10.816 35.2715 26.9368 35.9001 34.8694C37.3784 53.5822 11.8702 61.3357 2.53562 45.3789C-1.73163 38.0829 0.0134 32.2087 3.1757 25.027C6.98574 16.3662 12.6284 7.90372 17.7948 0.00538ZM18.3549 7.24807L17.57 7.48441C14.4306 12.9431 10.9063 18.2341 8.1859 23.9368C4.67686 31.29 1.18305 38.5479 7.68679 45.5657C17.2881 55.9228 34.9476 46.8808 31.4271 32.8681C29.2249 24.0969 22.3974 15.2913 18.3587 7.24807H18.3549Z" fill="#C3C2C1"/>
  566. </svg>
  567. );
  568. }
  569. // Thermometer SVG - empty outline
  570. function ThermometerEmpty({ className }: { className?: string }) {
  571. return (
  572. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  573. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  574. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  575. </svg>
  576. );
  577. }
  578. // Thermometer SVG - half filled (gold - same as humidity fair)
  579. function ThermometerHalf({ className }: { className?: string }) {
  580. return (
  581. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  582. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  583. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  584. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  585. </svg>
  586. );
  587. }
  588. // Thermometer SVG - fully filled (red - same as humidity bad)
  589. function ThermometerFull({ className }: { className?: string }) {
  590. return (
  591. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  592. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  593. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  594. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  595. </svg>
  596. );
  597. }
  598. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  599. // Added for visual parity with the thermometer icons on the dual-nozzle card
  600. // that previously had no icon at all (#1115, design by @m4rtini2).
  601. function NozzleIcon({ className }: { className?: string }) {
  602. return (
  603. <svg
  604. className={className}
  605. viewBox="0 0 24 24"
  606. fill="none"
  607. xmlns="http://www.w3.org/2000/svg"
  608. stroke="currentColor"
  609. strokeWidth="1.5"
  610. strokeLinecap="round"
  611. strokeLinejoin="round"
  612. >
  613. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  614. <rect x="6" y="11.5" width="12.1" height="3.7" />
  615. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  616. </svg>
  617. );
  618. }
  619. // Heater thermometer icon - filled when heating, outline when off
  620. interface HeaterThermometerProps {
  621. className?: string;
  622. color: string; // The color class (e.g., "text-orange-400")
  623. isHeating: boolean;
  624. }
  625. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  626. // Extract the actual color from Tailwind class for SVG fill
  627. const colorMap: Record<string, string> = {
  628. 'text-orange-400': '#fb923c',
  629. 'text-blue-400': '#60a5fa',
  630. 'text-green-400': '#4ade80',
  631. };
  632. const fillColor = colorMap[color] || '#888';
  633. // Glow style when heating
  634. const glowStyle = isHeating ? {
  635. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  636. } : {};
  637. if (isHeating) {
  638. // Filled thermometer with glow - heater is ON
  639. return (
  640. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  641. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  642. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  643. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  644. </svg>
  645. );
  646. }
  647. // Empty thermometer - heater is OFF
  648. return (
  649. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  650. <path d="M6 0.5C4.6 0.5 3.5 1.6 3.5 3V12.1C2.6 12.8 2 13.9 2 15C2 17.2 3.8 19 6 19C8.2 19 10 17.2 10 15C10 13.9 9.4 12.8 8.5 12.1V3C8.5 1.6 7.4 0.5 6 0.5Z" stroke={fillColor} strokeWidth="1" fill="none"/>
  651. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  652. </svg>
  653. );
  654. }
  655. // AMS Filament Backup tri-state indicator + toggle.
  656. // state=true → ON, click to disable
  657. // state=false → OFF, click opens modal
  658. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  659. interface AmsBackupBadgeProps {
  660. state: boolean | null;
  661. onClick: () => void;
  662. }
  663. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  664. const { t } = useTranslation();
  665. const known = state !== null;
  666. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[10px] transition-colors ';
  667. let title: string;
  668. if (state === true) {
  669. className += known
  670. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  671. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  672. title = t('printers.amsBackup.titleOn');
  673. } else if (state === false) {
  674. className += known
  675. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  676. : 'bg-bambu-dark text-bambu-gray cursor-default';
  677. title = t('printers.amsBackup.titleOff');
  678. } else {
  679. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  680. title = t('printers.amsBackup.titleUnknown');
  681. }
  682. return (
  683. <button
  684. type="button"
  685. disabled={!known}
  686. onClick={() => known && onClick()}
  687. className={className}
  688. title={title}
  689. aria-label={title}
  690. >
  691. {known ? <Repeat className="w-3 h-3" /> : <span>?</span>}
  692. </button>
  693. );
  694. }
  695. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  696. // Reference: https://github.com/theicedmango/bambu-humidity
  697. interface HumidityIndicatorProps {
  698. humidity: number | string;
  699. goodThreshold?: number; // <= this is green
  700. fairThreshold?: number; // <= this is orange, > is red
  701. onClick?: () => void;
  702. compact?: boolean; // Smaller version for grid layout
  703. }
  704. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  705. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  706. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  707. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  708. // Status thresholds (configurable via settings)
  709. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  710. let textColor: string;
  711. let statusText: string;
  712. if (isNaN(humidityValue)) {
  713. textColor = '#C3C2C1';
  714. statusText = 'Unknown';
  715. } else if (humidityValue <= good) {
  716. textColor = '#22a352'; // Green - Good
  717. statusText = 'Good';
  718. } else if (humidityValue <= fair) {
  719. textColor = '#d4a017'; // Gold - Fair
  720. statusText = 'Fair';
  721. } else {
  722. textColor = '#c62828'; // Red - Bad
  723. statusText = 'Bad';
  724. }
  725. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  726. let DropComponent: React.FC<{ className?: string }>;
  727. if (isNaN(humidityValue)) {
  728. DropComponent = WaterDropEmpty;
  729. } else if (humidityValue <= good) {
  730. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  731. } else if (humidityValue <= fair) {
  732. DropComponent = WaterDropHalf; // Fair - half filled
  733. } else {
  734. DropComponent = WaterDropFull; // Bad - full (too humid)
  735. }
  736. return (
  737. <button
  738. type="button"
  739. onClick={onClick}
  740. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  741. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  742. >
  743. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  744. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  745. </button>
  746. );
  747. }
  748. // Temperature indicator with dynamic icon and coloring
  749. interface TemperatureIndicatorProps {
  750. temp: number;
  751. goodThreshold?: number; // <= this is blue
  752. fairThreshold?: number; // <= this is orange, > is red
  753. onClick?: () => void;
  754. compact?: boolean; // Smaller version for grid layout
  755. }
  756. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  757. // Ensure thresholds are numbers
  758. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  759. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  760. let textColor: string;
  761. let statusText: string;
  762. let ThermoComponent: React.FC<{ className?: string }>;
  763. if (temp <= good) {
  764. textColor = '#22a352'; // Green - good (same as humidity)
  765. statusText = 'Good';
  766. ThermoComponent = ThermometerEmpty;
  767. } else if (temp <= fair) {
  768. textColor = '#d4a017'; // Gold - fair (same as humidity)
  769. statusText = 'Fair';
  770. ThermoComponent = ThermometerHalf;
  771. } else {
  772. textColor = '#c62828'; // Red - bad (same as humidity)
  773. statusText = 'Bad';
  774. ThermoComponent = ThermometerFull;
  775. }
  776. return (
  777. <button
  778. type="button"
  779. onClick={onClick}
  780. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  781. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  782. >
  783. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  784. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  785. </button>
  786. );
  787. }
  788. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  789. *
  790. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  791. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  792. * every empty-by-bitmask slot lands here regardless of firmware payload
  793. * shape.
  794. *
  795. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  796. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  797. * the user cleared with "Reset Slot" where a physical spool may still be
  798. * loaded but unassigned.
  799. *
  800. * Returns null when the slot is loaded (tray_type is present).
  801. */
  802. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  803. if (tray?.tray_type) return null;
  804. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  805. // spool the firmware can't identify is physically present (exists === true)
  806. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  807. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  808. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  809. if (tray?.exists === true) return 'reset';
  810. if (tray?.exists === false) return 'physical';
  811. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  812. }
  813. // How long to wait for an AMS to report a live drying cycle after the printer
  814. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  815. // within a couple of seconds; 30s covers the slowest observed push cadence
  816. // without leaving the user waiting on a verdict.
  817. const DRY_START_CONFIRM_MS = 30_000;
  818. function CoverImage({
  819. url,
  820. printName,
  821. className = 'w-20 h-20',
  822. radiusClass = 'rounded-lg',
  823. }: {
  824. url: string | null;
  825. printName?: string;
  826. className?: string;
  827. radiusClass?: string;
  828. }) {
  829. const { t } = useTranslation();
  830. const [loaded, setLoaded] = useState(false);
  831. const [error, setError] = useState(false);
  832. const [showOverlay, setShowOverlay] = useState(false);
  833. // Cache-bust the image URL when the print name changes so the browser
  834. // fetches the new cover instead of serving the stale cached image.
  835. const cacheBustedUrl = useMemo(() => {
  836. if (!url) return null;
  837. const sep = url.includes('?') ? '&' : '?';
  838. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  839. }, [url, printName]);
  840. // Reset loaded/error state when the image URL changes
  841. useEffect(() => {
  842. setLoaded(false);
  843. setError(false);
  844. }, [cacheBustedUrl]);
  845. return (
  846. <>
  847. <div
  848. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  849. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  850. >
  851. {cacheBustedUrl && !error ? (
  852. <>
  853. <img
  854. src={cacheBustedUrl}
  855. alt={t('printers.printPreview')}
  856. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  857. onLoad={() => setLoaded(true)}
  858. onError={() => setError(true)}
  859. />
  860. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  861. </>
  862. ) : (
  863. <Box className="w-8 h-8 text-bambu-gray" />
  864. )}
  865. </div>
  866. {/* Cover Image Overlay */}
  867. {showOverlay && cacheBustedUrl && (
  868. <div
  869. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  870. onClick={() => setShowOverlay(false)}
  871. >
  872. <div className="relative max-w-2xl max-h-full">
  873. <img
  874. src={cacheBustedUrl}
  875. alt={t('printers.printPreview')}
  876. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  877. />
  878. {printName && (
  879. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  880. )}
  881. </div>
  882. </div>
  883. )}
  884. </>
  885. );
  886. }
  887. interface PrinterMaintenanceInfo {
  888. due_count: number;
  889. warning_count: number;
  890. total_print_hours: number;
  891. }
  892. // Status summary bar component - uses queryClient to read cached statuses
  893. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  894. const { t } = useTranslation();
  895. const queryClient = useQueryClient();
  896. // Subscribe to query cache changes to re-render when status updates
  897. // Throttled to prevent rapid re-renders from causing tab crashes
  898. const [cacheTick, setCacheTick] = useState(0);
  899. useEffect(() => {
  900. let pending = false;
  901. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  902. if (!pending) {
  903. pending = true;
  904. requestAnimationFrame(() => {
  905. setCacheTick(t => t + 1);
  906. pending = false;
  907. });
  908. }
  909. });
  910. return () => unsubscribe();
  911. }, [queryClient]);
  912. const { counts, nextFinish } = useMemo(() => {
  913. let printing = 0;
  914. let paused = 0;
  915. let finished = 0;
  916. let idle = 0;
  917. let offline = 0;
  918. let loading = 0;
  919. let error = 0;
  920. let nextPrinterName: string | null = null;
  921. let nextRemainingMin: number | null = null;
  922. let nextProgress: number = 0;
  923. printers?.forEach((printer) => {
  924. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  925. if (status === undefined) {
  926. // Status not yet loaded - don't count as offline yet
  927. loading++;
  928. } else if (!status.connected) {
  929. offline++;
  930. } else {
  931. // Count printers with active HMS errors as problems
  932. const knownHmsCount =
  933. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  934. if (knownHmsCount > 0) {
  935. error++;
  936. }
  937. switch (status.state) {
  938. case 'RUNNING':
  939. printing++;
  940. if (status.remaining_time != null && status.remaining_time > 0) {
  941. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  942. nextRemainingMin = status.remaining_time;
  943. nextPrinterName = printer.name;
  944. nextProgress = status.progress || 0;
  945. }
  946. }
  947. break;
  948. case 'PAUSE':
  949. paused++;
  950. break;
  951. case 'FINISH':
  952. finished++;
  953. break;
  954. case 'FAILED':
  955. // FAILED is the printer's terminal gcode_state after a print stops —
  956. // including user cancellations, where there's no actual fault. Only
  957. // count it as a "problem" when an HMS error is also active; otherwise
  958. // it's just a print that ended unsuccessfully and the plate needs
  959. // clearing (same as FINISH from the operator's perspective).
  960. if (knownHmsCount > 0) {
  961. // Already counted above
  962. } else {
  963. finished++;
  964. }
  965. break;
  966. default:
  967. idle++;
  968. break;
  969. }
  970. }
  971. });
  972. return {
  973. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  974. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  975. };
  976. // eslint-disable-next-line react-hooks/exhaustive-deps
  977. }, [printers, queryClient, cacheTick]);
  978. if (!printers?.length) return null;
  979. const badges: { count: number; dot: string; label: string }[] = [
  980. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  981. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  982. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  983. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  984. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  985. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  986. ];
  987. return (
  988. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  989. {badges.map(({ count, dot, label }) => count > 0 && (
  990. <div key={label} className="flex items-center gap-1.5">
  991. <div className={`w-2 h-2 rounded-full ${dot}`} />
  992. <span className="text-bambu-gray">
  993. <span className="text-white font-medium">{count}</span> {label}
  994. </span>
  995. </div>
  996. ))}
  997. {nextFinish && (
  998. <>
  999. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1000. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1001. <div className="flex items-center gap-2">
  1002. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1003. <span className="text-white font-medium">{nextFinish.name}</span>
  1004. </div>
  1005. <div className="flex items-center gap-2 w-full sm:w-auto">
  1006. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1007. <div
  1008. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1009. style={{ width: `${nextFinish.progress}%` }}
  1010. />
  1011. </div>
  1012. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1013. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1014. </div>
  1015. </div>
  1016. </>
  1017. )}
  1018. </div>
  1019. );
  1020. }
  1021. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1022. type ViewMode = 'expanded' | 'compact';
  1023. type ToolbarDropdownOption<T extends string> = {
  1024. value: T;
  1025. label: string;
  1026. };
  1027. function ToolbarDropdown<T extends string>({
  1028. value,
  1029. options,
  1030. onChange,
  1031. fullWidth = false,
  1032. }: {
  1033. value: T;
  1034. options: ToolbarDropdownOption<T>[];
  1035. onChange: (value: T) => void;
  1036. fullWidth?: boolean;
  1037. }) {
  1038. const [isOpen, setIsOpen] = useState(false);
  1039. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1040. return (
  1041. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1042. <button
  1043. type="button"
  1044. onClick={() => setIsOpen(open => !open)}
  1045. className={`h-8 px-2 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white text-sm font-medium transition-colors hover:bg-bambu-dark-tertiary focus:outline-none focus:border-bambu-green flex items-center justify-between gap-2 ${fullWidth ? 'w-full' : 'min-w-28'}`}
  1046. >
  1047. <span className="truncate">{selectedOption?.label}</span>
  1048. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1049. </button>
  1050. {isOpen && (
  1051. <>
  1052. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1053. <div className="absolute left-0 top-full z-20 mt-1 min-w-full rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary py-1 shadow-xl">
  1054. {options.map(option => (
  1055. <button
  1056. key={option.value}
  1057. type="button"
  1058. onClick={() => {
  1059. onChange(option.value);
  1060. setIsOpen(false);
  1061. }}
  1062. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1063. option.value === value ? 'text-bambu-green' : 'text-white'
  1064. }`}
  1065. >
  1066. {option.label}
  1067. </button>
  1068. ))}
  1069. </div>
  1070. </>
  1071. )}
  1072. </div>
  1073. );
  1074. }
  1075. function ToolbarMenu({
  1076. label,
  1077. icon,
  1078. children,
  1079. }: {
  1080. label: string;
  1081. icon: React.ReactNode;
  1082. children: React.ReactNode;
  1083. }) {
  1084. const [isOpen, setIsOpen] = useState(false);
  1085. return (
  1086. <div className="relative">
  1087. <button
  1088. type="button"
  1089. onClick={() => setIsOpen(open => !open)}
  1090. className="h-8 w-8 rounded-lg border bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center justify-center"
  1091. aria-label={label}
  1092. title={label}
  1093. >
  1094. {icon}
  1095. </button>
  1096. {isOpen && (
  1097. <>
  1098. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1099. <div className="absolute right-0 top-full z-20 mt-1 min-w-40 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-2 shadow-xl">
  1100. {children}
  1101. </div>
  1102. </>
  1103. )}
  1104. </div>
  1105. );
  1106. }
  1107. function IndicatorControlPopover({
  1108. title,
  1109. options = [],
  1110. unit,
  1111. customMin,
  1112. customMax,
  1113. customStep = 1,
  1114. widthClass = 'w-[240px]',
  1115. popoverWidth = 240,
  1116. popoverHeight = 280,
  1117. isPending,
  1118. onClose,
  1119. onSubmit,
  1120. children,
  1121. }: {
  1122. title: string;
  1123. options?: Array<{ label: string; value: number }>;
  1124. unit?: string;
  1125. customMin?: number;
  1126. customMax?: number;
  1127. customStep?: number;
  1128. widthClass?: string;
  1129. popoverWidth?: number;
  1130. popoverHeight?: number;
  1131. isPending?: boolean;
  1132. onClose: () => void;
  1133. onSubmit?: (value: number) => void;
  1134. children?: React.ReactNode;
  1135. }) {
  1136. const anchorRef = useRef<HTMLSpanElement>(null);
  1137. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1138. const [customValue, setCustomValue] = useState('');
  1139. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1140. // can position via fixed coords. Portaling to document.body escapes
  1141. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1142. // own contexts and would otherwise cover the popover even at z-[60].
  1143. useLayoutEffect(() => {
  1144. const trigger = anchorRef.current?.parentElement;
  1145. if (!trigger) return;
  1146. const measure = () => {
  1147. const rect = trigger.getBoundingClientRect();
  1148. setCoords(computePopoverPosition({
  1149. triggerRect: rect,
  1150. popoverWidth,
  1151. estimatedHeight: popoverHeight,
  1152. horizontalAlign: 'center',
  1153. }));
  1154. };
  1155. measure();
  1156. window.addEventListener('resize', measure);
  1157. window.addEventListener('scroll', measure, true);
  1158. return () => {
  1159. window.removeEventListener('resize', measure);
  1160. window.removeEventListener('scroll', measure, true);
  1161. };
  1162. }, [popoverWidth, popoverHeight]);
  1163. const showCustomInput = unit !== undefined;
  1164. const submitCustom = () => {
  1165. const value = Number(customValue);
  1166. if (!Number.isFinite(value)) return;
  1167. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1168. onSubmit?.(Math.round(bounded));
  1169. };
  1170. return (
  1171. <>
  1172. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1173. {createPortal(
  1174. <>
  1175. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1176. <div
  1177. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1178. style={{
  1179. top: coords?.top ?? -9999,
  1180. left: coords?.left ?? -9999,
  1181. visibility: coords ? 'visible' : 'hidden',
  1182. }}
  1183. onClick={e => e.stopPropagation()}
  1184. >
  1185. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1186. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1187. {options.length > 0 && (
  1188. <div className="px-3 py-2.5">
  1189. <div className="grid grid-cols-2 gap-1.5">
  1190. {options.map(option => (
  1191. <button
  1192. key={`${option.label}-${option.value}`}
  1193. type="button"
  1194. disabled={isPending}
  1195. onClick={() => onSubmit?.(option.value)}
  1196. className="h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1197. >
  1198. {option.label}
  1199. </button>
  1200. ))}
  1201. </div>
  1202. </div>
  1203. )}
  1204. {children}
  1205. {showCustomInput && (
  1206. <>
  1207. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1208. <form
  1209. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1210. onSubmit={(e) => {
  1211. e.preventDefault();
  1212. submitCustom();
  1213. }}
  1214. >
  1215. <input
  1216. type="number"
  1217. min={customMin}
  1218. max={customMax}
  1219. step={customStep}
  1220. value={customValue}
  1221. onChange={e => setCustomValue(e.target.value)}
  1222. placeholder="Custom"
  1223. className="h-8 min-w-0 flex-1 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none"
  1224. />
  1225. <button
  1226. type="submit"
  1227. disabled={isPending || customValue.trim() === ''}
  1228. className="h-8 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark px-2 text-xs font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1229. >
  1230. Set
  1231. </button>
  1232. </form>
  1233. </>
  1234. )}
  1235. </div>
  1236. </>,
  1237. document.body
  1238. )}
  1239. </>
  1240. );
  1241. }
  1242. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1243. function NozzleTemperatureControlBox({
  1244. label,
  1245. current,
  1246. target,
  1247. isActive,
  1248. isPending,
  1249. onSubmit,
  1250. options = NOZZLE_TEMPERATURE_OPTIONS,
  1251. }: {
  1252. label: string;
  1253. current?: number;
  1254. target?: number;
  1255. isActive: boolean;
  1256. isPending?: boolean;
  1257. onSubmit: (value: number) => void;
  1258. options?: Array<{ label: string; value: number }>;
  1259. }) {
  1260. const [customValue, setCustomValue] = useState('');
  1261. const submitCustom = () => {
  1262. const value = Number(customValue);
  1263. if (!Number.isFinite(value)) return;
  1264. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1265. };
  1266. return (
  1267. <div className={`rounded-lg border p-2 ${isActive ? 'border-amber-500/60 dark:border-amber-400/60 bg-amber-50 dark:bg-amber-400/10' : 'border-bambu-dark-tertiary bg-bambu-dark'}`}>
  1268. <div className="mb-1.5 flex items-center justify-between gap-2">
  1269. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1270. <span className="text-[10px] text-bambu-gray">
  1271. {Math.round(current ?? 0)}°C
  1272. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1273. </span>
  1274. </div>
  1275. <div className="grid grid-cols-2 gap-1">
  1276. {options.map(option => (
  1277. <button
  1278. key={`${label}-${option.value}`}
  1279. type="button"
  1280. disabled={isPending}
  1281. onClick={() => onSubmit(option.value)}
  1282. className="h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1283. >
  1284. {option.label}
  1285. </button>
  1286. ))}
  1287. </div>
  1288. <form
  1289. className="mt-1.5 flex gap-1"
  1290. onSubmit={(e) => {
  1291. e.preventDefault();
  1292. submitCustom();
  1293. }}
  1294. >
  1295. <input
  1296. type="number"
  1297. min={0}
  1298. max={320}
  1299. step={1}
  1300. value={customValue}
  1301. onChange={e => setCustomValue(e.target.value)}
  1302. placeholder="Custom"
  1303. className="h-7 min-w-0 flex-1 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-1.5 text-[11px] text-white placeholder:text-bambu-gray/60 focus:border-bambu-green focus:outline-none"
  1304. />
  1305. <button
  1306. type="submit"
  1307. disabled={isPending || customValue.trim() === ''}
  1308. className="h-7 rounded-md border border-bambu-dark-tertiary bg-bambu-dark-secondary px-2 text-[11px] font-medium text-white transition-colors hover:bg-bambu-dark-tertiary disabled:cursor-not-allowed disabled:opacity-50"
  1309. >
  1310. Set
  1311. </button>
  1312. </form>
  1313. </div>
  1314. );
  1315. }
  1316. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1317. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1318. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1319. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1320. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1321. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1322. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1323. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1324. };
  1325. /** Classify a printer into one of the UI status buckets. */
  1326. function classifyPrinterStatus(
  1327. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1328. ): PrinterState {
  1329. if (!status?.connected) return 'offline';
  1330. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1331. if (hmsErrors.length > 0) return 'error';
  1332. switch (status.state) {
  1333. case 'RUNNING': return 'printing';
  1334. case 'PAUSE': return 'paused';
  1335. case 'FINISH': return 'finished';
  1336. // FAILED without an active HMS error is the printer's terminal state after
  1337. // any unsuccessful end — including user-cancellations. Treat the same as
  1338. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1339. // HMS code is actually attached (handled by the early-return above).
  1340. case 'FAILED': return 'finished';
  1341. default: return 'idle';
  1342. }
  1343. }
  1344. /**
  1345. * Get human-readable status display text for a printer.
  1346. * Uses stg_cur_name for detailed calibration/preparation stages,
  1347. * otherwise formats the gcode_state nicely.
  1348. */
  1349. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1350. // If we have a specific stage name (calibration, heating, etc.), use it
  1351. if (stg_cur_name) {
  1352. return stg_cur_name;
  1353. }
  1354. // Format the gcode_state nicely
  1355. switch (state) {
  1356. case 'RUNNING':
  1357. return 'Printing';
  1358. case 'PAUSE':
  1359. return 'Paused';
  1360. case 'FINISH':
  1361. return 'Finished';
  1362. case 'FAILED':
  1363. return 'Failed';
  1364. case 'IDLE':
  1365. return 'Idle';
  1366. default:
  1367. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1368. }
  1369. }
  1370. // Bambu models that ship with an enclosure chamber fan (firmware field
  1371. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1372. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1373. // widget is hidden in fanItems instead of rendered greyed-out.
  1374. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1375. 'X1C',
  1376. 'X1',
  1377. 'X1E',
  1378. 'X2D',
  1379. 'P1S',
  1380. 'P2S',
  1381. 'H2D',
  1382. 'H2D Pro',
  1383. 'H2C',
  1384. 'H2S',
  1385. ]);
  1386. // Map SSDP model codes to display names
  1387. function mapModelCode(ssdpModel: string | null): string {
  1388. if (!ssdpModel) return '';
  1389. const modelMap: Record<string, string> = {
  1390. // H2 Series
  1391. 'O1D': 'H2D',
  1392. 'O1E': 'H2D Pro',
  1393. 'O2D': 'H2D Pro',
  1394. 'O1C': 'H2C',
  1395. 'O1C2': 'H2C',
  1396. 'O1S': 'H2S',
  1397. // X1 Series
  1398. 'BL-P001': 'X1C',
  1399. 'BL-P002': 'X1',
  1400. 'BL-P003': 'X1E',
  1401. // X2 Series
  1402. 'N6': 'X2D',
  1403. // A2 Series
  1404. 'N9': 'A2L',
  1405. // P Series
  1406. 'C11': 'P1S',
  1407. 'C12': 'P1P',
  1408. 'C13': 'P2S',
  1409. // A1 Series
  1410. 'N2S': 'A1',
  1411. 'N1': 'A1 Mini',
  1412. // Direct matches
  1413. 'X1C': 'X1C',
  1414. 'X1': 'X1',
  1415. 'X1E': 'X1E',
  1416. 'X2D': 'X2D',
  1417. 'P1S': 'P1S',
  1418. 'P1P': 'P1P',
  1419. 'P2S': 'P2S',
  1420. 'A1': 'A1',
  1421. 'A1 Mini': 'A1 Mini',
  1422. 'A2L': 'A2L',
  1423. 'H2D': 'H2D',
  1424. 'H2D Pro': 'H2D Pro',
  1425. 'H2C': 'H2C',
  1426. 'H2S': 'H2S',
  1427. };
  1428. return modelMap[ssdpModel] || ssdpModel;
  1429. }
  1430. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1431. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1432. // • User-defined friendly name (editable, protected by printers:update)
  1433. // • AMS serial number
  1434. // • AMS firmware version
  1435. export function AmsNameHoverCard({
  1436. ams,
  1437. printerId,
  1438. label,
  1439. amsLabels,
  1440. canEdit,
  1441. onSaved,
  1442. children,
  1443. }: {
  1444. ams: import('../api/client').AMSUnit;
  1445. printerId: number;
  1446. label: string; // auto-generated label, e.g. "AMS-A"
  1447. amsLabels?: Record<number, string>;
  1448. canEdit: boolean;
  1449. onSaved: () => void;
  1450. children: React.ReactNode;
  1451. }) {
  1452. const { t } = useTranslation();
  1453. const [isVisible, setIsVisible] = useState(false);
  1454. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1455. const [editValue, setEditValue] = useState('');
  1456. const [isSaving, setIsSaving] = useState(false);
  1457. const [saveError, setSaveError] = useState<string | null>(null);
  1458. const [isInputFocused, setIsInputFocused] = useState(false);
  1459. const triggerRef = useRef<HTMLDivElement>(null);
  1460. const cardRef = useRef<HTMLDivElement>(null);
  1461. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1462. useEffect(() => {
  1463. if (isVisible) {
  1464. setEditValue(amsLabels?.[ams.id] ?? '');
  1465. setSaveError(null);
  1466. requestAnimationFrame(() => {
  1467. if (triggerRef.current && cardRef.current) {
  1468. const rect = triggerRef.current.getBoundingClientRect();
  1469. const spaceAbove = rect.top - 56;
  1470. const spaceBelow = window.innerHeight - rect.bottom;
  1471. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1472. }
  1473. });
  1474. }
  1475. }, [isVisible, amsLabels, ams.id]);
  1476. const handleMouseEnter = () => {
  1477. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1478. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1479. };
  1480. const handleMouseLeave = () => {
  1481. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1482. if (!isInputFocused) {
  1483. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1484. }
  1485. };
  1486. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1487. const handleSave = async () => {
  1488. if (!canEdit) return;
  1489. setIsSaving(true);
  1490. setSaveError(null);
  1491. try {
  1492. const trimmed = editValue.trim();
  1493. if (trimmed) {
  1494. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1495. } else {
  1496. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1497. }
  1498. onSaved();
  1499. setIsVisible(false);
  1500. } catch (err) {
  1501. setSaveError(err instanceof Error ? err.message : String(err));
  1502. } finally {
  1503. setIsSaving(false);
  1504. }
  1505. };
  1506. const handleClear = async () => {
  1507. if (!canEdit) return;
  1508. setIsSaving(true);
  1509. setSaveError(null);
  1510. try {
  1511. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1512. onSaved();
  1513. setIsVisible(false);
  1514. } catch (err) {
  1515. setSaveError(err instanceof Error ? err.message : String(err));
  1516. } finally {
  1517. setIsSaving(false);
  1518. }
  1519. };
  1520. return (
  1521. <div
  1522. ref={triggerRef}
  1523. className="relative inline-block"
  1524. onMouseEnter={handleMouseEnter}
  1525. onMouseLeave={handleMouseLeave}
  1526. >
  1527. {children}
  1528. {isVisible && (
  1529. <div
  1530. ref={cardRef}
  1531. className={`
  1532. absolute left-0 z-50
  1533. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1534. animate-in fade-in-0 zoom-in-95 duration-150
  1535. `}
  1536. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1537. onMouseEnter={handleMouseEnter}
  1538. onMouseLeave={handleMouseLeave}
  1539. >
  1540. <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">
  1541. {/* AMS auto-label */}
  1542. <div className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1543. {/* Serial number */}
  1544. <div className="flex items-center justify-between gap-2">
  1545. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1546. {t('printers.amsPopup.serialNumber')}
  1547. </span>
  1548. <span className="text-[10px] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1549. </div>
  1550. {/* Firmware version */}
  1551. <div className="flex items-center justify-between gap-2">
  1552. <span className="text-[10px] tracking-wide text-bambu-gray font-medium shrink-0">
  1553. {t('printers.amsPopup.firmwareVersion')}
  1554. </span>
  1555. <span className="text-[10px] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1556. </div>
  1557. {/* Friendly name editor */}
  1558. <div className="space-y-1">
  1559. <div className="flex items-center gap-2">
  1560. <span className="text-[10px] text-bambu-gray font-medium shrink-0">
  1561. {t('printers.amsPopup.friendlyName')}
  1562. </span>
  1563. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1564. </div>
  1565. <input
  1566. type="text"
  1567. value={editValue}
  1568. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1569. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1570. onFocus={() => setIsInputFocused(true)}
  1571. onBlur={() => {
  1572. setIsInputFocused(false);
  1573. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1574. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1575. }}
  1576. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1577. disabled={!canEdit}
  1578. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1579. 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"
  1580. maxLength={100}
  1581. />
  1582. {canEdit && (
  1583. <div className="space-y-1">
  1584. {saveError && (
  1585. <p className="text-[10px] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1586. )}
  1587. <div className="flex gap-1 justify-end">
  1588. <button
  1589. onClick={handleSave}
  1590. disabled={isSaving}
  1591. className="px-2 py-0.5 text-[10px] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1592. >
  1593. {t('printers.amsPopup.save')}
  1594. </button>
  1595. {amsLabels?.[ams.id] && (
  1596. <button
  1597. onClick={handleClear}
  1598. disabled={isSaving}
  1599. className="px-2 py-0.5 text-[10px] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1600. >
  1601. {t('printers.amsPopup.clear')}
  1602. </button>
  1603. )}
  1604. </div>
  1605. </div>
  1606. )}
  1607. </div>
  1608. </div>
  1609. </div>
  1610. )}
  1611. </div>
  1612. );
  1613. }
  1614. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1615. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1616. const DRYING_PRESETS: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }> = {
  1617. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1618. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1619. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1620. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1621. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1622. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1623. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1624. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1625. };
  1626. function PrinterCard({
  1627. printer,
  1628. hideIfDisconnected,
  1629. maintenanceInfo,
  1630. viewMode = 'expanded',
  1631. cardSize = 2,
  1632. amsThresholds,
  1633. spoolmanEnabled = false,
  1634. linkedSpools,
  1635. spoolmanUrl,
  1636. spoolmanSyncMode,
  1637. onGetAssignment,
  1638. onUnassignSpool,
  1639. spoolmanSpools,
  1640. spoolmanSlotAssignments,
  1641. spoolmanLoading = false,
  1642. onUnassignSpoolmanSpool,
  1643. timeFormat = 'system',
  1644. cameraViewMode = 'window',
  1645. onOpenEmbeddedCamera,
  1646. checkPrinterFirmware = true,
  1647. dryingPresets = DRYING_PRESETS,
  1648. requirePlateClear = false,
  1649. selectionMode = false,
  1650. isSelected = false,
  1651. onToggleSelect,
  1652. onOpenCompactCard,
  1653. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1654. bedTempPresets = BED_TEMP_DEFAULTS,
  1655. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1656. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1657. aiDetectionEnabled = false,
  1658. aiDetection,
  1659. aiLastError = null,
  1660. }: {
  1661. printer: Printer;
  1662. hideIfDisconnected?: boolean;
  1663. maintenanceInfo?: PrinterMaintenanceInfo;
  1664. viewMode?: ViewMode;
  1665. cardSize?: number;
  1666. amsThresholds?: {
  1667. humidityGood: number;
  1668. humidityFair: number;
  1669. tempGood: number;
  1670. tempFair: number;
  1671. };
  1672. spoolmanEnabled?: boolean;
  1673. hasUnlinkedSpools?: boolean;
  1674. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1675. spoolmanUrl?: string | null;
  1676. spoolmanSyncMode?: string | null;
  1677. spoolAssignments?: SpoolAssignment[];
  1678. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1679. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1680. spoolmanSpools?: InventorySpool[];
  1681. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1682. spoolmanLoading?: boolean;
  1683. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1684. timeFormat?: 'system' | '12h' | '24h';
  1685. cameraViewMode?: 'window' | 'embedded';
  1686. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1687. checkPrinterFirmware?: boolean;
  1688. dryingPresets?: Record<string, { n3f: number; n3s: number; n3f_hours: number; n3s_hours: number }>;
  1689. requirePlateClear?: boolean;
  1690. selectionMode?: boolean;
  1691. isSelected?: boolean;
  1692. onToggleSelect?: (id: number) => void;
  1693. onOpenCompactCard?: (id: number) => void;
  1694. nozzleTempPresets?: readonly [number, number, number];
  1695. bedTempPresets?: readonly [number, number, number];
  1696. chamberTempPresets?: readonly [number, number, number];
  1697. fanSpeedPresets?: readonly [number, number, number];
  1698. aiDetectionEnabled?: boolean;
  1699. aiDetection?: { class: string; frame_count: number; score: number };
  1700. aiLastError?: string | null;
  1701. }) {
  1702. const { t } = useTranslation();
  1703. const queryClient = useQueryClient();
  1704. const navigate = useNavigate();
  1705. const { showToast } = useToast();
  1706. const { hasPermission } = useAuth();
  1707. const [showMenu, setShowMenu] = useState(false);
  1708. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1709. const [deleteArchives, setDeleteArchives] = useState(true);
  1710. const [showEditModal, setShowEditModal] = useState(false);
  1711. const [showFileManager, setShowFileManager] = useState(false);
  1712. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1713. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1714. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1715. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1716. const [showHMSModal, setShowHMSModal] = useState(false);
  1717. // #1546: AI failure detection modal — opens from the AI badge.
  1718. const [showAiModal, setShowAiModal] = useState(false);
  1719. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1720. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1721. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1722. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1723. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1724. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1725. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1726. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1727. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1728. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1729. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1730. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1731. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1732. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1733. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1734. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1735. // AMS drying popover state: which AMS unit has the popover open
  1736. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1737. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1738. const [dryingFilament, setDryingFilament] = useState('PLA');
  1739. const [dryingTemp, setDryingTemp] = useState(50);
  1740. const [dryingDuration, setDryingDuration] = useState(4);
  1741. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1742. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1743. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  1744. // an object rather than a bare id so restarting drying on the SAME unit produces
  1745. // a new identity and rearms the timeout below.
  1746. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  1747. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1748. const [isDropUploading, setIsDropUploading] = useState(false);
  1749. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1750. const dragCounterRef = useRef(0);
  1751. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1752. amsId: number;
  1753. amsLabel: string;
  1754. mode: 'humidity' | 'temperature';
  1755. } | null>(null);
  1756. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1757. initialKind: HeaterSensorKind;
  1758. availableKinds: HeaterSensorKind[];
  1759. } | null>(null);
  1760. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1761. tagUid: string;
  1762. trayUuid: string;
  1763. printerId: number;
  1764. amsId: number;
  1765. trayId: number;
  1766. } | null>(null);
  1767. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1768. printerId: number;
  1769. amsId: number;
  1770. trayId: number;
  1771. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1772. } | null>(null);
  1773. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1774. amsId: number;
  1775. trayId: number;
  1776. trayCount: number;
  1777. trayType?: string;
  1778. trayColor?: string;
  1779. traySubBrands?: string;
  1780. trayInfoIdx?: string;
  1781. extruderId?: number;
  1782. caliIdx?: number | null;
  1783. savedPresetId?: string;
  1784. } | null>(null);
  1785. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1786. const [plateCheckResult, setPlateCheckResult] = useState<{
  1787. is_empty: boolean;
  1788. confidence: number;
  1789. difference_percent: number;
  1790. message: string;
  1791. debug_image_url?: string;
  1792. needs_calibration: boolean;
  1793. light_warning?: boolean;
  1794. reference_count?: number;
  1795. max_references?: number;
  1796. roi?: { x: number; y: number; w: number; h: number };
  1797. } | null>(null);
  1798. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1799. const [isCalibrating, setIsCalibrating] = useState(false);
  1800. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1801. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1802. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1803. const { data: status } = useQuery({
  1804. queryKey: ['printerStatus', printer.id],
  1805. queryFn: () => api.getPrinterStatus(printer.id),
  1806. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1807. });
  1808. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1809. const { data: firmwareInfo } = useQuery({
  1810. queryKey: ['firmwareUpdate', printer.id],
  1811. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1812. staleTime: 5 * 60 * 1000,
  1813. refetchInterval: 5 * 60 * 1000,
  1814. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1815. });
  1816. // Collect unique tray_info_idx values for cloud filament info lookup
  1817. const trayInfoIds = useMemo(() => {
  1818. const ids = new Set<string>();
  1819. if (status?.ams) {
  1820. for (const ams of status.ams) {
  1821. for (const tray of ams.tray || []) {
  1822. if (tray.tray_info_idx) {
  1823. ids.add(tray.tray_info_idx);
  1824. }
  1825. }
  1826. }
  1827. }
  1828. for (const vt of status?.vt_tray ?? []) {
  1829. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1830. }
  1831. if (status?.nozzle_rack) {
  1832. for (const slot of status.nozzle_rack) {
  1833. if (slot.filament_id) {
  1834. ids.add(slot.filament_id);
  1835. }
  1836. }
  1837. }
  1838. return Array.from(ids);
  1839. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1840. // Collect loaded filament types for queue widget filtering
  1841. const loadedFilamentTypes = useMemo(() => {
  1842. const types = new Set<string>();
  1843. if (status?.ams) {
  1844. for (const ams of status.ams) {
  1845. for (const tray of ams.tray || []) {
  1846. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1847. }
  1848. }
  1849. }
  1850. for (const vt of status?.vt_tray ?? []) {
  1851. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1852. }
  1853. return types;
  1854. }, [status?.ams, status?.vt_tray]);
  1855. // Collect loaded filament type+color pairs for queue widget override matching
  1856. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  1857. const loadedFilaments = useMemo(() => {
  1858. const filaments = new Set<string>();
  1859. if (status?.ams) {
  1860. for (const ams of status.ams) {
  1861. for (const tray of ams.tray || []) {
  1862. if (tray.tray_type && tray.tray_color) {
  1863. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1864. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  1865. }
  1866. }
  1867. }
  1868. }
  1869. for (const vt of status?.vt_tray ?? []) {
  1870. if (vt.tray_type && vt.tray_color) {
  1871. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1872. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  1873. }
  1874. }
  1875. return filaments;
  1876. }, [status?.ams, status?.vt_tray]);
  1877. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  1878. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  1879. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  1880. const loadedVariants = useMemo(() => {
  1881. const variants = new Set<string>();
  1882. if (status?.ams) {
  1883. for (const ams of status.ams) {
  1884. for (const tray of ams.tray || []) {
  1885. if (tray.tray_type && tray.tray_color) {
  1886. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1887. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  1888. }
  1889. }
  1890. }
  1891. }
  1892. for (const vt of status?.vt_tray ?? []) {
  1893. if (vt.tray_type && vt.tray_color) {
  1894. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  1895. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  1896. }
  1897. }
  1898. return variants;
  1899. }, [status?.ams, status?.vt_tray]);
  1900. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  1901. const { data: filamentInfo } = useQuery({
  1902. queryKey: ['filamentInfo', trayInfoIds],
  1903. queryFn: () => api.getFilamentInfo(trayInfoIds),
  1904. enabled: trayInfoIds.length > 0,
  1905. staleTime: 5 * 60 * 1000, // 5 minutes
  1906. });
  1907. // Fetch slot preset mappings (stores preset name for user-configured slots)
  1908. const { data: slotPresets } = useQuery({
  1909. queryKey: ['slotPresets', printer.id],
  1910. queryFn: () => api.getSlotPresets(printer.id),
  1911. staleTime: 2 * 60 * 1000, // 2 minutes
  1912. });
  1913. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  1914. // Only queried when there's a running print backed by an archive; shared
  1915. // React Query cache with the Queue / Archives pages keeps it cheap.
  1916. const activeArchiveId =
  1917. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  1918. const { data: activeArchivePlates } = useQuery({
  1919. queryKey: ['archive-plates', activeArchiveId],
  1920. queryFn: () => api.getArchivePlates(activeArchiveId!),
  1921. enabled: activeArchiveId != null,
  1922. staleTime: 5 * 60 * 1000,
  1923. });
  1924. const activePlateLabel = (() => {
  1925. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  1926. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  1927. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  1928. })();
  1929. // Fetch user-defined AMS friendly names from the database
  1930. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  1931. queryKey: ['amsLabels', printer.id],
  1932. queryFn: () => api.getAmsLabels(printer.id),
  1933. staleTime: 5 * 60 * 1000, // 5 minutes
  1934. });
  1935. // Cache WiFi signal to prevent it disappearing on updates
  1936. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  1937. useEffect(() => {
  1938. if (status?.wifi_signal != null) {
  1939. setCachedWifiSignal(status.wifi_signal);
  1940. }
  1941. }, [status?.wifi_signal]);
  1942. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  1943. // Cache connected state to prevent flicker when status briefly becomes undefined
  1944. const cachedConnected = useRef<boolean | undefined>(undefined);
  1945. useEffect(() => {
  1946. if (status?.connected !== undefined) {
  1947. cachedConnected.current = status.connected;
  1948. }
  1949. }, [status?.connected]);
  1950. const isConnected = status?.connected ?? cachedConnected.current;
  1951. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  1952. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  1953. useEffect(() => {
  1954. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  1955. cachedAmsExtruderMap.current = status.ams_extruder_map;
  1956. }
  1957. }, [status?.ams_extruder_map]);
  1958. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  1959. ? status.ams_extruder_map
  1960. : cachedAmsExtruderMap.current;
  1961. // Cache AMS data to prevent it disappearing on idle/offline printers
  1962. const cachedAmsData = useRef<AMSUnit[]>([]);
  1963. useEffect(() => {
  1964. if (status?.ams && status.ams.length > 0) {
  1965. cachedAmsData.current = status.ams;
  1966. }
  1967. }, [status?.ams]);
  1968. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  1969. // Confirm a drying cycle actually started (#2533). Firmware answers
  1970. // ams_filament_drying with result=success even when it then silently declines,
  1971. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  1972. // reason guard is blind there and the card just sits unchanged. Watch the unit
  1973. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  1974. // means the printer took the command and dropped it.
  1975. useEffect(() => {
  1976. if (!dryStartWatch) return;
  1977. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  1978. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  1979. }, [dryStartWatch, amsData]);
  1980. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  1981. // otherwise rearm the timeout on every frame, so it would never elapse.
  1982. useEffect(() => {
  1983. if (!dryStartWatch) return;
  1984. const timer = setTimeout(() => {
  1985. setDryStartWatch(null);
  1986. showToast(t('printers.drying.toastNotStarted'), 'error');
  1987. }, DRY_START_CONFIRM_MS);
  1988. return () => clearTimeout(timer);
  1989. }, [dryStartWatch, showToast, t]);
  1990. // Cache tray_now to prevent flickering when undefined values come in
  1991. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  1992. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  1993. const cachedTrayNow = useRef<number | undefined>(undefined);
  1994. const currentTrayNow = status?.tray_now;
  1995. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  1996. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  1997. cachedTrayNow.current = currentTrayNow;
  1998. } else if (currentTrayNow === 255) {
  1999. cachedTrayNow.current = undefined;
  2000. }
  2001. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2002. ? currentTrayNow
  2003. : cachedTrayNow.current;
  2004. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2005. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2006. // expectedTray = the slot the firmware now expects filament in
  2007. // previousTray = the slot that ran out
  2008. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2009. // so these are often different — the graphic highlights the expected one.
  2010. const expectedTray = status?.expected_tray ?? null;
  2011. const previousTray = status?.previous_tray ?? null;
  2012. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2013. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2014. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2015. if (globalId === null) return null;
  2016. if (globalId === 254) return t('printers.expectedSlot.external');
  2017. if (globalId >= 128 && globalId <= 135) {
  2018. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2019. }
  2020. const amsId = Math.floor(globalId / 4);
  2021. const slot = globalId % 4;
  2022. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2023. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2024. };
  2025. const runoutGuidance = status?.state === 'PAUSE'
  2026. ? {
  2027. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2028. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2029. }
  2030. : null;
  2031. // Fetch smart plug for this printer
  2032. const { data: smartPlug } = useQuery({
  2033. queryKey: ['smartPlugByPrinter', printer.id],
  2034. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2035. });
  2036. // Fetch script plugs for this printer (for multi-device control)
  2037. const { data: scriptPlugs } = useQuery({
  2038. queryKey: ['scriptPlugsByPrinter', printer.id],
  2039. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2040. });
  2041. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2042. const { data: plugStatus } = useQuery({
  2043. queryKey: ['smartPlugStatus', smartPlug?.id],
  2044. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2045. enabled: !!smartPlug,
  2046. refetchInterval: 10000, // 10 seconds for real-time power display
  2047. });
  2048. // Fetch queue count for this printer
  2049. const { data: queueItems } = useQuery({
  2050. queryKey: ['queue', printer.id, 'pending'],
  2051. queryFn: () => api.getQueue(printer.id, 'pending'),
  2052. });
  2053. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2054. // so the badge only shows on printers that can actually run the queued jobs.
  2055. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2056. const queueCount = useMemo(() => {
  2057. if (!queueItems?.length) return 0;
  2058. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2059. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2060. // Fetch currently printing queue item to show who started it (Issue #206)
  2061. const { data: printingQueueItems } = useQuery({
  2062. queryKey: ['queue', printer.id, 'printing'],
  2063. queryFn: () => api.getQueue(printer.id, 'printing'),
  2064. enabled: status?.state === 'RUNNING',
  2065. });
  2066. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2067. const { data: reprintUser } = useQuery({
  2068. queryKey: ['currentPrintUser', printer.id],
  2069. queryFn: () => api.getCurrentPrintUser(printer.id),
  2070. enabled: status?.state === 'RUNNING',
  2071. });
  2072. // Combine both sources: queue item user takes precedence, then reprint user
  2073. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2074. // Fetch last completed print for this printer
  2075. const { data: lastPrints } = useQuery({
  2076. queryKey: ['archives', printer.id, 'last'],
  2077. queryFn: () => api.getArchives(printer.id, 1, 0),
  2078. enabled: status?.connected && status?.state !== 'RUNNING',
  2079. });
  2080. const lastPrint = lastPrints?.[0];
  2081. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2082. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2083. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2084. const activePrintName = status?.current_print && isPrintingOrPaused
  2085. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2086. : null;
  2087. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2088. useEffect(() => {
  2089. if (activePrintName) {
  2090. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2091. } else if (!needsPlateClear) {
  2092. setRetainedPrintJob(null);
  2093. }
  2094. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2095. const plateStatus = (() => {
  2096. if (!requirePlateClear || !status?.connected) return null;
  2097. if (isPrintingOrPaused) {
  2098. return {
  2099. label: t('printers.plateStatus.inUse'),
  2100. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2101. };
  2102. }
  2103. if (status.awaiting_plate_clear) {
  2104. return {
  2105. label: t('printers.plateStatus.notCleared'),
  2106. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2107. };
  2108. }
  2109. return {
  2110. label: t('printers.plateStatus.cleared'),
  2111. className: 'bg-status-ok/20 text-status-ok',
  2112. };
  2113. })();
  2114. const plateStatusPill = plateStatus ? (
  2115. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${plateStatus.className}`}>
  2116. {plateStatus.label}
  2117. </span>
  2118. ) : null;
  2119. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2120. const shouldHide = hideIfDisconnected && isConnected === false;
  2121. const deleteMutation = useMutation({
  2122. mutationFn: (options: { deleteArchives: boolean }) =>
  2123. api.deletePrinter(printer.id, options.deleteArchives),
  2124. onSuccess: () => {
  2125. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2126. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2127. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2128. },
  2129. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2130. });
  2131. const connectMutation = useMutation({
  2132. mutationFn: () => api.connectPrinter(printer.id),
  2133. onSuccess: () => {
  2134. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2135. },
  2136. });
  2137. const forceRefreshMutation = useMutation({
  2138. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2139. onSuccess: () => {
  2140. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2141. showToast(t('printers.forceRefreshSuccess'), 'success');
  2142. },
  2143. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2144. });
  2145. const unlinkSpoolMutation = useMutation({
  2146. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2147. onSuccess: (result) => {
  2148. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2149. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2150. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2151. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2152. },
  2153. onError: (error: Error) => {
  2154. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2155. },
  2156. });
  2157. // AMS drying mutations
  2158. const startDryingMutation = useMutation({
  2159. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2160. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2161. onSuccess: (_data, { amsId }) => {
  2162. setDryingPopoverAmsId(null);
  2163. setDryStartWatch({ amsId });
  2164. // "Command sent", not "drying started" — at this point the printer has only
  2165. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2166. // the cycle is genuinely live; the watcher below covers the case where it
  2167. // never appears.
  2168. showToast(t('printers.drying.toastCommandSent'), 'success');
  2169. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2170. },
  2171. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2172. });
  2173. const stopDryingMutation = useMutation({
  2174. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2175. onSuccess: () => {
  2176. setDryStartWatch(null);
  2177. showToast(t('printers.drying.toastStopped'), 'success');
  2178. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2179. },
  2180. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2181. });
  2182. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2183. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2184. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2185. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2186. // showing the old backup state until the user reopens it.
  2187. const setAmsBackupMutation = useMutation({
  2188. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2189. onSuccess: (_data, enabled) => {
  2190. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2191. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2192. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2193. },
  2194. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2195. });
  2196. // Smart plug control mutations
  2197. const powerControlMutation = useMutation({
  2198. mutationFn: (action: 'on' | 'off') =>
  2199. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2200. onSuccess: () => {
  2201. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2202. },
  2203. });
  2204. const toggleAutoOffMutation = useMutation({
  2205. mutationFn: (enabled: boolean) =>
  2206. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2207. onSuccess: () => {
  2208. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2209. // Also invalidate the smart-plugs list to keep Settings page in sync
  2210. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2211. },
  2212. });
  2213. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2214. const runScriptMutation = useMutation({
  2215. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2216. onSuccess: () => {
  2217. showToast(t('printers.toast.scriptTriggered'));
  2218. },
  2219. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2220. });
  2221. // Print control mutations
  2222. const stopPrintMutation = useMutation({
  2223. mutationFn: () => api.stopPrint(printer.id),
  2224. onSuccess: () => {
  2225. showToast(t('printers.toast.printStopped'));
  2226. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2227. },
  2228. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2229. });
  2230. const pausePrintMutation = useMutation({
  2231. mutationFn: () => api.pausePrint(printer.id),
  2232. onSuccess: () => {
  2233. showToast(t('printers.toast.printPaused'));
  2234. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2235. },
  2236. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2237. });
  2238. const resumePrintMutation = useMutation({
  2239. mutationFn: () => api.resumePrint(printer.id),
  2240. onSuccess: () => {
  2241. showToast(t('printers.toast.printResumed'));
  2242. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2243. },
  2244. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2245. });
  2246. const clearPlateMutation = useMutation({
  2247. mutationFn: () => api.clearPlate(printer.id),
  2248. onSuccess: () => {
  2249. showToast(t('queue.clearPlateSuccess'));
  2250. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2251. old ? { ...old, awaiting_plate_clear: false } : old
  2252. );
  2253. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2254. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2255. },
  2256. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2257. });
  2258. const nozzleTemperatureMutation = useMutation({
  2259. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2260. api.setNozzleTemperature(printer.id, target, nozzle),
  2261. onSuccess: (result) => {
  2262. setStatusControlMenu(null);
  2263. showToast(result.message);
  2264. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2265. },
  2266. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2267. });
  2268. const bedTemperatureMutation = useMutation({
  2269. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2270. onSuccess: (result) => {
  2271. setStatusControlMenu(null);
  2272. showToast(result.message);
  2273. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2274. },
  2275. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2276. });
  2277. const chamberTemperatureMutation = useMutation({
  2278. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2279. onSuccess: (result) => {
  2280. setStatusControlMenu(null);
  2281. showToast(result.message);
  2282. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2283. },
  2284. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2285. });
  2286. const fanSpeedMutation = useMutation({
  2287. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'chamber'; speed: number }) =>
  2288. api.setFanSpeed(printer.id, fan, speed),
  2289. onMutate: async ({ fan, speed }) => {
  2290. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2291. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2292. const fanField = {
  2293. part: 'cooling_fan_speed',
  2294. aux: 'big_fan1_speed',
  2295. chamber: 'big_fan2_speed',
  2296. }[fan];
  2297. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2298. old ? { ...old, [fanField]: speed } : old
  2299. );
  2300. return { previousStatus };
  2301. },
  2302. onSuccess: (result) => {
  2303. setStatusControlMenu(null);
  2304. showToast(result.message);
  2305. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2306. },
  2307. onError: (error: Error, _variables, context) => {
  2308. if (context?.previousStatus) {
  2309. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2310. }
  2311. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2312. },
  2313. });
  2314. const selectExtruderMutation = useMutation({
  2315. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2316. onMutate: async (extruder) => {
  2317. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2318. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2319. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2320. old ? { ...old, active_extruder: extruder } : old
  2321. );
  2322. return { previousStatus };
  2323. },
  2324. onSuccess: (result) => {
  2325. setStatusControlMenu(null);
  2326. showToast(result.message);
  2327. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2328. },
  2329. onError: (error: Error, _extruder, context) => {
  2330. if (context?.previousStatus) {
  2331. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2332. }
  2333. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2334. },
  2335. });
  2336. // Chamber light mutation with optimistic update
  2337. const chamberLightMutation = useMutation({
  2338. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2339. onMutate: async (on) => {
  2340. // Cancel any outgoing refetches
  2341. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2342. // Snapshot the previous value
  2343. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2344. // Optimistically update
  2345. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2346. ...old,
  2347. chamber_light: on,
  2348. }));
  2349. return { previousStatus };
  2350. },
  2351. onSuccess: (_, on) => {
  2352. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2353. },
  2354. onError: (error: Error, _, context) => {
  2355. // Rollback on error
  2356. if (context?.previousStatus) {
  2357. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2358. }
  2359. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2360. },
  2361. });
  2362. // Print speed mutation with optimistic update
  2363. const printSpeedMutation = useMutation({
  2364. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2365. onMutate: async (mode) => {
  2366. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2367. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2368. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2369. ...old,
  2370. speed_level: mode,
  2371. }));
  2372. return { previousStatus };
  2373. },
  2374. onError: (error: Error, _, context) => {
  2375. if (context?.previousStatus) {
  2376. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2377. }
  2378. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2379. },
  2380. });
  2381. const airductMutation = useMutation({
  2382. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2383. onMutate: async (mode) => {
  2384. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2385. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2386. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2387. ...old,
  2388. airduct_mode: mode === 'cooling' ? 0 : 1,
  2389. }));
  2390. return { previousStatus };
  2391. },
  2392. onError: (error: Error, _, context) => {
  2393. if (context?.previousStatus) {
  2394. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2395. }
  2396. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2397. },
  2398. });
  2399. const bedJogMutation = useMutation({
  2400. mutationFn: ({ distance }: { distance: number }) =>
  2401. api.bedJog(printer.id, distance),
  2402. onError: (error: Error) =>
  2403. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2404. });
  2405. const xyJogMutation = useMutation({
  2406. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2407. api.xyJog(printer.id, x, y),
  2408. onError: (error: Error) =>
  2409. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2410. });
  2411. const extruderJogMutation = useMutation({
  2412. mutationFn: (distance: number) =>
  2413. api.extruderJog(printer.id, distance),
  2414. onError: (error: Error) =>
  2415. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2416. });
  2417. const homeAxesMutation = useMutation({
  2418. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2419. onSuccess: () => {
  2420. showToast(t('printers.bedJog.homingStarted'));
  2421. },
  2422. onError: (error: Error) =>
  2423. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2424. });
  2425. // Plate detection setting mutation
  2426. const plateDetectionMutation = useMutation({
  2427. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2428. onSuccess: () => {
  2429. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2430. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2431. },
  2432. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2433. });
  2434. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2435. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2436. // metrics, and the print picker — so flipping this flag puts the printer
  2437. // out of service across every consumer in one place. Used from the
  2438. // overflow menu and EditPrinterModal.
  2439. const maintenanceMutation = useMutation({
  2440. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2441. onSuccess: (_data, isActive) => {
  2442. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2443. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2444. showToast(
  2445. isActive
  2446. ? t('printers.maintenance.toastExited', { name: printer.name })
  2447. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2448. 'success',
  2449. );
  2450. },
  2451. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2452. });
  2453. // Confirm before entering maintenance on a printing printer (entering mode
  2454. // disconnects MQTT, which stops progress tracking + completion notifications
  2455. // for the in-flight job).
  2456. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2457. const handleEnterMaintenance = () => {
  2458. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2459. setConfirmMaintenanceEnter(true);
  2460. } else {
  2461. maintenanceMutation.mutate(false);
  2462. }
  2463. };
  2464. // Query for printable objects (for skip functionality)
  2465. // Fetch when printing with 2+ objects OR when modal is open
  2466. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2467. const { data: objectsData } = useQuery({
  2468. queryKey: ['printableObjects', printer.id],
  2469. queryFn: () => api.getPrintableObjects(printer.id),
  2470. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2471. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2472. });
  2473. // State for tracking which AMS slot is being refreshed
  2474. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2475. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2476. const seenBusyStateRef = useRef<boolean>(false);
  2477. // Fallback timeout ref
  2478. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2479. // Minimum display time passed
  2480. const minTimePassedRef = useRef<boolean>(false);
  2481. // AMS slot refresh mutation
  2482. const refreshAmsSlotMutation = useMutation({
  2483. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2484. api.refreshAmsSlot(printer.id, amsId, slotId),
  2485. onMutate: ({ amsId, slotId }) => {
  2486. // Clear any existing timeout
  2487. if (refreshTimeoutRef.current) {
  2488. clearTimeout(refreshTimeoutRef.current);
  2489. }
  2490. // Reset state
  2491. seenBusyStateRef.current = false;
  2492. minTimePassedRef.current = false;
  2493. setRefreshingSlot({ amsId, slotId });
  2494. // Minimum display time (2 seconds)
  2495. setTimeout(() => {
  2496. minTimePassedRef.current = true;
  2497. }, 2000);
  2498. // Fallback timeout (30 seconds max)
  2499. refreshTimeoutRef.current = setTimeout(() => {
  2500. setRefreshingSlot(null);
  2501. }, 30000);
  2502. },
  2503. onSuccess: (data) => {
  2504. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2505. },
  2506. onError: (error: Error) => {
  2507. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2508. if (refreshTimeoutRef.current) {
  2509. clearTimeout(refreshTimeoutRef.current);
  2510. }
  2511. setRefreshingSlot(null);
  2512. },
  2513. });
  2514. // AMS load/unload mutations (#891)
  2515. const loadAmsTrayMutation = useMutation({
  2516. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2517. onSuccess: (data) => {
  2518. showToast(data.message || t('printers.toast.loadInitiated'));
  2519. },
  2520. onError: (error: Error) => {
  2521. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2522. },
  2523. });
  2524. const unloadAmsMutation = useMutation({
  2525. mutationFn: () => api.unloadAms(printer.id),
  2526. onSuccess: (data) => {
  2527. showToast(data.message || t('printers.toast.unloadInitiated'));
  2528. },
  2529. onError: (error: Error) => {
  2530. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2531. },
  2532. });
  2533. // Plate references state
  2534. const [plateReferences, setPlateReferences] = useState<{
  2535. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2536. max_references: number;
  2537. } | null>(null);
  2538. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2539. // Fetch plate references
  2540. const fetchPlateReferences = async () => {
  2541. try {
  2542. const data = await api.getPlateReferences(printer.id);
  2543. setPlateReferences(data);
  2544. } catch {
  2545. // Ignore errors - references will show as empty
  2546. }
  2547. };
  2548. // Toggle plate detection enabled/disabled
  2549. const handleTogglePlateDetection = () => {
  2550. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2551. };
  2552. // Open plate detection management modal (for calibration/references)
  2553. const handleOpenPlateManagement = async () => {
  2554. setIsCheckingPlate(true);
  2555. setPlateCheckResult(null);
  2556. // Auto-turn on light if it's off
  2557. const lightWasOff = status?.chamber_light === false;
  2558. setPlateCheckLightWasOff(lightWasOff);
  2559. if (lightWasOff) {
  2560. await api.setChamberLight(printer.id, true);
  2561. // Wait for light to physically turn on and camera to adjust exposure
  2562. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2563. await new Promise(resolve => setTimeout(resolve, 2500));
  2564. }
  2565. try {
  2566. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2567. setPlateCheckResult(result);
  2568. fetchPlateReferences();
  2569. } catch (error) {
  2570. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2571. // Restore light if check failed
  2572. if (lightWasOff) {
  2573. await api.setChamberLight(printer.id, false);
  2574. setPlateCheckLightWasOff(false);
  2575. }
  2576. } finally {
  2577. setIsCheckingPlate(false);
  2578. }
  2579. };
  2580. // Close plate check modal and restore light state
  2581. const closePlateCheckModal = useCallback(async () => {
  2582. setPlateCheckResult(null);
  2583. // Restore light to original state if we turned it on
  2584. if (plateCheckLightWasOff) {
  2585. await api.setChamberLight(printer.id, false);
  2586. setPlateCheckLightWasOff(false);
  2587. }
  2588. }, [plateCheckLightWasOff, printer.id]);
  2589. // Calibrate plate detection handler
  2590. const handleCalibratePlate = async (label?: string) => {
  2591. setIsCalibrating(true);
  2592. try {
  2593. const result = await api.calibratePlateDetection(printer.id, { label });
  2594. if (result.success) {
  2595. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2596. // Refresh references and re-check
  2597. fetchPlateReferences();
  2598. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2599. setPlateCheckResult(checkResult);
  2600. } else {
  2601. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2602. }
  2603. } catch (error) {
  2604. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2605. } finally {
  2606. setIsCalibrating(false);
  2607. }
  2608. };
  2609. // Update reference label
  2610. const handleUpdateRefLabel = async (index: number, label: string) => {
  2611. try {
  2612. await api.updatePlateReferenceLabel(printer.id, index, label);
  2613. setEditingRefLabel(null);
  2614. fetchPlateReferences();
  2615. } catch (error) {
  2616. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2617. }
  2618. };
  2619. // Delete reference
  2620. const handleDeleteRef = async (index: number) => {
  2621. try {
  2622. await api.deletePlateReference(printer.id, index);
  2623. showToast(t('printers.toast.referenceDeleted'), 'success');
  2624. fetchPlateReferences();
  2625. // Re-check to update counts
  2626. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2627. setPlateCheckResult(checkResult);
  2628. } catch (error) {
  2629. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2630. }
  2631. };
  2632. // Save ROI settings
  2633. const handleSaveRoi = async () => {
  2634. if (!editingRoi) return;
  2635. setIsSavingRoi(true);
  2636. try {
  2637. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2638. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2639. setEditingRoi(null);
  2640. // Re-check to see new ROI in action
  2641. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2642. setPlateCheckResult(checkResult);
  2643. } catch (error) {
  2644. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2645. } finally {
  2646. setIsSavingRoi(false);
  2647. }
  2648. };
  2649. // Close plate check modal on Escape key
  2650. useEffect(() => {
  2651. const handleEscape = (e: KeyboardEvent) => {
  2652. if (e.key === 'Escape' && plateCheckResult) {
  2653. closePlateCheckModal();
  2654. }
  2655. };
  2656. window.addEventListener('keydown', handleEscape);
  2657. return () => window.removeEventListener('keydown', handleEscape);
  2658. }, [plateCheckResult, closePlateCheckModal]);
  2659. // Watch ams_status_main to detect when RFID read completes
  2660. // ams_status_main: 0=idle, 2=rfid_identifying
  2661. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2662. useEffect(() => {
  2663. if (!refreshingSlot) return;
  2664. const amsStatus = status?.ams_status_main ?? 0;
  2665. // Track when we see non-idle state (printer is working)
  2666. if (amsStatus !== 0) {
  2667. seenBusyStateRef.current = true;
  2668. // Cancel any deferred clear since we're back to busy
  2669. if (deferredClearRef.current) {
  2670. clearTimeout(deferredClearRef.current);
  2671. deferredClearRef.current = null;
  2672. }
  2673. }
  2674. // When we've seen busy and now idle, clear (with min time check)
  2675. if (seenBusyStateRef.current && amsStatus === 0) {
  2676. if (minTimePassedRef.current) {
  2677. // Min time passed - clear now
  2678. if (refreshTimeoutRef.current) {
  2679. clearTimeout(refreshTimeoutRef.current);
  2680. }
  2681. setRefreshingSlot(null);
  2682. } else {
  2683. // Schedule clear after min time (2 seconds from start)
  2684. if (!deferredClearRef.current) {
  2685. deferredClearRef.current = setTimeout(() => {
  2686. if (refreshTimeoutRef.current) {
  2687. clearTimeout(refreshTimeoutRef.current);
  2688. }
  2689. setRefreshingSlot(null);
  2690. }, 2000);
  2691. }
  2692. }
  2693. }
  2694. return () => {
  2695. if (deferredClearRef.current) {
  2696. clearTimeout(deferredClearRef.current);
  2697. }
  2698. };
  2699. }, [status?.ams_status_main, refreshingSlot]);
  2700. useEffect(() => {
  2701. if (!showMenu) return;
  2702. const handleClickOutside = (event: MouseEvent) => {
  2703. const target = event.target as Node;
  2704. if (!printerActionsMenuRef.current?.contains(target)) {
  2705. setShowMenu(false);
  2706. }
  2707. };
  2708. document.addEventListener('mousedown', handleClickOutside);
  2709. return () => document.removeEventListener('mousedown', handleClickOutside);
  2710. }, [showMenu]);
  2711. if (shouldHide) {
  2712. return null;
  2713. }
  2714. // Size-based styling helpers
  2715. const getImageSize = () => {
  2716. switch (cardSize) {
  2717. case 1: return 'w-10 h-10';
  2718. case 2: return 'w-14 h-14';
  2719. case 3: return 'w-16 h-16';
  2720. case 4: return 'w-20 h-20';
  2721. default: return 'w-14 h-14';
  2722. }
  2723. };
  2724. const getTitleSize = () => {
  2725. switch (cardSize) {
  2726. case 1: return 'text-base truncate';
  2727. case 2: return 'text-lg';
  2728. case 3: return 'text-xl';
  2729. case 4: return 'text-2xl';
  2730. default: return 'text-lg';
  2731. }
  2732. };
  2733. const getSpacing = () => {
  2734. switch (cardSize) {
  2735. case 1: return 'mb-2';
  2736. case 2: return 'mb-4';
  2737. case 3: return 'mb-5';
  2738. case 4: return 'mb-6';
  2739. default: return 'mb-4';
  2740. }
  2741. };
  2742. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2743. const handleCardDragEnter = (e: React.DragEvent) => {
  2744. e.preventDefault();
  2745. dragCounterRef.current++;
  2746. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2747. };
  2748. const handleCardDragOver = (e: React.DragEvent) => {
  2749. e.preventDefault();
  2750. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2751. };
  2752. const handleCardDragLeave = (e: React.DragEvent) => {
  2753. e.preventDefault();
  2754. dragCounterRef.current--;
  2755. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2756. };
  2757. const handleCardDrop = async (e: React.DragEvent) => {
  2758. e.preventDefault();
  2759. dragCounterRef.current = 0;
  2760. setIsDraggingFile(false);
  2761. if (!canDrop) return;
  2762. const droppedFiles = Array.from(e.dataTransfer.files);
  2763. const file = droppedFiles[0];
  2764. if (!file) return;
  2765. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2766. const lower = file.name.toLowerCase();
  2767. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2768. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2769. return;
  2770. }
  2771. setIsDropUploading(true);
  2772. try {
  2773. const result = await api.uploadLibraryFile(file, null);
  2774. // Check printer compatibility if sliced_for_model is available in metadata
  2775. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2776. const printerModel = mapModelCode(printer.model);
  2777. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2778. await api.deleteLibraryFile(result.id).catch(() => {});
  2779. showToast(
  2780. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2781. 'error'
  2782. );
  2783. return;
  2784. }
  2785. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2786. } catch {
  2787. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2788. } finally {
  2789. setIsDropUploading(false);
  2790. }
  2791. };
  2792. const handleCardClick = (e: React.MouseEvent) => {
  2793. if (viewMode !== 'compact' || selectionMode) return;
  2794. const target = e.target as HTMLElement;
  2795. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2796. onOpenCompactCard?.(printer.id);
  2797. };
  2798. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2799. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2800. const renderAmsSlotActions = ({
  2801. amsId,
  2802. slotId,
  2803. loadTrayId,
  2804. isRefreshing,
  2805. includeRfid = true,
  2806. }: {
  2807. amsId: number;
  2808. slotId: number;
  2809. loadTrayId: number;
  2810. isRefreshing?: boolean;
  2811. includeRfid?: boolean;
  2812. }) => {
  2813. const printerBusy = status?.state === 'RUNNING';
  2814. return (
  2815. <>
  2816. {includeRfid && (
  2817. <button
  2818. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2819. hasPermission('printers:ams_rfid')
  2820. ? 'text-white hover:bg-bambu-dark-tertiary'
  2821. : 'text-bambu-gray/50 cursor-not-allowed'
  2822. }`}
  2823. onClick={(e) => {
  2824. e.stopPropagation();
  2825. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2826. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2827. }}
  2828. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2829. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2830. >
  2831. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  2832. {t('printers.rfid.reread')}
  2833. </button>
  2834. )}
  2835. <button
  2836. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2837. hasPermission('printers:control')
  2838. ? 'text-white hover:bg-bambu-dark-tertiary'
  2839. : 'text-bambu-gray/50 cursor-not-allowed'
  2840. }`}
  2841. onClick={(e) => {
  2842. e.stopPropagation();
  2843. if (printerBusy || !hasPermission('printers:control')) return;
  2844. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  2845. }}
  2846. disabled={printerBusy || !hasPermission('printers:control')}
  2847. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2848. >
  2849. <LogIn className="w-3 h-3" />
  2850. {t('printers.ams.load')}
  2851. </button>
  2852. <button
  2853. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2854. hasPermission('printers:control')
  2855. ? 'text-white hover:bg-bambu-dark-tertiary'
  2856. : 'text-bambu-gray/50 cursor-not-allowed'
  2857. }`}
  2858. onClick={(e) => {
  2859. e.stopPropagation();
  2860. if (printerBusy || !hasPermission('printers:control')) return;
  2861. unloadAmsMutation.mutate();
  2862. }}
  2863. disabled={printerBusy || !hasPermission('printers:control')}
  2864. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  2865. >
  2866. <LogOut className="w-3 h-3" />
  2867. {t('printers.ams.unload')}
  2868. </button>
  2869. </>
  2870. );
  2871. };
  2872. const printerActionsMenu = (
  2873. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  2874. <Button
  2875. variant="secondary"
  2876. size="sm"
  2877. onClick={() => setShowMenu(!showMenu)}
  2878. title={t('common.more', 'More')}
  2879. className={footerIconButtonClass}
  2880. >
  2881. <MoreVertical className="w-4 h-4" />
  2882. </Button>
  2883. {showMenu && (
  2884. <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">
  2885. <button
  2886. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2887. hasPermission('printers:update')
  2888. ? 'hover:bg-bambu-dark-tertiary'
  2889. : 'opacity-50 cursor-not-allowed'
  2890. }`}
  2891. onClick={() => {
  2892. if (!hasPermission('printers:update')) return;
  2893. setShowEditModal(true);
  2894. setShowMenu(false);
  2895. }}
  2896. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2897. >
  2898. <Pencil className="w-4 h-4" />
  2899. {t('common.edit')}
  2900. </button>
  2901. <button
  2902. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2903. onClick={() => {
  2904. setShowPrinterInfo(true);
  2905. setShowMenu(false);
  2906. }}
  2907. >
  2908. <Info className="w-4 h-4" />
  2909. {t('printers.printerInformation')}
  2910. </button>
  2911. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  2912. <button
  2913. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2914. hasPermission('printers:update')
  2915. ? 'hover:bg-bambu-dark-tertiary'
  2916. : 'opacity-50 cursor-not-allowed'
  2917. }`}
  2918. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  2919. onClick={() => {
  2920. if (!hasPermission('printers:update')) return;
  2921. setShowMenu(false);
  2922. if (printer.is_active !== false) {
  2923. handleEnterMaintenance();
  2924. } else {
  2925. maintenanceMutation.mutate(true);
  2926. }
  2927. }}
  2928. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  2929. >
  2930. <Wrench className="w-4 h-4" />
  2931. {printer.is_active !== false
  2932. ? t('printers.maintenance.menuEnter')
  2933. : t('printers.maintenance.menuExit')}
  2934. </button>
  2935. <button
  2936. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2937. onClick={() => {
  2938. connectMutation.mutate();
  2939. setShowMenu(false);
  2940. }}
  2941. >
  2942. <RefreshCw className="w-4 h-4" />
  2943. {t('printers.reconnect')}
  2944. </button>
  2945. <button
  2946. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  2947. disabled={forceRefreshMutation.isPending}
  2948. onClick={() => {
  2949. forceRefreshMutation.mutate();
  2950. setShowMenu(false);
  2951. }}
  2952. >
  2953. <RotateCw className={`w-4 h-4 ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  2954. {t('printers.forceRefresh')}
  2955. </button>
  2956. <button
  2957. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2958. onClick={() => {
  2959. setShowMQTTDebug(true);
  2960. setShowMenu(false);
  2961. }}
  2962. >
  2963. <Terminal className="w-4 h-4" />
  2964. {t('printers.mqttDebug')}
  2965. </button>
  2966. <button
  2967. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  2968. onClick={() => {
  2969. setShowDiagnostic(true);
  2970. setShowMenu(false);
  2971. }}
  2972. >
  2973. <Stethoscope className="w-4 h-4" />
  2974. {t('diagnostic.runButton')}
  2975. </button>
  2976. <button
  2977. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  2978. hasPermission('printers:delete')
  2979. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  2980. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  2981. }`}
  2982. onClick={() => {
  2983. if (!hasPermission('printers:delete')) return;
  2984. setShowDeleteConfirm(true);
  2985. setShowMenu(false);
  2986. }}
  2987. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  2988. >
  2989. <Trash2 className="w-4 h-4" />
  2990. {t('common.delete')}
  2991. </button>
  2992. </div>
  2993. )}
  2994. </div>
  2995. );
  2996. return (
  2997. <Card
  2998. id={`printer-card-${printer.id}`}
  2999. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3000. onClick={handleCardClick}
  3001. onDragEnter={handleCardDragEnter}
  3002. onDragOver={handleCardDragOver}
  3003. onDragLeave={handleCardDragLeave}
  3004. onDrop={handleCardDrop}
  3005. >
  3006. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3007. {selectionMode && (
  3008. <div
  3009. className="absolute inset-0 z-20 flex items-start p-2"
  3010. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3011. >
  3012. {isSelected ? (
  3013. <CheckSquare className="w-5 h-5 text-bambu-green" />
  3014. ) : (
  3015. <Square className="w-5 h-5 text-bambu-gray" />
  3016. )}
  3017. </div>
  3018. )}
  3019. {/* Drop zone overlay */}
  3020. {(isDraggingFile || isDropUploading) && (
  3021. <div
  3022. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3023. isDropUploading
  3024. ? 'bg-bambu-green/10 border-bambu-green/50'
  3025. : canDrop
  3026. ? 'bg-bambu-green/10 border-bambu-green'
  3027. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3028. }`}
  3029. >
  3030. <div className="text-center">
  3031. {isDropUploading ? (
  3032. <>
  3033. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3034. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3035. </>
  3036. ) : canDrop ? (
  3037. <>
  3038. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3039. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  3040. </>
  3041. ) : (
  3042. <>
  3043. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3044. <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  3045. </>
  3046. )}
  3047. </div>
  3048. </div>
  3049. )}
  3050. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3051. {/* Header */}
  3052. <div className={getSpacing()}>
  3053. {/* Top row: Image, Name, Menu */}
  3054. <div className="flex items-start justify-between gap-2">
  3055. <div className="flex items-center gap-3 min-w-0 flex-1">
  3056. {/* Printer Model Image */}
  3057. <img
  3058. src={getPrinterImage(printer.model)}
  3059. alt={printer.model || t('common.printer')}
  3060. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3061. />
  3062. <div className="min-w-0 flex-1">
  3063. <div className="flex items-center justify-between gap-2">
  3064. <div className="flex min-w-0 items-center gap-2">
  3065. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3066. {/* Connection indicator dot for compact mode */}
  3067. {viewMode === 'compact' && (() => {
  3068. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3069. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3070. const hasWarning = hmsErrors.length > 0;
  3071. const pipColor = !status?.connected
  3072. ? 'bg-status-error'
  3073. : hasSevere
  3074. ? 'bg-status-error'
  3075. : hasWarning
  3076. ? 'bg-status-warning'
  3077. : 'bg-status-ok';
  3078. const pipTitle = !status?.connected
  3079. ? t('printers.connection.offline')
  3080. : hasWarning
  3081. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3082. : t('printers.connection.connected');
  3083. return (
  3084. <div
  3085. className={`w-2 h-2 rounded-full flex-shrink-0 ${pipColor}`}
  3086. title={pipTitle}
  3087. />
  3088. );
  3089. })()}
  3090. </div>
  3091. {viewMode === 'compact' && showClearPlateButton && (
  3092. <button
  3093. type="button"
  3094. onClick={() => clearPlateMutation.mutate()}
  3095. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3096. aria-label={t('printers.plateStatus.markCleared')}
  3097. 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"
  3098. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3099. >
  3100. {clearPlateMutation.isPending ? (
  3101. <Loader2 className="w-3 h-3 animate-spin" />
  3102. ) : (
  3103. <PlateClearedIcon className="w-3 h-3" />
  3104. )}
  3105. </button>
  3106. )}
  3107. </div>
  3108. <p className="text-sm text-bambu-gray">
  3109. {printer.model || 'Unknown Model'}
  3110. {/* Nozzle Info - only in expanded */}
  3111. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3112. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3113. • {status.nozzles[0].nozzle_diameter}mm
  3114. </span>
  3115. )}
  3116. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3117. <span className="ml-2 text-bambu-gray">
  3118. <Clock className="w-3 h-3 inline-block mr-1" />
  3119. {Math.round(maintenanceInfo.total_print_hours)}h
  3120. </span>
  3121. )}
  3122. </p>
  3123. </div>
  3124. </div>
  3125. </div>
  3126. {/* Badges row - only in expanded mode */}
  3127. {viewMode === 'expanded' && (
  3128. <div className="mt-2">
  3129. <div className="flex flex-wrap items-center gap-2">
  3130. {/* Connection status badge (or Maintenance pill when out of service).
  3131. Defensive: only swap when is_active is EXPLICITLY false. An
  3132. undefined / missing field defaults to "active" so the regular
  3133. pill renders — matches the backend default and prevents test
  3134. fixtures (or stale clients) from accidentally tripping the
  3135. maintenance UI. */}
  3136. {printer.is_active === false ? (
  3137. <span
  3138. 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"
  3139. title={t('printers.maintenance.subtitle')}
  3140. >
  3141. <Wrench className="w-3 h-3" />
  3142. {t('printers.maintenance.pillLabel')}
  3143. </span>
  3144. ) : (
  3145. <span
  3146. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3147. status?.connected
  3148. ? 'bg-status-ok/20 text-status-ok'
  3149. : 'bg-status-error/20 text-status-error'
  3150. }`}
  3151. >
  3152. {status?.connected ? (
  3153. <Link className="w-3 h-3" />
  3154. ) : (
  3155. <Unlink className="w-3 h-3" />
  3156. )}
  3157. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3158. </span>
  3159. )}
  3160. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3161. {printer.is_active !== false && !status?.connected && (
  3162. <button
  3163. onClick={() => setShowDiagnostic(true)}
  3164. 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"
  3165. title={t('diagnostic.runButton')}
  3166. >
  3167. <Stethoscope className="w-3 h-3" />
  3168. {t('diagnostic.runButton')}
  3169. </button>
  3170. )}
  3171. {/* Network connection indicator */}
  3172. {status?.connected && status?.wired_network && (
  3173. <span
  3174. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3175. title={t('printers.connection.ethernet', 'Ethernet')}
  3176. >
  3177. <Cable className="w-3 h-3" />
  3178. {t('printers.connection.ethernet', 'Ethernet')}
  3179. </span>
  3180. )}
  3181. {/* WiFi signal indicator */}
  3182. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3183. <span
  3184. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3185. wifiSignal >= -50
  3186. ? 'bg-status-ok/20 text-status-ok'
  3187. : wifiSignal >= -60
  3188. ? 'bg-status-ok/20 text-status-ok'
  3189. : wifiSignal >= -70
  3190. ? 'bg-status-warning/20 text-status-warning'
  3191. : wifiSignal >= -80
  3192. ? 'bg-orange-500/20 text-orange-600'
  3193. : 'bg-status-error/20 text-status-error'
  3194. }`}
  3195. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3196. >
  3197. <Signal className="w-3 h-3" />
  3198. {wifiSignal}dBm
  3199. </span>
  3200. )}
  3201. {/* HMS Status Indicator */}
  3202. {status?.connected && (() => {
  3203. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3204. return (
  3205. <button
  3206. onClick={() => setShowHMSModal(true)}
  3207. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3208. knownErrors.length > 0
  3209. ? knownErrors.some(e => e.severity <= 2)
  3210. ? 'bg-status-error/20 text-status-error'
  3211. : 'bg-status-warning/20 text-status-warning'
  3212. : 'bg-status-ok/20 text-status-ok'
  3213. }`}
  3214. title={t('printers.clickToViewHmsErrors')}
  3215. >
  3216. <AlertTriangle className="w-3 h-3" />
  3217. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3218. </button>
  3219. );
  3220. })()}
  3221. {/* AI failure detection badge (#1546) — always shown while detection
  3222. is enabled for this printer, like the other health badges. Gray
  3223. "Idle" outside a monitored print, class-colored during one. */}
  3224. {aiDetectionEnabled && (() => {
  3225. const cls = aiDetection
  3226. ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
  3227. : 'idle';
  3228. const colorClass =
  3229. cls === 'failure'
  3230. ? 'bg-status-error/20 text-status-error'
  3231. : cls === 'warning'
  3232. ? 'bg-status-warning/20 text-status-warning'
  3233. : cls === 'safe'
  3234. ? 'bg-status-ok/20 text-status-ok'
  3235. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3236. return (
  3237. <button
  3238. onClick={() => setShowAiModal(true)}
  3239. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3240. title={
  3241. aiDetection
  3242. ? t('printers.aiDetection.tooltip', {
  3243. status: t(`printers.aiDetection.${cls}`),
  3244. score: aiDetection.score.toFixed(3),
  3245. })
  3246. : t('printers.aiDetection.tooltipIdle')
  3247. }
  3248. >
  3249. <ScanEye className="w-3 h-3" />
  3250. {t(`printers.aiDetection.${cls}`)}
  3251. </button>
  3252. );
  3253. })()}
  3254. {/* Maintenance Status Indicator */}
  3255. {maintenanceInfo && (
  3256. <button
  3257. onClick={() => navigate('/maintenance')}
  3258. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3259. maintenanceInfo.due_count > 0
  3260. ? 'bg-status-error/20 text-status-error'
  3261. : maintenanceInfo.warning_count > 0
  3262. ? 'bg-status-warning/20 text-status-warning'
  3263. : 'bg-status-ok/20 text-status-ok'
  3264. }`}
  3265. title={
  3266. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3267. ? `${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`
  3268. : t('printers.maintenanceUpToDate')
  3269. }
  3270. >
  3271. <Wrench className="w-3 h-3" />
  3272. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3273. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3274. : 'OK'}
  3275. </button>
  3276. )}
  3277. {/* Queue Count Badge */}
  3278. {queueCount > 0 && (
  3279. <button
  3280. onClick={() => navigate('/queue')}
  3281. 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"
  3282. title={t('printers.queue.inQueue', { count: queueCount })}
  3283. >
  3284. <Layers className="w-3 h-3" />
  3285. {queueCount}
  3286. </button>
  3287. )}
  3288. {/* Firmware Version Badge */}
  3289. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3290. <button
  3291. onClick={() => setShowFirmwareModal(true)}
  3292. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3293. firmwareInfo.update_available
  3294. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3295. : 'bg-status-ok/20 text-status-ok'
  3296. }`}
  3297. title={
  3298. firmwareInfo.update_available
  3299. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3300. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3301. }
  3302. >
  3303. {firmwareInfo.update_available ? <Download className="w-3 h-3" /> : <CheckCircle className="w-3 h-3" />}
  3304. {firmwareInfo.current_version}
  3305. </button>
  3306. ) : status?.firmware_version ? (
  3307. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3308. {status.firmware_version}
  3309. </span>
  3310. ) : null}
  3311. {/* Enclosure Door Badge — models with an actual door sensor.
  3312. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3313. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3314. <span
  3315. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3316. status.door_open
  3317. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3318. : 'bg-status-ok/20 text-status-ok'
  3319. }`}
  3320. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3321. >
  3322. {status.door_open ? <DoorOpen className="w-3 h-3" /> : <DoorClosed className="w-3 h-3" />}
  3323. </span>
  3324. )}
  3325. </div>
  3326. </div>
  3327. )}
  3328. </div>
  3329. {/* Delete Confirmation */}
  3330. {showDeleteConfirm && (
  3331. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3332. <Card className="w-full max-w-md mx-4">
  3333. <CardContent>
  3334. <div className="flex items-start gap-3 mb-4">
  3335. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3336. <AlertTriangle className="w-5 h-5 text-red-600 dark:text-red-400" />
  3337. </div>
  3338. <div>
  3339. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3340. <p className="text-sm text-bambu-gray mt-1">
  3341. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3342. </p>
  3343. </div>
  3344. </div>
  3345. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3346. <label className="flex items-start gap-3 cursor-pointer">
  3347. <input
  3348. type="checkbox"
  3349. checked={deleteArchives}
  3350. onChange={(e) => setDeleteArchives(e.target.checked)}
  3351. className="mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3352. />
  3353. <div>
  3354. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3355. <p className="text-xs text-bambu-gray mt-0.5">
  3356. {deleteArchives
  3357. ? t('printers.confirm.deleteArchivesNote')
  3358. : t('printers.confirm.keepArchivesNote')}
  3359. </p>
  3360. </div>
  3361. </label>
  3362. </div>
  3363. <div className="flex justify-end gap-2">
  3364. <Button
  3365. variant="secondary"
  3366. onClick={() => {
  3367. setShowDeleteConfirm(false);
  3368. setDeleteArchives(true);
  3369. }}
  3370. >
  3371. {t('common.cancel')}
  3372. </Button>
  3373. <Button
  3374. variant="danger"
  3375. onClick={() => {
  3376. deleteMutation.mutate({ deleteArchives });
  3377. setShowDeleteConfirm(false);
  3378. setDeleteArchives(true);
  3379. }}
  3380. >
  3381. Delete
  3382. </Button>
  3383. </div>
  3384. </CardContent>
  3385. </Card>
  3386. </div>
  3387. )}
  3388. {/* Status — see the equivalent defensive `=== false` check on the
  3389. header pill above for why this is not `!printer.is_active`. */}
  3390. {printer.is_active === false ? (
  3391. // Maintenance mode (#1476) — replaces the cover/progress container
  3392. // so the card keeps the same height. Renders for both compact and
  3393. // expanded view modes so the printer stays visible but plainly
  3394. // out-of-service.
  3395. <>
  3396. {viewMode === 'compact' ? (
  3397. <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">
  3398. <Wrench className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  3399. <span className="text-[11px] text-amber-700 dark:text-amber-400 font-medium truncate">
  3400. {t('printers.maintenance.pillLabel')}
  3401. </span>
  3402. </div>
  3403. ) : (
  3404. <>
  3405. <div className="flex items-center gap-2 mb-2">
  3406. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3407. {t('printers.status.title', 'Status')}
  3408. </span>
  3409. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3410. </div>
  3411. <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">
  3412. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3413. <div className="flex-1 min-w-0">
  3414. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3415. {t('printers.maintenance.title')}
  3416. </p>
  3417. <p className="text-xs text-bambu-gray mt-0.5">
  3418. {t('printers.maintenance.subtitle')}
  3419. </p>
  3420. </div>
  3421. <Button
  3422. variant="secondary"
  3423. size="sm"
  3424. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3425. onClick={() => maintenanceMutation.mutate(true)}
  3426. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3427. >
  3428. {t('printers.maintenance.exitButton')}
  3429. </Button>
  3430. </div>
  3431. </>
  3432. )}
  3433. </>
  3434. ) : status?.connected && (
  3435. <>
  3436. {/* Compact: Simple status bar */}
  3437. {viewMode === 'compact' ? (
  3438. (() => {
  3439. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3440. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3441. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3442. ? Math.max(0, Math.min(100, status.progress || 0))
  3443. : showClearPlateButton
  3444. ? 100
  3445. : hasProblem
  3446. ? 100
  3447. : 0;
  3448. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3449. const compactProgressClass = hasProblem
  3450. ? 'bg-status-error'
  3451. : status.state === 'PAUSE'
  3452. ? 'bg-status-warning'
  3453. : 'bg-bambu-green';
  3454. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  3455. const hasCompactLayers =
  3456. isActiveCompactPrint &&
  3457. status.layer_num != null &&
  3458. status.total_layers != null &&
  3459. status.total_layers > 0;
  3460. return (
  3461. <>
  3462. <div className="relative mt-2 flex items-center gap-2">
  3463. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3464. <div
  3465. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3466. style={{ width: `${compactProgress}%` }}
  3467. />
  3468. </div>
  3469. <span className={`w-9 shrink-0 text-right text-[11px] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3470. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3471. </span>
  3472. </div>
  3473. {/* #2674: size S showed only a name, a pip and a progress bar — not
  3474. enough to answer "which printer finishes first", which is what a
  3475. wall-mounted fleet view is for. One line of the metrics the
  3476. expanded card already renders, using the same formatters and the
  3477. same ETA styling so S and M read alike. The row keeps its height
  3478. when idle so cards don't shift as prints start and stop. */}
  3479. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[11px] leading-none text-bambu-gray">
  3480. {hasCompactEta && (
  3481. <>
  3482. <span className="flex shrink-0 items-center gap-1">
  3483. <Clock className="w-3 h-3" />
  3484. {formatDuration(status.remaining_time! * 60)}
  3485. </span>
  3486. <span
  3487. className="shrink-0 font-medium text-bambu-green"
  3488. title={t('printers.estimatedCompletion')}
  3489. >
  3490. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  3491. </span>
  3492. </>
  3493. )}
  3494. {hasCompactLayers && (
  3495. <span className="flex min-w-0 items-center gap-1 truncate">
  3496. <Layers className="w-3 h-3 shrink-0" />
  3497. {status.layer_num}/{status.total_layers}
  3498. </span>
  3499. )}
  3500. </div>
  3501. </>
  3502. );
  3503. })()
  3504. ) : (
  3505. /* Expanded: Full status section */
  3506. <>
  3507. <div className="flex items-center gap-2 mb-2">
  3508. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3509. {t('printers.status.title', 'Status')}
  3510. </span>
  3511. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3512. </div>
  3513. {/* Current Print or Idle Placeholder */}
  3514. {(() => {
  3515. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3516. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3517. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3518. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3519. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3520. return (
  3521. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3522. <button
  3523. onClick={() => setShowSkipObjectsModal(true)}
  3524. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3525. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3526. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3527. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3528. : 'text-bambu-gray/30 cursor-not-allowed'
  3529. }`}
  3530. title={
  3531. !hasPermission('printers:control')
  3532. ? t('printers.permission.noControl')
  3533. : !isActivePrint
  3534. ? t('printers.skipObjects.onlyWhilePrinting')
  3535. : (status.printable_objects_count ?? 0) >= 2
  3536. ? t('printers.skipObjects.tooltip')
  3537. : t('printers.skipObjects.requiresMultiple')
  3538. }
  3539. >
  3540. <SkipObjectsIcon className="w-4 h-4" />
  3541. {objectsData && objectsData.skipped_count > 0 && (
  3542. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full">
  3543. {objectsData.skipped_count}
  3544. </span>
  3545. )}
  3546. </button>
  3547. <div className="flex items-stretch gap-2">
  3548. <CoverImage
  3549. url={coverUrl}
  3550. printName={printName || undefined}
  3551. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3552. />
  3553. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3554. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3555. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3556. {plateStatusPill}
  3557. </div>
  3558. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3559. {printName || t('printers.noActiveJob', 'No active job')}
  3560. </p>
  3561. <div className="flex h-3 items-center gap-2 text-sm">
  3562. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3563. <div
  3564. 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`}
  3565. style={{ width: `${progress}%` }}
  3566. />
  3567. </div>
  3568. <span className={`w-9 shrink-0 pr-1 text-right text-[11px] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  3569. </div>
  3570. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3571. {isActivePrint ? (
  3572. <>
  3573. {status.remaining_time != null && status.remaining_time > 0 && (
  3574. <>
  3575. <span className="flex items-center gap-1">
  3576. <Clock className="w-3 h-3" />
  3577. {formatDuration(status.remaining_time * 60)}
  3578. </span>
  3579. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3580. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3581. </span>
  3582. </>
  3583. )}
  3584. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3585. <span className="flex items-center gap-1">
  3586. <Layers className="w-3 h-3" />
  3587. {status.layer_num}/{status.total_layers}
  3588. </span>
  3589. )}
  3590. {currentPrintUser && (
  3591. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3592. <User className="w-3 h-3" />
  3593. {currentPrintUser}
  3594. </span>
  3595. )}
  3596. </>
  3597. ) : lastPrint ? (
  3598. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3599. Last: {lastPrint.print_name || lastPrint.filename}
  3600. {lastPrint.completed_at && (
  3601. <span className="ml-1 text-bambu-gray/60">
  3602. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3603. </span>
  3604. )}
  3605. </p>
  3606. ) : (
  3607. <span>{t('printers.readyToPrint')}</span>
  3608. )}
  3609. </div>
  3610. </div>
  3611. </div>
  3612. <PrinterQueueWidget
  3613. printerId={printer.id}
  3614. printerModel={printer.model}
  3615. loadedFilamentTypes={loadedFilamentTypes}
  3616. loadedFilaments={loadedFilaments}
  3617. loadedVariants={loadedVariants}
  3618. variant="panelExtension"
  3619. />
  3620. </div>
  3621. );
  3622. })()}
  3623. </>
  3624. )}
  3625. {/* Temperatures */}
  3626. {status.temperatures && viewMode === 'expanded' && (() => {
  3627. // Use actual heater states from MQTT stream
  3628. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3629. const bedHeating = status.temperatures.bed_heating || false;
  3630. const chamberHeating = status.temperatures.chamber_heating || false;
  3631. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3632. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3633. const kinds: HeaterSensorKind[] = ['nozzle'];
  3634. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3635. kinds.push('bed');
  3636. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3637. return kinds;
  3638. })();
  3639. // active_extruder: 0=right, 1=left
  3640. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3641. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3642. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3643. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3644. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3645. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3646. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3647. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3648. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3649. 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 ${
  3650. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3651. }`;
  3652. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3653. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3654. // the widget there is at best dead UI and at worst suggests a
  3655. // control that does nothing. Mirrors the enclosure-door badge
  3656. // gate above.
  3657. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3658. const fanItems = [
  3659. {
  3660. key: 'part',
  3661. label: t('printers.fans.partCooling'),
  3662. value: status.cooling_fan_speed ?? 0,
  3663. Icon: Fan,
  3664. activeClass: 'text-cyan-600 dark:text-cyan-400',
  3665. },
  3666. {
  3667. key: 'aux',
  3668. label: t('printers.fans.auxiliary'),
  3669. value: status.big_fan1_speed ?? 0,
  3670. Icon: Wind,
  3671. activeClass: 'text-blue-600 dark:text-blue-400',
  3672. },
  3673. ...(hasChamberFan
  3674. ? [
  3675. {
  3676. key: 'chamber',
  3677. label: t('printers.fans.chamber'),
  3678. value: status.big_fan2_speed ?? 0,
  3679. Icon: AirVent,
  3680. activeClass: 'text-green-600 dark:text-green-400',
  3681. },
  3682. ]
  3683. : []),
  3684. ];
  3685. return (
  3686. <>
  3687. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3688. {/* Nozzle temp - combined for dual nozzle */}
  3689. <div
  3690. className={statusControlClass}
  3691. title={statusControlTitle}
  3692. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3693. >
  3694. <button
  3695. type="button"
  3696. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3697. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3698. onClick={(e) => {
  3699. e.stopPropagation();
  3700. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3701. }}
  3702. >
  3703. <LineChartIcon className="w-2.5 h-2.5" />
  3704. </button>
  3705. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3706. {status.temperatures.nozzle_2 !== undefined ? (
  3707. <>
  3708. <p className="text-[9px] text-bambu-gray">L / R</p>
  3709. <p className="text-[11px] text-white">
  3710. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3711. </p>
  3712. </>
  3713. ) : singleNozzleSlot ? (
  3714. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3715. <div className="cursor-default">
  3716. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3717. <p className="text-[11px] text-white">
  3718. {Math.round(status.temperatures.nozzle || 0)}°C
  3719. </p>
  3720. </div>
  3721. </NozzleSlotHoverCard>
  3722. ) : (
  3723. <>
  3724. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3725. <p className="text-[11px] text-white">
  3726. {Math.round(status.temperatures.nozzle || 0)}°C
  3727. </p>
  3728. </>
  3729. )}
  3730. {statusControlMenu === 'nozzle-temp' && (
  3731. isDualNozzle ? (
  3732. <IndicatorControlPopover
  3733. title="Set Nozzle Temperatures"
  3734. widthClass="w-[300px]"
  3735. popoverWidth={300}
  3736. popoverHeight={260}
  3737. isPending={nozzleTemperatureMutation.isPending}
  3738. onClose={() => setStatusControlMenu(null)}
  3739. >
  3740. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3741. <NozzleTemperatureControlBox
  3742. label="Left Temp"
  3743. current={status.temperatures.nozzle}
  3744. target={status.temperatures.nozzle_target}
  3745. isActive={activeNozzle === 'L'}
  3746. isPending={nozzleTemperatureMutation.isPending}
  3747. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3748. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3749. />
  3750. <NozzleTemperatureControlBox
  3751. label="Right Temp"
  3752. current={status.temperatures.nozzle_2}
  3753. target={status.temperatures.nozzle_2_target}
  3754. isActive={activeNozzle === 'R'}
  3755. isPending={nozzleTemperatureMutation.isPending}
  3756. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3757. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3758. />
  3759. </div>
  3760. </IndicatorControlPopover>
  3761. ) : (
  3762. <IndicatorControlPopover
  3763. title="Set Nozzle Temperature"
  3764. unit="°C"
  3765. customMin={0}
  3766. customMax={320}
  3767. isPending={nozzleTemperatureMutation.isPending}
  3768. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3769. onClose={() => setStatusControlMenu(null)}
  3770. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3771. />
  3772. )
  3773. )}
  3774. </div>
  3775. <div
  3776. className={statusControlClass}
  3777. title={statusControlTitle}
  3778. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3779. >
  3780. <button
  3781. type="button"
  3782. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3783. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3784. onClick={(e) => {
  3785. e.stopPropagation();
  3786. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3787. }}
  3788. >
  3789. <LineChartIcon className="w-2.5 h-2.5" />
  3790. </button>
  3791. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3792. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3793. <p className="text-[11px] text-white">
  3794. {Math.round(status.temperatures.bed || 0)}°C
  3795. </p>
  3796. {statusControlMenu === 'bed-temp' && (
  3797. <IndicatorControlPopover
  3798. title="Set Bed Temperature"
  3799. unit="°C"
  3800. customMin={0}
  3801. customMax={140}
  3802. isPending={bedTemperatureMutation.isPending}
  3803. options={buildPresetOptions(bedTempPresets, 'C')}
  3804. onClose={() => setStatusControlMenu(null)}
  3805. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  3806. />
  3807. )}
  3808. </div>
  3809. {status.temperatures.chamber !== undefined && (() => {
  3810. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  3811. // but can't act on M141, so we keep the card read-only there.
  3812. const hasChamberHeater = status.supports_chamber_heater === true;
  3813. return (
  3814. <div
  3815. className={hasChamberHeater
  3816. ? statusControlClass
  3817. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  3818. title={hasChamberHeater ? statusControlTitle : undefined}
  3819. onClick={hasChamberHeater
  3820. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  3821. : undefined}
  3822. >
  3823. <button
  3824. type="button"
  3825. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3826. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3827. onClick={(e) => {
  3828. e.stopPropagation();
  3829. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  3830. }}
  3831. >
  3832. <LineChartIcon className="w-2.5 h-2.5" />
  3833. </button>
  3834. <HeaterThermometer className="w-3.5 h-3.5 mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  3835. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  3836. <p className="text-[11px] text-white">
  3837. {Math.round(status.temperatures.chamber || 0)}°C
  3838. </p>
  3839. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  3840. <IndicatorControlPopover
  3841. title="Set Chamber Temperature"
  3842. unit="°C"
  3843. customMin={0}
  3844. customMax={60}
  3845. isPending={chamberTemperatureMutation.isPending}
  3846. options={buildPresetOptions(chamberTempPresets, 'C')}
  3847. onClose={() => setStatusControlMenu(null)}
  3848. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  3849. />
  3850. )}
  3851. </div>
  3852. );
  3853. })()}
  3854. {/* Active nozzle indicator for dual-nozzle printers */}
  3855. {isDualNozzle && (
  3856. <DualNozzleHoverCard
  3857. leftSlot={leftNozzleSlot}
  3858. rightSlot={rightNozzleSlot}
  3859. activeNozzle={activeNozzle}
  3860. filamentInfo={filamentInfo}
  3861. >
  3862. <div
  3863. 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 ${
  3864. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3865. }`}
  3866. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  3867. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  3868. >
  3869. <NozzleIcon className="w-3.5 h-3.5 mb-0.5 text-amber-600 dark:text-amber-400" />
  3870. <div className="flex items-center gap-2">
  3871. <span className={`text-[11px] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3872. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  3873. </span>
  3874. <span className="text-[9px] text-bambu-gray/40">·</span>
  3875. <span className={`text-[11px] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  3876. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  3877. </span>
  3878. </div>
  3879. <p className="text-[9px] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3880. {statusControlMenu === 'nozzle-select' && (
  3881. <IndicatorControlPopover
  3882. title="Set Nozzle Selection"
  3883. widthClass="w-[300px]"
  3884. popoverWidth={300}
  3885. popoverHeight={140}
  3886. isPending={selectExtruderMutation.isPending}
  3887. options={[
  3888. { label: 'Left', value: 1 },
  3889. { label: 'Right', value: 0 },
  3890. ]}
  3891. onClose={() => setStatusControlMenu(null)}
  3892. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  3893. />
  3894. )}
  3895. </div>
  3896. </DualNozzleHoverCard>
  3897. )}
  3898. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  3899. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  3900. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  3901. )}
  3902. </div>
  3903. <div className="mt-2 flex items-center gap-1.5">
  3904. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  3905. const active = value > 0;
  3906. return (
  3907. <div
  3908. key={key}
  3909. 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 ${
  3910. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3911. }`}
  3912. title={canUseStatusControls ? label : statusControlTitle}
  3913. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  3914. >
  3915. <Icon className={`w-3 h-3 shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  3916. <span className={`text-[10px] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  3917. {value}%
  3918. </span>
  3919. {statusControlMenu === `fan-${key}` && (
  3920. <IndicatorControlPopover
  3921. title={`Set ${label} Speed`}
  3922. unit="%"
  3923. customMin={0}
  3924. customMax={100}
  3925. isPending={fanSpeedMutation.isPending}
  3926. options={buildPresetOptions(fanSpeedPresets, '%')}
  3927. onClose={() => setStatusControlMenu(null)}
  3928. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'chamber', speed })}
  3929. />
  3930. )}
  3931. </div>
  3932. );
  3933. })}
  3934. </div>
  3935. </>
  3936. );
  3937. })()}
  3938. {viewMode === 'expanded' && showClearPlateButton && (
  3939. <button
  3940. type="button"
  3941. onClick={() => clearPlateMutation.mutate()}
  3942. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3943. 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"
  3944. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3945. >
  3946. {clearPlateMutation.isPending ? (
  3947. <Loader2 className="w-3 h-3 animate-spin" />
  3948. ) : (
  3949. <PlateClearedIcon className="w-4 h-4" />
  3950. )}
  3951. {t('printers.plateStatus.markCleared')}
  3952. </button>
  3953. )}
  3954. {/* Controls */}
  3955. {viewMode === 'expanded' && (() => {
  3956. // Determine print state for control buttons
  3957. const isRunning = status.state === 'RUNNING';
  3958. const isPaused = status.state === 'PAUSE';
  3959. const isPrinting = isRunning || isPaused;
  3960. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  3961. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  3962. 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';
  3963. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  3964. return (
  3965. <div className="mt-3">
  3966. {/* Section Header */}
  3967. <div className="flex items-center gap-2 mb-2">
  3968. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  3969. {t('printers.controls')}
  3970. </span>
  3971. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3972. </div>
  3973. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  3974. {/* Left: Secondary controls */}
  3975. <div className="flex flex-wrap items-center gap-2 min-w-0">
  3976. <button
  3977. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  3978. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  3979. className={`${iconControlClass} ${
  3980. status.chamber_light
  3981. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  3982. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  3983. }`}
  3984. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  3985. >
  3986. <ChamberLight on={status.chamber_light ?? false} className="w-4 h-4" />
  3987. </button>
  3988. {/* Airduct Mode (P2S / X2D / H2*) */}
  3989. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  3990. const isHeating = status.airduct_mode === 1;
  3991. const Icon = isHeating ? Flame : Snowflake;
  3992. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  3993. 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';
  3994. return (
  3995. <div className="relative">
  3996. <button
  3997. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  3998. disabled={!hasPermission('printers:control')}
  3999. className={`${iconControlClass} ${bg}`}
  4000. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4001. >
  4002. <Icon className={`w-4 h-4 ${color}`} />
  4003. </button>
  4004. {showAirductMenu === printer.id && (
  4005. <>
  4006. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4007. <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]">
  4008. {([
  4009. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4010. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4011. ] as const).map(({ mode, label, modeId }) => (
  4012. <button
  4013. key={mode}
  4014. onClick={() => {
  4015. airductMutation.mutate(mode);
  4016. setShowAirductMenu(null);
  4017. }}
  4018. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4019. status.airduct_mode === modeId
  4020. ? 'text-bambu-green bg-bambu-green/10'
  4021. : 'text-white hover:bg-bambu-dark-tertiary'
  4022. }`}
  4023. >
  4024. {mode === 'heating' ? <Flame className="w-3 h-3" /> : <Snowflake className="w-3 h-3" />}
  4025. {label}
  4026. </button>
  4027. ))}
  4028. </div>
  4029. </>
  4030. )}
  4031. </div>
  4032. );
  4033. })()}
  4034. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4035. {(() => {
  4036. const canControl = hasPermission('printers:control');
  4037. const disabled = isPrinting || !canControl;
  4038. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  4039. 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';
  4040. const requestZJog = (direction: 1 | -1) => {
  4041. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  4042. // The jog never disables the soft endstops (#2579), so it's always
  4043. // safe: the firmware clamps the move at the travel limit, or refuses
  4044. // it if the printer isn't homed. No not-homed bypass to gate.
  4045. bedJogMutation.mutate({ distance: signed });
  4046. };
  4047. const requestXyJog = (x: number, y: number) => {
  4048. xyJogMutation.mutate({ x, y });
  4049. };
  4050. const requestExtruderJog = (distance: number) => {
  4051. extruderJogMutation.mutate(distance);
  4052. };
  4053. return (
  4054. <div className="relative">
  4055. <button
  4056. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4057. disabled={disabled}
  4058. className={`${iconControlClass} ${
  4059. disabled
  4060. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4061. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4062. }`}
  4063. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4064. >
  4065. <Move className="w-4 h-4" />
  4066. </button>
  4067. {showBedJogMenu === printer.id && (
  4068. <>
  4069. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4070. <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">
  4071. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4072. {t('printers.bedJog.title')}
  4073. </div>
  4074. <div className="h-px bg-bambu-dark-tertiary" />
  4075. {/* #2579: Bambu firmware does not enforce soft endstops on
  4076. G-code sent over MQTT, so manual moves can drive past the
  4077. travel limits and cause a collision. Not fixable from our
  4078. side — warn prominently. */}
  4079. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[11px] leading-snug text-yellow-700 dark:text-yellow-400">
  4080. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4081. <span>{t('printers.bedJog.limitWarning')}</span>
  4082. </div>
  4083. <div className="h-px bg-bambu-dark-tertiary" />
  4084. <div className="flex justify-center px-3 py-2.5">
  4085. <div className="flex items-center justify-center gap-3">
  4086. <div className="grid grid-cols-3 gap-1">
  4087. <div />
  4088. <button
  4089. onClick={() => requestXyJog(0, bedJogStep)}
  4090. disabled={xyJogMutation.isPending}
  4091. className={jogButtonClass}
  4092. aria-label="Move Y forward"
  4093. >
  4094. <ArrowUp className="w-4 h-4" />
  4095. </button>
  4096. <div />
  4097. <button
  4098. onClick={() => requestXyJog(-bedJogStep, 0)}
  4099. disabled={xyJogMutation.isPending}
  4100. className={jogButtonClass}
  4101. aria-label="Move X left"
  4102. >
  4103. <ArrowLeft className="w-4 h-4" />
  4104. </button>
  4105. <button
  4106. onClick={() => {
  4107. setShowBedJogMenu(null);
  4108. homeAxesMutation.mutate('all');
  4109. }}
  4110. disabled={homeAxesMutation.isPending}
  4111. className={jogButtonClass}
  4112. aria-label={t('printers.bedJog.homeZ')}
  4113. >
  4114. <Home className="w-4 h-4" />
  4115. </button>
  4116. <button
  4117. onClick={() => requestXyJog(bedJogStep, 0)}
  4118. disabled={xyJogMutation.isPending}
  4119. className={jogButtonClass}
  4120. aria-label="Move X right"
  4121. >
  4122. <ArrowRight className="w-4 h-4" />
  4123. </button>
  4124. <div />
  4125. <button
  4126. onClick={() => requestXyJog(0, -bedJogStep)}
  4127. disabled={xyJogMutation.isPending}
  4128. className={jogButtonClass}
  4129. aria-label="Move Y back"
  4130. >
  4131. <ArrowDown className="w-4 h-4" />
  4132. </button>
  4133. <div />
  4134. </div>
  4135. <div className="flex flex-col items-center gap-1">
  4136. <button
  4137. onClick={() => requestZJog(-1)}
  4138. disabled={bedJogMutation.isPending}
  4139. className={jogButtonClass}
  4140. aria-label={t('printers.bedJog.up')}
  4141. >
  4142. <ArrowUp className="w-4 h-4" />
  4143. </button>
  4144. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4145. <Layers className="w-4 h-4" />
  4146. </div>
  4147. <button
  4148. onClick={() => requestZJog(1)}
  4149. disabled={bedJogMutation.isPending}
  4150. className={jogButtonClass}
  4151. aria-label={t('printers.bedJog.down')}
  4152. >
  4153. <ArrowDown className="w-4 h-4" />
  4154. </button>
  4155. </div>
  4156. <div className="flex flex-col items-center gap-1">
  4157. <button
  4158. onClick={() => requestExtruderJog(-bedJogStep)}
  4159. disabled={extruderJogMutation.isPending}
  4160. className={jogButtonClass}
  4161. aria-label="Retract filament"
  4162. >
  4163. <ArrowUp className="w-4 h-4" />
  4164. </button>
  4165. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4166. <span className="text-sm font-semibold leading-none">E</span>
  4167. </div>
  4168. <button
  4169. onClick={() => requestExtruderJog(bedJogStep)}
  4170. disabled={extruderJogMutation.isPending}
  4171. className={jogButtonClass}
  4172. aria-label="Extrude filament"
  4173. >
  4174. <ArrowDown className="w-4 h-4" />
  4175. </button>
  4176. </div>
  4177. </div>
  4178. </div>
  4179. <div className="h-px bg-bambu-dark-tertiary" />
  4180. <div className="px-3 pt-2.5 pb-3">
  4181. <div className="mb-1 text-[9px] uppercase tracking-wider text-bambu-gray/70">
  4182. {t('printers.bedJog.step')}
  4183. </div>
  4184. <div className="flex gap-1">
  4185. {[1, 10, 50].map((step) => (
  4186. <button
  4187. key={step}
  4188. onClick={() => setBedJogStep(step)}
  4189. className={`flex-1 px-1 py-1 rounded text-[10px] transition-colors ${
  4190. bedJogStep === step
  4191. ? 'bg-bambu-green/20 text-bambu-green'
  4192. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4193. }`}
  4194. >
  4195. {step}
  4196. </button>
  4197. ))}
  4198. </div>
  4199. </div>
  4200. </div>
  4201. </>
  4202. )}
  4203. </div>
  4204. );
  4205. })()}
  4206. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4207. <button
  4208. onClick={handleTogglePlateDetection}
  4209. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4210. className={`${iconControlClass} rounded-r-none ${
  4211. printer.plate_detection_enabled
  4212. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4213. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4214. }`}
  4215. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4216. >
  4217. {plateDetectionMutation.isPending ? (
  4218. <Loader2 className="w-4 h-4 animate-spin" />
  4219. ) : (
  4220. <ScanSearch className="w-4 h-4" />
  4221. )}
  4222. </button>
  4223. <button
  4224. onClick={handleOpenPlateManagement}
  4225. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4226. 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 ${
  4227. printer.plate_detection_enabled
  4228. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4229. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4230. }`}
  4231. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4232. >
  4233. {isCheckingPlate ? (
  4234. <Loader2 className="w-4 h-4 animate-spin" />
  4235. ) : (
  4236. <ChevronDown className="w-4 h-4" />
  4237. )}
  4238. </button>
  4239. </div>
  4240. {/* Print Speed */}
  4241. {(() => (
  4242. <div className="relative">
  4243. <button
  4244. data-testid="speed-control"
  4245. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4246. disabled={!isPrinting || !hasPermission('printers:control')}
  4247. className={`${iconControlClass} ${
  4248. isPrinting
  4249. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4250. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4251. }`}
  4252. title={isPrinting ? t('printers.speed.title') : undefined}
  4253. >
  4254. <Gauge className="w-4 h-4" />
  4255. </button>
  4256. {showSpeedMenu === printer.id && (
  4257. <>
  4258. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4259. <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]">
  4260. {([
  4261. { mode: 1, label: t('printers.speed.silent') },
  4262. { mode: 2, label: t('printers.speed.standard') },
  4263. { mode: 3, label: t('printers.speed.sport') },
  4264. { mode: 4, label: t('printers.speed.ludicrous') },
  4265. ] as const).map(({ mode, label }) => (
  4266. <button
  4267. key={mode}
  4268. onClick={() => {
  4269. printSpeedMutation.mutate(mode);
  4270. setShowSpeedMenu(null);
  4271. }}
  4272. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4273. status.speed_level === mode
  4274. ? 'text-bambu-green bg-bambu-green/10'
  4275. : 'text-white hover:bg-bambu-dark-tertiary'
  4276. }`}
  4277. >
  4278. {label}
  4279. </button>
  4280. ))}
  4281. </div>
  4282. </>
  4283. )}
  4284. </div>
  4285. ))()}
  4286. </div>
  4287. {/* Right: Print Control Buttons */}
  4288. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4289. {/* Pause/Resume button */}
  4290. {(() => {
  4291. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4292. return (
  4293. <button
  4294. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4295. disabled={pauseUnavailable}
  4296. className={`
  4297. ${printControlClass}
  4298. ${pauseUnavailable
  4299. ? unavailablePrintActionClass
  4300. : isPaused
  4301. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4302. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4303. }
  4304. `}
  4305. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4306. >
  4307. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  4308. {isPaused ? t('printers.resume') : t('printers.pause')}
  4309. </button>
  4310. );
  4311. })()}
  4312. {/* Stop button */}
  4313. {(() => {
  4314. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4315. return (
  4316. <button
  4317. onClick={() => setShowStopConfirm(true)}
  4318. disabled={stopUnavailable}
  4319. className={`
  4320. ${printControlClass}
  4321. ${stopUnavailable
  4322. ? unavailablePrintActionClass
  4323. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4324. }
  4325. `}
  4326. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4327. >
  4328. <Square className="w-3 h-3" />
  4329. {t('printers.stop')}
  4330. </button>
  4331. );
  4332. })()}
  4333. </div>
  4334. </div>
  4335. </div>
  4336. );
  4337. })()}
  4338. {/* AMS Units - 2-Column Grid Layout */}
  4339. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4340. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4341. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4342. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4343. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4344. const filamentSlotClass = 'min-w-14';
  4345. // #1762 (comment 2): while a print is running/paused, overlay a small
  4346. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4347. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4348. // staged to a printer with mismatched filament: the wrong-slot pill
  4349. // is visible the instant printing starts.
  4350. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4351. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4352. ? status.ams_mapping
  4353. : [];
  4354. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4355. const boundedSlotCount = Math.max(1, slotCount);
  4356. const gapCount = Math.max(0, boundedSlotCount - 1);
  4357. const minWidth = `calc(${boundedSlotCount} * 3.5rem + ${gapCount} * 0.25rem + 1rem)`;
  4358. return {
  4359. flex: `1 1 ${minWidth}`,
  4360. minWidth,
  4361. };
  4362. };
  4363. return (
  4364. <div className="mt-3">
  4365. {/* Section Header */}
  4366. <div className="flex items-center gap-2 mb-2">
  4367. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  4368. {t('printers.filaments')}
  4369. </span>
  4370. <AmsBackupBadge
  4371. state={status.ams_filament_backup}
  4372. onClick={() => setAmsBackupModalOpen(true)}
  4373. />
  4374. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4375. </div>
  4376. {/* AMS Content */}
  4377. <div className="flex flex-wrap gap-2">
  4378. {/* Regular AMS units */}
  4379. {regularAms.map((ams) => {
  4380. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4381. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4382. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4383. const isLeftNozzle = extruderId === 1;
  4384. const isRightNozzle = extruderId === 0;
  4385. return (
  4386. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4387. {/* Header: Label + Stats (no icon) */}
  4388. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4389. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4390. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4391. <AmsNameHoverCard
  4392. ams={ams}
  4393. printerId={printer.id}
  4394. label={getAmsLabel(ams.id, ams.tray.length)}
  4395. amsLabels={amsLabels}
  4396. canEdit={hasPermission('printers:update')}
  4397. onSaved={refetchAmsLabels}
  4398. >
  4399. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4400. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4401. </span>
  4402. </AmsNameHoverCard>
  4403. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4404. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4405. )}
  4406. </div>
  4407. {(ams.humidity != null || ams.temp != null) && (
  4408. <div className="flex shrink-0 items-center gap-1.5">
  4409. {ams.humidity != null && (
  4410. <HumidityIndicator
  4411. humidity={ams.humidity}
  4412. goodThreshold={amsThresholds?.humidityGood}
  4413. fairThreshold={amsThresholds?.humidityFair}
  4414. onClick={() => setAmsHistoryModal({
  4415. amsId: ams.id,
  4416. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4417. mode: 'humidity',
  4418. })}
  4419. compact
  4420. />
  4421. )}
  4422. {ams.temp != null && (
  4423. <div className="mr-1">
  4424. <TemperatureIndicator
  4425. temp={ams.temp}
  4426. goodThreshold={amsThresholds?.tempGood}
  4427. fairThreshold={amsThresholds?.tempFair}
  4428. onClick={() => setAmsHistoryModal({
  4429. amsId: ams.id,
  4430. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4431. mode: 'temperature',
  4432. })}
  4433. compact
  4434. />
  4435. </div>
  4436. )}
  4437. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4438. Screen-only models (P1 series) keep the control but can't
  4439. be commanded: it stays disabled and says why (#2533). */}
  4440. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4441. <button
  4442. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4443. onClick={(e) => {
  4444. if (ams.dry_time > 0) {
  4445. stopDryingMutation.mutate(ams.id);
  4446. } else if (dryingPopoverAmsId === ams.id) {
  4447. setDryingPopoverAmsId(null);
  4448. } else {
  4449. const firstTray = ams.tray.find(t => t.tray_type);
  4450. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4451. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4452. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4453. setDryingFilament(filType);
  4454. setDryingTemp(preset[moduleType] || preset.n3f);
  4455. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4456. setDryingRotateTray(false);
  4457. setDryingPopoverModuleType(ams.module_type);
  4458. setDryingPopoverAmsId(ams.id);
  4459. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4460. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4461. }
  4462. }}
  4463. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4464. ams.dry_time > 0
  4465. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4466. : status.drying_screen_only || ams.dry_sf_reason?.length
  4467. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4468. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4469. }`}
  4470. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : ams.dry_sf_reason?.length ? t('printers.drying.powerRequired') : t('printers.drying.start')}
  4471. >
  4472. <Flame className="w-3 h-3" />
  4473. </button>
  4474. )}
  4475. </div>
  4476. )}
  4477. </div>
  4478. {/* Drying status bar */}
  4479. {ams.dry_time > 0 && (
  4480. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  4481. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  4482. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4483. {ams.dry_filament && ams.dry_target_temp != null && (
  4484. <span className="text-amber-700/80 dark:text-amber-300/70">
  4485. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  4486. </span>
  4487. )}
  4488. <span className="text-amber-700/80 dark:text-amber-300/70">
  4489. {t('printers.drying.timeRemaining', {
  4490. time: ams.dry_time >= 60
  4491. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4492. : `${ams.dry_time}m`
  4493. })}
  4494. </span>
  4495. {/* A cycle on a screen-only model was started at the printer
  4496. and can only be stopped there (#2533). */}
  4497. {!status.drying_screen_only && (
  4498. <button
  4499. onClick={() => stopDryingMutation.mutate(ams.id)}
  4500. disabled={stopDryingMutation.isPending}
  4501. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  4502. title={t('printers.drying.stop')}
  4503. >
  4504. <X className="w-3 h-3" />
  4505. </button>
  4506. )}
  4507. </div>
  4508. )}
  4509. {/* Slots grid: 4 columns - always render 4 slots */}
  4510. <div className="grid w-full grid-cols-[repeat(4,minmax(3.5rem,1fr))] gap-1">
  4511. {[0, 1, 2, 3].map((slotIdx) => {
  4512. // Find tray data for this slot (may be undefined if data incomplete)
  4513. // Use array index if available, as tray.id may not always be set
  4514. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4515. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4516. const isEmpty = !tray?.tray_type;
  4517. const emptyKind = getEmptySlotKind(tray);
  4518. // Check if this is the currently loaded tray
  4519. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4520. const globalTrayId = ams.id * 4 + slotIdx;
  4521. const isActive = effectiveTrayNow === globalTrayId;
  4522. // Runout guidance (#2587): the slot the paused print now
  4523. // expects filament in, and the slot that ran out.
  4524. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4525. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4526. // Get cloud preset info if available
  4527. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4528. // Get saved slot preset mapping (for user-configured slots)
  4529. const slotPreset = slotPresets?.[globalTrayId];
  4530. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4531. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4532. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4533. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4534. // Slot-assigned-only spool fill (no tag link required)
  4535. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4536. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4537. : undefined;
  4538. const slotSpoolForFill = slotAssignmentForFill
  4539. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4540. : undefined;
  4541. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4542. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4543. : null;
  4544. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4545. const inventoryFill = (() => {
  4546. const sp = inventoryAssignment?.spool;
  4547. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4548. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4549. }
  4550. return null;
  4551. })();
  4552. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4553. // (inventory weight_used may be stale or over-counted — #676)
  4554. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4555. ? null : inventoryFill;
  4556. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4557. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4558. : resolvedInventoryFill !== null ? 'inventory' as const
  4559. : hasFillLevel ? 'ams' as const
  4560. : undefined;
  4561. // Build filament data for hover card
  4562. const filamentData = tray?.tray_type ? {
  4563. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4564. // Spoolman spool name wins over cloud lookup so a slot bound to
  4565. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4566. // Design PLA") instead of whatever the printer's filament_id
  4567. // resolves to in the cloud catalog (often "Generic PLA" for
  4568. // P-prefix local presets). Spoolman's filament.name is just the
  4569. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4570. // the hover card shows "Devil Design PLA Basic" rather than the
  4571. // vendor-less form. Strip the "@<printer>..." suffix that
  4572. // BambuStudio appends to user-preset names.
  4573. 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,
  4574. colorName: getColorName(tray.tray_color || ''),
  4575. colorHex: tray.tray_color || null,
  4576. kFactor: formatKValue(tray.k),
  4577. fillLevel: effectiveFill,
  4578. trayUuid: tray.tray_uuid || null,
  4579. tagUid: tray.tag_uid || null,
  4580. fillSource,
  4581. } : null;
  4582. // Check if this specific slot is being refreshed
  4583. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4584. refreshingSlot?.slotId === slotIdx;
  4585. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4586. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4587. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4588. ? `P${activePrintSlotIdx + 1}`
  4589. : null;
  4590. // Slot visual content (goes inside hover card)
  4591. const slotVisual = (
  4592. <div
  4593. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4594. isExpectedSlot
  4595. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4596. : isRanOutSlot
  4597. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4598. : isActive
  4599. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4600. : ''
  4601. }`}
  4602. >
  4603. {isExpectedSlot && (
  4604. <span
  4605. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  4606. title={t('printers.expectedSlot.title')}
  4607. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4608. >
  4609. </span>
  4610. )}
  4611. {activePrintSlotLabel && (
  4612. <span
  4613. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4614. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4615. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4616. >
  4617. {activePrintSlotLabel}
  4618. </span>
  4619. )}
  4620. {/* Filament color circle with 1-based slot number centered inside */}
  4621. <FilamentSlotCircle
  4622. trayColor={tray?.tray_color}
  4623. trayType={tray?.tray_type}
  4624. isEmpty={isEmpty}
  4625. emptyKind={emptyKind}
  4626. slotNumber={slotIdx + 1}
  4627. />
  4628. <div className="text-[9px] text-white font-bold truncate">
  4629. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4630. </div>
  4631. {/* Fill bar */}
  4632. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4633. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4634. <div
  4635. className="h-full rounded-full transition-all"
  4636. style={{
  4637. width: `${effectiveFill}%`,
  4638. backgroundColor: getFillBarColor(effectiveFill),
  4639. }}
  4640. />
  4641. )}
  4642. </div>
  4643. </div>
  4644. );
  4645. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4646. return (
  4647. <div key={slotIdx} className={`relative group w-full ${filamentSlotClass}`}>
  4648. {/* Loading overlay during RFID re-read */}
  4649. {isRefreshing && (
  4650. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4651. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  4652. </div>
  4653. )}
  4654. {/* Hover card wraps only the visual content */}
  4655. {filamentData ? (
  4656. <FilamentHoverCard
  4657. data={filamentData}
  4658. actions={renderAmsSlotActions({
  4659. amsId: ams.id,
  4660. slotId: slotIdx,
  4661. loadTrayId: ams.id * 4 + slotIdx,
  4662. isRefreshing,
  4663. })}
  4664. spoolman={{
  4665. enabled: spoolmanEnabled,
  4666. // #1457: slot assignment is the user's most explicit action — it must
  4667. // outrank the tag-link, which can be stale when a non-RFID slot's
  4668. // fallback tag is still attached to a previous spool in Spoolman.
  4669. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4670. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4671. spoolmanUrl,
  4672. syncMode: spoolmanSyncMode,
  4673. // Suppress Link button when slot is already occupied by ANY assignment
  4674. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4675. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4676. // still appearing on slots with a local Devil Design PLA assigned.
  4677. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4678. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4679. setLinkSpoolModal({
  4680. tagUid: filamentData.tagUid || linkTag,
  4681. trayUuid: filamentData.trayUuid || '',
  4682. printerId: printer.id,
  4683. amsId: ams.id,
  4684. trayId: slotIdx,
  4685. });
  4686. } : undefined,
  4687. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4688. }}
  4689. inventory={(() => {
  4690. if (spoolmanEnabled) {
  4691. if (spoolmanLoading) return undefined;
  4692. const slotAssignment = slotAssignmentForFill;
  4693. const spoolmanSpool = slotSpoolForFill;
  4694. return {
  4695. assignedSpool: spoolmanSpool ? {
  4696. id: spoolmanSpool.id,
  4697. material: spoolmanSpool.material,
  4698. brand: spoolmanSpool.brand ?? null,
  4699. color_name: spoolmanSpool.color_name ?? null,
  4700. remainingWeightGrams: spoolmanSpool.label_weight
  4701. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4702. : undefined,
  4703. } : null,
  4704. onAssignSpool: () => setAssignSpoolModal({
  4705. printerId: printer.id,
  4706. amsId: ams.id,
  4707. trayId: slotIdx,
  4708. trayInfo: {
  4709. type: tray?.tray_type || filamentData.profile,
  4710. material: tray?.tray_type ?? undefined,
  4711. profile: filamentData.profile,
  4712. color: filamentData.colorHex || '',
  4713. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4714. },
  4715. }),
  4716. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4717. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4718. };
  4719. }
  4720. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4721. return {
  4722. assignedSpool: assignment?.spool ? {
  4723. id: assignment.spool.id,
  4724. material: assignment.spool.material,
  4725. brand: assignment.spool.brand,
  4726. color_name: assignment.spool.color_name,
  4727. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4728. } : null,
  4729. onAssignSpool: () => setAssignSpoolModal({
  4730. printerId: printer.id,
  4731. amsId: ams.id,
  4732. trayId: slotIdx,
  4733. trayInfo: {
  4734. type: tray?.tray_type || filamentData.profile,
  4735. material: tray?.tray_type ?? undefined,
  4736. profile: filamentData.profile,
  4737. color: filamentData.colorHex || '',
  4738. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4739. },
  4740. }),
  4741. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4742. isAssigned: !!assignment || isBambuLabSpool(tray),
  4743. };
  4744. })()}
  4745. configureSlot={{
  4746. enabled: hasPermission('printers:control'),
  4747. onConfigure: () => setConfigureSlotModal({
  4748. amsId: ams.id,
  4749. trayId: slotIdx,
  4750. trayCount: ams.tray.length,
  4751. trayType: tray?.tray_type || undefined,
  4752. trayColor: tray?.tray_color || undefined,
  4753. traySubBrands: tray?.tray_sub_brands || undefined,
  4754. trayInfoIdx: tray?.tray_info_idx || undefined,
  4755. extruderId: mappedExtruderId,
  4756. caliIdx: tray?.cali_idx,
  4757. savedPresetId: slotPreset?.preset_id,
  4758. }),
  4759. }}
  4760. >
  4761. {slotVisual}
  4762. </FilamentHoverCard>
  4763. ) : (
  4764. <EmptySlotHoverCard
  4765. kind={emptyKind ?? undefined}
  4766. actions={renderAmsSlotActions({
  4767. amsId: ams.id,
  4768. slotId: slotIdx,
  4769. loadTrayId: ams.id * 4 + slotIdx,
  4770. isRefreshing,
  4771. })}
  4772. configureSlot={{
  4773. enabled: hasPermission('printers:control'),
  4774. onConfigure: () => setConfigureSlotModal({
  4775. amsId: ams.id,
  4776. trayId: slotIdx,
  4777. trayCount: ams.tray.length,
  4778. extruderId: mappedExtruderId,
  4779. }),
  4780. }}
  4781. onAssignSpool={() => setAssignSpoolModal({
  4782. printerId: printer.id,
  4783. amsId: ams.id,
  4784. trayId: slotIdx,
  4785. trayInfo: {
  4786. type: '',
  4787. material: undefined,
  4788. profile: '',
  4789. color: '',
  4790. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4791. },
  4792. })}
  4793. >
  4794. {slotVisual}
  4795. </EmptySlotHoverCard>
  4796. )}
  4797. </div>
  4798. );
  4799. })}
  4800. </div>
  4801. </div>
  4802. );
  4803. })}
  4804. {/* HT AMS units */}
  4805. {htAms.map((ams) => {
  4806. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4807. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4808. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4809. const isLeftNozzle = extruderId === 1;
  4810. const isRightNozzle = extruderId === 0;
  4811. const tray = ams.tray[0];
  4812. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4813. const isEmpty = !tray?.tray_type;
  4814. const emptyKind = getEmptySlotKind(tray);
  4815. // Check if this is the currently loaded tray
  4816. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  4817. const isActive = effectiveTrayNow === globalTrayId;
  4818. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  4819. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4820. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4821. // Get cloud preset info if available
  4822. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4823. // Get saved slot preset mapping (for user-configured slots)
  4824. const slotPreset = slotPresets?.[globalTrayId];
  4825. const htSlotId = tray?.id ?? 0;
  4826. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4827. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  4828. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  4829. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  4830. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  4831. const htInventoryFill = (() => {
  4832. const sp = htInventoryAssignment?.spool;
  4833. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4834. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4835. }
  4836. return null;
  4837. })();
  4838. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  4839. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4840. ? null : htInventoryFill;
  4841. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  4842. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4843. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  4844. : undefined;
  4845. const htSlotSpoolForFill = htSlotAssignmentForFill
  4846. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  4847. : undefined;
  4848. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  4849. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  4850. : null;
  4851. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4852. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  4853. : htResolvedInventoryFill !== null ? 'inventory' as const
  4854. : hasFillLevel ? 'ams' as const
  4855. : undefined;
  4856. // Build filament data for hover card
  4857. const filamentData = tray?.tray_type ? {
  4858. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4859. 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,
  4860. colorName: getColorName(tray.tray_color || ''),
  4861. colorHex: tray.tray_color || null,
  4862. kFactor: formatKValue(tray.k),
  4863. fillLevel: htEffectiveFill,
  4864. trayUuid: tray.tray_uuid || null,
  4865. tagUid: tray.tag_uid || null,
  4866. fillSource: htFillSource,
  4867. } : null;
  4868. // Check if this specific slot is being refreshed
  4869. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  4870. refreshingSlot?.slotId === htSlotId;
  4871. // #1762 (comment 2): active print-slot index for this HT slot.
  4872. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4873. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  4874. ? `P${htActivePrintSlotIdx + 1}`
  4875. : null;
  4876. // Slot visual content (goes inside hover card)
  4877. const slotVisual = (
  4878. <div
  4879. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4880. isExpectedSlot
  4881. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4882. : isRanOutSlot
  4883. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4884. : isActive
  4885. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4886. : ''
  4887. }`}
  4888. >
  4889. {isExpectedSlot && (
  4890. <span
  4891. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  4892. title={t('printers.expectedSlot.title')}
  4893. className="absolute top-0.5 left-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4894. >
  4895. </span>
  4896. )}
  4897. {htActivePrintSlotLabel && (
  4898. <span
  4899. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  4900. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  4901. className="absolute top-0.5 right-0.5 px-1 py-px text-[8px] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4902. >
  4903. {htActivePrintSlotLabel}
  4904. </span>
  4905. )}
  4906. {/* Filament color circle with 1-based slot number centered inside */}
  4907. <FilamentSlotCircle
  4908. trayColor={tray?.tray_color}
  4909. trayType={tray?.tray_type}
  4910. isEmpty={isEmpty}
  4911. emptyKind={emptyKind}
  4912. slotNumber={1}
  4913. />
  4914. <div className="text-[9px] text-white font-bold truncate">
  4915. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4916. </div>
  4917. {/* Fill bar */}
  4918. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4919. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  4920. <div
  4921. className="h-full rounded-full transition-all"
  4922. style={{
  4923. width: `${htEffectiveFill}%`,
  4924. backgroundColor: getFillBarColor(htEffectiveFill),
  4925. }}
  4926. />
  4927. )}
  4928. </div>
  4929. </div>
  4930. );
  4931. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  4932. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  4933. // Without this override, the L view squishes HT into a sliver next to the
  4934. // 4-slot AMS neighbors.
  4935. const htCardStyle: React.CSSProperties = { flex: '1 1 11rem', minWidth: '11rem' };
  4936. return (
  4937. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4938. {/* Row 1: Label + Nozzle + Drying */}
  4939. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4940. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4941. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4942. <AmsNameHoverCard
  4943. ams={ams}
  4944. printerId={printer.id}
  4945. label={getAmsLabel(ams.id, ams.tray.length)}
  4946. amsLabels={amsLabels}
  4947. canEdit={hasPermission('printers:update')}
  4948. onSaved={refetchAmsLabels}
  4949. >
  4950. <span className="block truncate text-[10px] text-white font-medium cursor-default select-none">
  4951. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4952. </span>
  4953. </AmsNameHoverCard>
  4954. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4955. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4956. )}
  4957. </div>
  4958. {/* Drying button for HT AMS */}
  4959. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4960. <div className="relative ml-auto">
  4961. <button
  4962. disabled={status.drying_screen_only}
  4963. onClick={(e) => {
  4964. if (ams.dry_time > 0) {
  4965. stopDryingMutation.mutate(ams.id);
  4966. } else if (dryingPopoverAmsId === ams.id) {
  4967. setDryingPopoverAmsId(null);
  4968. } else {
  4969. const firstTray = ams.tray.find(t => t.tray_type);
  4970. const filType = (firstTray?.tray_type || 'PLA').split(' ')[0].toUpperCase();
  4971. const preset = dryingPresets[filType] || dryingPresets['PLA'];
  4972. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4973. setDryingFilament(filType);
  4974. setDryingTemp(preset[moduleType] || preset.n3f);
  4975. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4976. setDryingRotateTray(false);
  4977. setDryingPopoverModuleType(ams.module_type);
  4978. setDryingPopoverAmsId(ams.id);
  4979. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4980. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4981. }
  4982. }}
  4983. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[9px] transition-colors ${
  4984. ams.dry_time > 0
  4985. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4986. : status.drying_screen_only
  4987. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4988. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4989. }`}
  4990. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  4991. >
  4992. <Flame className="w-3 h-3" />
  4993. </button>
  4994. </div>
  4995. )}
  4996. </div>
  4997. {/* HT AMS drying status bar */}
  4998. {ams.dry_time > 0 && (
  4999. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[9px]">
  5000. <Flame className="w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0" />
  5001. {ams.dry_filament && ams.dry_target_temp != null && (
  5002. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  5003. {t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })}
  5004. </span>
  5005. )}
  5006. <span className="text-amber-700/80 dark:text-amber-300/70 text-[8px] truncate">
  5007. {ams.dry_time >= 60
  5008. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5009. : `${ams.dry_time}m`}
  5010. </span>
  5011. {!status.drying_screen_only && (
  5012. <button
  5013. onClick={() => stopDryingMutation.mutate(ams.id)}
  5014. disabled={stopDryingMutation.isPending}
  5015. 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"
  5016. title={t('printers.drying.stop')}
  5017. >
  5018. <X className="w-3 h-3" />
  5019. </button>
  5020. )}
  5021. </div>
  5022. )}
  5023. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5024. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5025. {/* Slot wrapper with loading overlay */}
  5026. <div className="relative group min-w-14 flex-1">
  5027. {/* Loading overlay during RFID re-read */}
  5028. {isHtRefreshing && (
  5029. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5030. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  5031. </div>
  5032. )}
  5033. {/* Hover card wraps only the visual content */}
  5034. {filamentData ? (
  5035. <FilamentHoverCard
  5036. data={filamentData}
  5037. actions={renderAmsSlotActions({
  5038. amsId: ams.id,
  5039. slotId: htSlotId,
  5040. loadTrayId: ams.id * 4 + htSlotId,
  5041. isRefreshing: isHtRefreshing,
  5042. })}
  5043. spoolman={{
  5044. enabled: spoolmanEnabled,
  5045. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5046. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5047. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5048. spoolmanUrl,
  5049. syncMode: spoolmanSyncMode,
  5050. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5051. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5052. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5053. setLinkSpoolModal({
  5054. tagUid: filamentData.tagUid || linkTag,
  5055. trayUuid: filamentData.trayUuid || '',
  5056. printerId: printer.id,
  5057. amsId: ams.id,
  5058. trayId: htSlotId,
  5059. });
  5060. } : undefined,
  5061. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5062. }}
  5063. inventory={(() => {
  5064. if (spoolmanEnabled) {
  5065. if (spoolmanLoading) return undefined;
  5066. const slotAssignment = htSlotAssignmentForFill;
  5067. const spoolmanSpool = htSlotSpoolForFill;
  5068. return {
  5069. assignedSpool: spoolmanSpool ? {
  5070. id: spoolmanSpool.id,
  5071. material: spoolmanSpool.material,
  5072. brand: spoolmanSpool.brand ?? null,
  5073. color_name: spoolmanSpool.color_name ?? null,
  5074. remainingWeightGrams: spoolmanSpool.label_weight
  5075. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5076. : undefined,
  5077. } : null,
  5078. onAssignSpool: () => setAssignSpoolModal({
  5079. printerId: printer.id,
  5080. amsId: ams.id,
  5081. trayId: htSlotId,
  5082. trayInfo: {
  5083. type: tray?.tray_type || filamentData.profile,
  5084. material: tray?.tray_type ?? undefined,
  5085. profile: filamentData.profile,
  5086. color: filamentData.colorHex || '',
  5087. location: getAmsLabel(ams.id, ams.tray.length),
  5088. },
  5089. }),
  5090. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5091. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5092. };
  5093. }
  5094. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5095. return {
  5096. assignedSpool: assignment?.spool ? {
  5097. id: assignment.spool.id,
  5098. material: assignment.spool.material,
  5099. brand: assignment.spool.brand,
  5100. color_name: assignment.spool.color_name,
  5101. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5102. } : null,
  5103. onAssignSpool: () => setAssignSpoolModal({
  5104. printerId: printer.id,
  5105. amsId: ams.id,
  5106. trayId: htSlotId,
  5107. trayInfo: {
  5108. type: tray?.tray_type || filamentData.profile,
  5109. material: tray?.tray_type ?? undefined,
  5110. profile: filamentData.profile,
  5111. color: filamentData.colorHex || '',
  5112. location: getAmsLabel(ams.id, ams.tray.length),
  5113. },
  5114. }),
  5115. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5116. isAssigned: !!assignment || isBambuLabSpool(tray),
  5117. };
  5118. })()}
  5119. configureSlot={{
  5120. enabled: hasPermission('printers:control'),
  5121. onConfigure: () => setConfigureSlotModal({
  5122. amsId: ams.id,
  5123. trayId: htSlotId,
  5124. trayCount: ams.tray.length,
  5125. trayType: tray?.tray_type || undefined,
  5126. trayColor: tray?.tray_color || undefined,
  5127. traySubBrands: tray?.tray_sub_brands || undefined,
  5128. trayInfoIdx: tray?.tray_info_idx || undefined,
  5129. extruderId: mappedExtruderId,
  5130. caliIdx: tray?.cali_idx,
  5131. savedPresetId: slotPreset?.preset_id,
  5132. }),
  5133. }}
  5134. >
  5135. {slotVisual}
  5136. </FilamentHoverCard>
  5137. ) : (
  5138. <EmptySlotHoverCard
  5139. kind={emptyKind ?? undefined}
  5140. actions={renderAmsSlotActions({
  5141. amsId: ams.id,
  5142. slotId: htSlotId,
  5143. loadTrayId: ams.id * 4 + htSlotId,
  5144. isRefreshing: isHtRefreshing,
  5145. })}
  5146. configureSlot={{
  5147. enabled: hasPermission('printers:control'),
  5148. onConfigure: () => setConfigureSlotModal({
  5149. amsId: ams.id,
  5150. trayId: htSlotId,
  5151. trayCount: ams.tray.length,
  5152. extruderId: mappedExtruderId,
  5153. }),
  5154. }}
  5155. onAssignSpool={() => setAssignSpoolModal({
  5156. printerId: printer.id,
  5157. amsId: ams.id,
  5158. trayId: htSlotId,
  5159. trayInfo: {
  5160. type: '',
  5161. material: undefined,
  5162. profile: '',
  5163. color: '',
  5164. location: getAmsLabel(ams.id, ams.tray.length),
  5165. },
  5166. })}
  5167. >
  5168. {slotVisual}
  5169. </EmptySlotHoverCard>
  5170. )}
  5171. </div>
  5172. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5173. {(ams.humidity != null || ams.temp != null) && (
  5174. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5175. {ams.temp != null && (
  5176. <TemperatureIndicator
  5177. temp={ams.temp}
  5178. goodThreshold={amsThresholds?.tempGood}
  5179. fairThreshold={amsThresholds?.tempFair}
  5180. onClick={() => setAmsHistoryModal({
  5181. amsId: ams.id,
  5182. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5183. mode: 'temperature',
  5184. })}
  5185. compact
  5186. />
  5187. )}
  5188. {ams.humidity != null && (
  5189. <HumidityIndicator
  5190. humidity={ams.humidity}
  5191. goodThreshold={amsThresholds?.humidityGood}
  5192. fairThreshold={amsThresholds?.humidityFair}
  5193. onClick={() => setAmsHistoryModal({
  5194. amsId: ams.id,
  5195. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5196. mode: 'humidity',
  5197. })}
  5198. compact
  5199. />
  5200. )}
  5201. </div>
  5202. )}
  5203. </div>
  5204. </div>
  5205. );
  5206. })}
  5207. {/* External spool(s) - grouped in one card like regular AMS */}
  5208. {status.vt_tray.length > 0 && (
  5209. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5210. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5211. <span className="block min-w-0 flex-1 truncate text-[10px] text-white font-medium">{t('printers.external')}</span>
  5212. </div>
  5213. <div className={`grid w-full ${status.vt_tray.length > 1 ? 'grid-cols-[repeat(2,minmax(3.5rem,1fr))]' : 'grid-cols-[minmax(3.5rem,1fr)]'} gap-1`}>
  5214. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5215. const extTrayId = extTray.id ?? 254;
  5216. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5217. // generically — use active_extruder to determine L vs R:
  5218. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5219. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5220. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5221. (extTrayId === 255 && status.active_extruder === 0)
  5222. : effectiveTrayNow === extTrayId;
  5223. const slotTrayId = extTrayId - 254; // 0 or 1
  5224. const extLabel = isDualNozzle
  5225. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5226. : '';
  5227. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5228. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5229. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5230. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5231. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5232. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5233. const extInventoryFill = (() => {
  5234. const sp = extInventoryAssignment?.spool;
  5235. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5236. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5237. }
  5238. return null;
  5239. })();
  5240. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5241. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5242. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5243. ? null : extInventoryFill;
  5244. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5245. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5246. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5247. : undefined;
  5248. const extSlotSpoolForFill = extSlotAssignmentForFill
  5249. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5250. : undefined;
  5251. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5252. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5253. : null;
  5254. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5255. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5256. : extResolvedInventoryFill !== null ? 'inventory' as const
  5257. : extHasFillLevel ? 'ams' as const
  5258. : undefined;
  5259. const extFilamentData = {
  5260. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5261. 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',
  5262. colorName: getColorName(extTray.tray_color || ''),
  5263. colorHex: extTray.tray_color || null,
  5264. kFactor: formatKValue(extTray.k),
  5265. fillLevel: extEffectiveFill,
  5266. trayUuid: extTray.tray_uuid || null,
  5267. tagUid: extTray.tag_uid || null,
  5268. fillSource: extFillSource,
  5269. };
  5270. const isEmpty = !extTray.tray_type;
  5271. const emptyKind = getEmptySlotKind(extTray);
  5272. const extSlotContent = (
  5273. <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' : ''}`}>
  5274. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5275. the separate Ext-L/Ext-R caption that made the row taller than
  5276. regular AMS slots), 1-based slot number on single-nozzle. */}
  5277. <FilamentSlotCircle
  5278. trayColor={extTray.tray_color}
  5279. trayType={extTray.tray_type}
  5280. isEmpty={isEmpty}
  5281. emptyKind={emptyKind}
  5282. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5283. />
  5284. <div className={`text-[9px] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5285. {extTray.tray_type || t('ams.slotEmpty')}
  5286. </div>
  5287. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5288. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5289. <div
  5290. className="h-full rounded-full transition-all"
  5291. style={{
  5292. width: `${extEffectiveFill}%`,
  5293. backgroundColor: getFillBarColor(extEffectiveFill),
  5294. }}
  5295. />
  5296. )}
  5297. </div>
  5298. </div>
  5299. );
  5300. return (
  5301. <div key={extTrayId} className={`relative group w-full ${filamentSlotClass}`}>
  5302. {!isEmpty ? (
  5303. <FilamentHoverCard
  5304. data={extFilamentData}
  5305. actions={renderAmsSlotActions({
  5306. amsId: 255,
  5307. slotId: slotTrayId,
  5308. loadTrayId: extTrayId,
  5309. includeRfid: false,
  5310. })}
  5311. spoolman={{
  5312. enabled: spoolmanEnabled,
  5313. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5314. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5315. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5316. spoolmanUrl,
  5317. syncMode: spoolmanSyncMode,
  5318. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5319. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5320. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5321. setLinkSpoolModal({
  5322. tagUid: extFilamentData.tagUid || linkTag,
  5323. trayUuid: extFilamentData.trayUuid || '',
  5324. printerId: printer.id,
  5325. amsId: 255,
  5326. trayId: slotTrayId,
  5327. });
  5328. } : undefined,
  5329. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5330. }}
  5331. inventory={(() => {
  5332. if (spoolmanEnabled) {
  5333. if (spoolmanLoading) return undefined;
  5334. const slotAssignment = extSlotAssignmentForFill;
  5335. const spoolmanSpool = extSlotSpoolForFill;
  5336. return {
  5337. assignedSpool: spoolmanSpool ? {
  5338. id: spoolmanSpool.id,
  5339. material: spoolmanSpool.material,
  5340. brand: spoolmanSpool.brand ?? null,
  5341. color_name: spoolmanSpool.color_name ?? null,
  5342. remainingWeightGrams: spoolmanSpool.label_weight
  5343. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5344. : undefined,
  5345. } : null,
  5346. onAssignSpool: () => setAssignSpoolModal({
  5347. printerId: printer.id,
  5348. amsId: 255,
  5349. trayId: slotTrayId,
  5350. trayInfo: {
  5351. type: extTray.tray_type || extFilamentData.profile,
  5352. material: extTray.tray_type ?? undefined,
  5353. profile: extFilamentData.profile,
  5354. color: extFilamentData.colorHex || '',
  5355. location: extLabel || t('printers.external'),
  5356. },
  5357. }),
  5358. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5359. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5360. };
  5361. }
  5362. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5363. return {
  5364. assignedSpool: assignment?.spool ? {
  5365. id: assignment.spool.id,
  5366. material: assignment.spool.material,
  5367. brand: assignment.spool.brand,
  5368. color_name: assignment.spool.color_name,
  5369. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5370. } : null,
  5371. onAssignSpool: () => setAssignSpoolModal({
  5372. printerId: printer.id,
  5373. amsId: 255,
  5374. trayId: slotTrayId,
  5375. trayInfo: {
  5376. type: extTray.tray_type || extFilamentData.profile,
  5377. material: extTray.tray_type ?? undefined,
  5378. profile: extFilamentData.profile,
  5379. color: extFilamentData.colorHex || '',
  5380. location: extLabel || t('printers.external'),
  5381. },
  5382. }),
  5383. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5384. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5385. };
  5386. })()}
  5387. configureSlot={{
  5388. enabled: hasPermission('printers:control'),
  5389. onConfigure: () => setConfigureSlotModal({
  5390. amsId: 255,
  5391. trayId: slotTrayId,
  5392. trayCount: 1,
  5393. trayType: extTray.tray_type || undefined,
  5394. trayColor: extTray.tray_color || undefined,
  5395. traySubBrands: extTray.tray_sub_brands || undefined,
  5396. trayInfoIdx: extTray.tray_info_idx || undefined,
  5397. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5398. caliIdx: extTray.cali_idx,
  5399. savedPresetId: extSlotPreset?.preset_id,
  5400. }),
  5401. }}
  5402. >
  5403. {extSlotContent}
  5404. </FilamentHoverCard>
  5405. ) : (
  5406. <EmptySlotHoverCard
  5407. kind={emptyKind ?? undefined}
  5408. actions={renderAmsSlotActions({
  5409. amsId: 255,
  5410. slotId: slotTrayId,
  5411. loadTrayId: extTrayId,
  5412. includeRfid: false,
  5413. })}
  5414. configureSlot={{
  5415. enabled: hasPermission('printers:control'),
  5416. onConfigure: () => setConfigureSlotModal({
  5417. amsId: 255,
  5418. trayId: slotTrayId,
  5419. trayCount: 1,
  5420. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5421. }),
  5422. }}
  5423. onAssignSpool={() => setAssignSpoolModal({
  5424. printerId: printer.id,
  5425. amsId: 255,
  5426. trayId: slotTrayId,
  5427. trayInfo: {
  5428. type: '',
  5429. material: undefined,
  5430. profile: '',
  5431. color: '',
  5432. location: `External Slot ${slotTrayId + 1}`,
  5433. },
  5434. })}
  5435. >
  5436. {extSlotContent}
  5437. </EmptySlotHoverCard>
  5438. )}
  5439. </div>
  5440. );
  5441. })}
  5442. </div>
  5443. </div>
  5444. )}
  5445. </div>
  5446. </div>
  5447. );
  5448. })()}
  5449. </>
  5450. )}
  5451. {/* Bottom block (power row + action bar). Wrapped together so the
  5452. power row hugs the action bar at the card bottom instead of
  5453. floating up when there's less filament content above. */}
  5454. {viewMode === 'expanded' && (
  5455. <div className="mt-auto">
  5456. {smartPlug && (
  5457. <div className="pt-3">
  5458. <div className="flex items-center gap-2 mb-2">
  5459. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  5460. {t('printers.power', 'Power')}
  5461. </span>
  5462. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5463. </div>
  5464. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5465. {/* Plug name + current power */}
  5466. <div className="flex items-center gap-2 min-w-0 pl-1">
  5467. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  5468. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5469. <span
  5470. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[10px] font-medium flex-shrink-0"
  5471. title={t('smartPlugs.power')}
  5472. >
  5473. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5474. </span>
  5475. </div>
  5476. {/* Spacer */}
  5477. <div className="flex-1" />
  5478. <div className="flex items-center gap-2">
  5479. {/* Auto-off */}
  5480. <button
  5481. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5482. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5483. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5484. 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 ${
  5485. !hasPermission('smart_plugs:control')
  5486. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5487. : smartPlug.auto_off || smartPlug.auto_off_executed
  5488. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5489. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5490. }`}
  5491. >
  5492. <Clock className="w-4 h-4" />
  5493. </button>
  5494. <button
  5495. onClick={() => {
  5496. if (plugStatus?.state === 'ON') {
  5497. setShowPowerOffConfirm(true);
  5498. } else {
  5499. setShowPowerOnConfirm(true);
  5500. }
  5501. }}
  5502. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5503. 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 ${
  5504. !hasPermission('smart_plugs:control')
  5505. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5506. : plugStatus?.state === 'ON'
  5507. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5508. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5509. }`}
  5510. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5511. >
  5512. <Zap className="w-4 h-4" />
  5513. </button>
  5514. </div>
  5515. </div>
  5516. {/* HA entity buttons row */}
  5517. {scriptPlugs && scriptPlugs.length > 0 && (
  5518. <div className="flex items-center gap-2 mt-2">
  5519. <Home className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
  5520. <span className="text-xs text-bambu-gray">HA:</span>
  5521. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5522. <div className="flex flex-wrap gap-1">
  5523. {scriptPlugs.map(script => {
  5524. const isScript = script.ha_entity_id?.startsWith('script.');
  5525. return (
  5526. <button
  5527. key={script.id}
  5528. onClick={() => {
  5529. if (isScript) {
  5530. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5531. } else {
  5532. setHaToggleConfirm(script);
  5533. }
  5534. }}
  5535. disabled={runScriptMutation.isPending}
  5536. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5537. 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"
  5538. >
  5539. <Play className="w-2.5 h-2.5" />
  5540. {script.name}
  5541. </button>
  5542. );
  5543. })}
  5544. </div>
  5545. </div>
  5546. )}
  5547. </div>
  5548. )}
  5549. {/* Connection Info & Actions */}
  5550. <div className="pt-4">
  5551. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5552. <div className="flex items-center justify-between gap-2">
  5553. {printerActionsMenu}
  5554. <div className="flex items-center justify-end gap-2 flex-wrap">
  5555. {/* Camera Button */}
  5556. <Button
  5557. variant="secondary"
  5558. size="sm"
  5559. onClick={() => {
  5560. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5561. onOpenEmbeddedCamera(printer.id, printer.name);
  5562. } else {
  5563. // Use saved window state or defaults
  5564. const saved = localStorage.getItem('cameraWindowState');
  5565. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5566. const features = [
  5567. `width=${state.width}`,
  5568. `height=${state.height}`,
  5569. state.left !== undefined ? `left=${state.left}` : '',
  5570. state.top !== undefined ? `top=${state.top}` : '',
  5571. // No `noopener`: same-origin popup needs opener so the browser
  5572. // copies sessionStorage (auth token) into the new window.
  5573. 'menubar=no,toolbar=no,location=no,status=no',
  5574. ].filter(Boolean).join(',');
  5575. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5576. }
  5577. }}
  5578. disabled={!status?.connected || !hasPermission('camera:view')}
  5579. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5580. className={footerIconButtonClass}
  5581. >
  5582. <Video className="w-4 h-4" />
  5583. </Button>
  5584. <Button
  5585. variant="secondary"
  5586. size="sm"
  5587. onClick={() => setShowFileManager(true)}
  5588. disabled={!isConnected || !hasPermission('printers:files')}
  5589. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5590. className={footerIconButtonClass}
  5591. >
  5592. <HardDrive className="w-4 h-4" />
  5593. </Button>
  5594. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5595. <Button
  5596. size="sm"
  5597. onClick={() => setShowUploadForPrint(true)}
  5598. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  5599. title={
  5600. !hasPermission('library:upload')
  5601. ? t('fileManager.noPermissionUpload')
  5602. : !hasPermission('queue:create')
  5603. ? t('fileManager.noPermissionAddToQueue')
  5604. : t('common.print')
  5605. }
  5606. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5607. >
  5608. <PrinterIcon className="w-4 h-4" />
  5609. {t('common.print')}
  5610. </Button>
  5611. )}
  5612. </div>
  5613. </div>
  5614. </div>
  5615. </div>
  5616. )}
  5617. </CardContent>
  5618. {/* File Manager Modal */}
  5619. {showFileManager && (
  5620. <FileManagerModal
  5621. printerId={printer.id}
  5622. printerName={printer.name}
  5623. onClose={() => setShowFileManager(false)}
  5624. />
  5625. )}
  5626. {/* Upload for Print Modal */}
  5627. {showUploadForPrint && (
  5628. <FileUploadModal
  5629. folderId={null}
  5630. onClose={() => setShowUploadForPrint(false)}
  5631. onUploadComplete={() => {}}
  5632. autoUpload
  5633. accept=".gcode,.3mf"
  5634. validateFile={(file) => {
  5635. const lower = file.name.toLowerCase();
  5636. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5637. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5638. }
  5639. }}
  5640. onFileUploaded={(uploadedFile) => {
  5641. // Check printer compatibility if sliced_for_model is available in metadata
  5642. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5643. const printerModel = mapModelCode(printer.model);
  5644. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5645. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5646. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5647. }
  5648. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5649. }}
  5650. />
  5651. )}
  5652. {/* Print Modal (after upload) */}
  5653. {printAfterUpload && (
  5654. <PrintModal
  5655. mode="create"
  5656. libraryFileId={printAfterUpload.id}
  5657. archiveName={printAfterUpload.filename}
  5658. initialSelectedPrinterIds={[printer.id]}
  5659. onClose={() => setPrintAfterUpload(null)}
  5660. onSuccess={() => setPrintAfterUpload(null)}
  5661. cleanupLibraryAfterDispatch
  5662. />
  5663. )}
  5664. {/* MQTT Debug Modal */}
  5665. {showMQTTDebug && (
  5666. <MQTTDebugModal
  5667. printerId={printer.id}
  5668. printerName={printer.name}
  5669. onClose={() => setShowMQTTDebug(false)}
  5670. />
  5671. )}
  5672. {showDiagnostic && (
  5673. <ConnectionDiagnosticModal
  5674. printerId={printer.id}
  5675. printerName={printer.name}
  5676. onClose={() => setShowDiagnostic(false)}
  5677. />
  5678. )}
  5679. {showPrinterInfo && (
  5680. <PrinterInfoModal
  5681. printer={printer}
  5682. status={status}
  5683. totalPrintHours={maintenanceInfo?.total_print_hours}
  5684. onClose={closePrinterInfo}
  5685. />
  5686. )}
  5687. {/* Plate Check Result Modal */}
  5688. {plateCheckResult && (
  5689. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5690. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5691. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5692. <div className="flex items-center gap-2">
  5693. {plateCheckResult.needs_calibration ? (
  5694. <ScanSearch className="w-5 h-5 text-blue-500" />
  5695. ) : plateCheckResult.is_empty ? (
  5696. <CheckCircle className="w-5 h-5 text-green-500" />
  5697. ) : (
  5698. <XCircle className="w-5 h-5 text-yellow-500" />
  5699. )}
  5700. <h2 className="text-lg font-semibold text-white">
  5701. Build Plate Check
  5702. </h2>
  5703. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5704. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5705. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5706. </span>
  5707. )}
  5708. </div>
  5709. <button
  5710. onClick={() => closePlateCheckModal()}
  5711. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5712. >
  5713. <X className="w-5 h-5" />
  5714. </button>
  5715. </div>
  5716. <div className="p-4 space-y-4">
  5717. {plateCheckResult.needs_calibration ? (
  5718. <>
  5719. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  5720. <p className="font-medium text-blue-700 dark:text-blue-400">
  5721. {t('printers.plateDetection.calibrationRequired')}
  5722. </p>
  5723. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5724. </div>
  5725. <div className="text-sm text-bambu-gray space-y-2">
  5726. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5727. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5728. </div>
  5729. </>
  5730. ) : (
  5731. <>
  5732. <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'}`}>
  5733. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  5734. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  5735. </p>
  5736. <p className="text-sm text-bambu-gray mt-1">
  5737. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  5738. </p>
  5739. </div>
  5740. {plateCheckResult.debug_image_url && (
  5741. <div>
  5742. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  5743. <img
  5744. src={plateCheckResult.debug_image_url}
  5745. alt={t('printers.plateDetection.analysisPreview')}
  5746. className="w-full rounded-lg border border-bambu-dark-tertiary"
  5747. />
  5748. <p className="text-xs text-bambu-gray mt-2">
  5749. {t('printers.plateDetection.analysisLegend')}
  5750. </p>
  5751. </div>
  5752. )}
  5753. <p className="text-xs text-bambu-gray">
  5754. {plateCheckResult.message}
  5755. </p>
  5756. </>
  5757. )}
  5758. {/* Saved References Grid */}
  5759. {plateReferences && plateReferences.references.length > 0 && (
  5760. <div className="mt-4">
  5761. <div className="flex items-center gap-2 mb-2">
  5762. <p className="text-sm font-medium text-white shrink-0">
  5763. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  5764. </p>
  5765. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5766. </div>
  5767. <div className="grid grid-cols-5 gap-2">
  5768. {plateReferences.references.map((ref) => (
  5769. <div key={ref.index} className="relative group">
  5770. <img
  5771. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  5772. alt={ref.label || `Reference ${ref.index + 1}`}
  5773. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  5774. />
  5775. {/* Delete button */}
  5776. <button
  5777. onClick={() => handleDeleteRef(ref.index)}
  5778. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  5779. title={t('printers.plateDetection.deleteReference')}
  5780. >
  5781. <X className="w-3 h-3 text-white" />
  5782. </button>
  5783. {/* Label */}
  5784. {editingRefLabel?.index === ref.index ? (
  5785. <input
  5786. type="text"
  5787. value={editingRefLabel.label}
  5788. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  5789. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  5790. onKeyDown={(e) => {
  5791. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  5792. if (e.key === 'Escape') setEditingRefLabel(null);
  5793. }}
  5794. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  5795. autoFocus
  5796. placeholder={t('printers.plateDetection.labelPlaceholder')}
  5797. />
  5798. ) : (
  5799. <p
  5800. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  5801. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  5802. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  5803. >
  5804. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  5805. </p>
  5806. )}
  5807. {/* Timestamp */}
  5808. <p className="text-[10px] text-bambu-gray/60">
  5809. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  5810. </p>
  5811. </div>
  5812. ))}
  5813. </div>
  5814. </div>
  5815. )}
  5816. {/* ROI Editor */}
  5817. {!plateCheckResult.needs_calibration && (
  5818. <div className="mt-4">
  5819. <div className="flex items-center justify-between mb-2">
  5820. <div className="flex min-w-0 flex-1 items-center gap-2">
  5821. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  5822. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5823. </div>
  5824. {!editingRoi ? (
  5825. <Button
  5826. variant="ghost"
  5827. size="sm"
  5828. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  5829. >
  5830. <Pencil className="w-3 h-3 mr-1" />
  5831. {t('common.edit')}
  5832. </Button>
  5833. ) : (
  5834. <div className="flex gap-1">
  5835. <Button
  5836. variant="ghost"
  5837. size="sm"
  5838. onClick={() => setEditingRoi(null)}
  5839. disabled={isSavingRoi}
  5840. >
  5841. {t('common.cancel')}
  5842. </Button>
  5843. <Button
  5844. size="sm"
  5845. onClick={handleSaveRoi}
  5846. disabled={isSavingRoi}
  5847. >
  5848. {isSavingRoi ? <Loader2 className="w-3 h-3 animate-spin" /> : t('common.save')}
  5849. </Button>
  5850. </div>
  5851. )}
  5852. </div>
  5853. {editingRoi ? (
  5854. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  5855. <div className="grid grid-cols-2 gap-3">
  5856. <div>
  5857. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  5858. <input
  5859. type="range"
  5860. min="0"
  5861. max="0.9"
  5862. step="0.01"
  5863. value={editingRoi.x}
  5864. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  5865. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5866. />
  5867. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  5868. </div>
  5869. <div>
  5870. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  5871. <input
  5872. type="range"
  5873. min="0"
  5874. max="0.9"
  5875. step="0.01"
  5876. value={editingRoi.y}
  5877. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  5878. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5879. />
  5880. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  5881. </div>
  5882. <div>
  5883. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  5884. <input
  5885. type="range"
  5886. min="0.1"
  5887. max="1"
  5888. step="0.01"
  5889. value={editingRoi.w}
  5890. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  5891. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5892. />
  5893. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  5894. </div>
  5895. <div>
  5896. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  5897. <input
  5898. type="range"
  5899. min="0.1"
  5900. max="1"
  5901. step="0.01"
  5902. value={editingRoi.h}
  5903. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  5904. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  5905. />
  5906. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  5907. </div>
  5908. </div>
  5909. <p className="text-xs text-bambu-gray">
  5910. {t('printers.roi.instruction')}
  5911. </p>
  5912. </div>
  5913. ) : (
  5914. <p className="text-xs text-bambu-gray">
  5915. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  5916. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  5917. </p>
  5918. )}
  5919. </div>
  5920. )}
  5921. </div>
  5922. <div className="flex justify-end gap-2 p-4">
  5923. {plateCheckResult.needs_calibration ? (
  5924. <>
  5925. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  5926. {t('common.cancel')}
  5927. </Button>
  5928. <Button
  5929. onClick={() => handleCalibratePlate()}
  5930. disabled={isCalibrating}
  5931. >
  5932. {isCalibrating ? (
  5933. <>
  5934. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  5935. Calibrating...
  5936. </>
  5937. ) : (
  5938. 'Calibrate Empty Plate'
  5939. )}
  5940. </Button>
  5941. </>
  5942. ) : (
  5943. <>
  5944. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  5945. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  5946. </Button>
  5947. <Button onClick={() => closePlateCheckModal()}>
  5948. Close
  5949. </Button>
  5950. </>
  5951. )}
  5952. </div>
  5953. </div>
  5954. </div>
  5955. )}
  5956. {/* Power On Confirmation */}
  5957. {showPowerOnConfirm && smartPlug && (
  5958. <ConfirmModal
  5959. title={t('printers.confirm.powerOnTitle')}
  5960. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  5961. confirmText={t('printers.confirm.powerOnButton')}
  5962. variant="default"
  5963. onConfirm={() => {
  5964. powerControlMutation.mutate('on');
  5965. setShowPowerOnConfirm(false);
  5966. }}
  5967. onCancel={() => setShowPowerOnConfirm(false)}
  5968. />
  5969. )}
  5970. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  5971. disconnects MQTT, which stops progress tracking + completion
  5972. notifications for the in-flight job. Idle / FINISH / FAILED states
  5973. skip this dialog and toggle directly. */}
  5974. {confirmMaintenanceEnter && (
  5975. <ConfirmModal
  5976. title={t('printers.maintenance.confirmMidPrintTitle')}
  5977. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  5978. confirmText={t('printers.maintenance.menuEnter')}
  5979. variant="danger"
  5980. onConfirm={() => {
  5981. maintenanceMutation.mutate(false);
  5982. setConfirmMaintenanceEnter(false);
  5983. }}
  5984. onCancel={() => setConfirmMaintenanceEnter(false)}
  5985. />
  5986. )}
  5987. {/* Power Off Confirmation */}
  5988. {showPowerOffConfirm && smartPlug && (
  5989. <ConfirmModal
  5990. title={t('printers.confirm.powerOffTitle')}
  5991. message={
  5992. status?.state === 'RUNNING'
  5993. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  5994. : t('printers.confirm.powerOffMessage', { name: printer.name })
  5995. }
  5996. confirmText={t('printers.confirm.powerOffButton')}
  5997. variant="danger"
  5998. onConfirm={() => {
  5999. powerControlMutation.mutate('off');
  6000. setShowPowerOffConfirm(false);
  6001. }}
  6002. onCancel={() => setShowPowerOffConfirm(false)}
  6003. />
  6004. )}
  6005. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6006. {haToggleConfirm && (
  6007. <ConfirmModal
  6008. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6009. message={
  6010. status?.state === 'RUNNING'
  6011. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6012. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6013. }
  6014. confirmText={t('printers.confirm.haToggleButton')}
  6015. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6016. onConfirm={() => {
  6017. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6018. setHaToggleConfirm(null);
  6019. }}
  6020. onCancel={() => setHaToggleConfirm(null)}
  6021. />
  6022. )}
  6023. {/* Stop Print Confirmation */}
  6024. {showStopConfirm && (
  6025. <ConfirmModal
  6026. title={t('printers.confirm.stopTitle')}
  6027. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6028. confirmText={t('printers.confirm.stopButton')}
  6029. variant="danger"
  6030. onConfirm={() => {
  6031. stopPrintMutation.mutate();
  6032. setShowStopConfirm(false);
  6033. }}
  6034. onCancel={() => setShowStopConfirm(false)}
  6035. />
  6036. )}
  6037. {/* Pause Print Confirmation */}
  6038. {showPauseConfirm && (
  6039. <ConfirmModal
  6040. title={t('printers.confirm.pauseTitle')}
  6041. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6042. confirmText={t('printers.confirm.pauseButton')}
  6043. variant="default"
  6044. onConfirm={() => {
  6045. pausePrintMutation.mutate();
  6046. setShowPauseConfirm(false);
  6047. }}
  6048. onCancel={() => setShowPauseConfirm(false)}
  6049. />
  6050. )}
  6051. {/* Resume Print Confirmation */}
  6052. {showResumeConfirm && (
  6053. <ConfirmModal
  6054. title={t('printers.confirm.resumeTitle')}
  6055. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6056. confirmText={t('printers.confirm.resumeButton')}
  6057. variant="default"
  6058. onConfirm={() => {
  6059. resumePrintMutation.mutate();
  6060. setShowResumeConfirm(false);
  6061. }}
  6062. onCancel={() => setShowResumeConfirm(false)}
  6063. />
  6064. )}
  6065. {/* Skip Objects Modal */}
  6066. <SkipObjectsModal
  6067. printerId={printer.id}
  6068. isOpen={showSkipObjectsModal}
  6069. onClose={() => setShowSkipObjectsModal(false)}
  6070. />
  6071. {/* HMS Error Modal */}
  6072. {showHMSModal && (
  6073. <HMSErrorModal
  6074. printerName={printer.name}
  6075. errors={status?.hms_errors || []}
  6076. onClose={() => setShowHMSModal(false)}
  6077. printerId={printer.id}
  6078. hasPermission={hasPermission}
  6079. runoutGuidance={runoutGuidance}
  6080. />
  6081. )}
  6082. {/* AI failure detection modal (#1546) */}
  6083. {showAiModal && (
  6084. <AiDetectionModal
  6085. printerName={printer.name}
  6086. detection={aiDetection}
  6087. lastError={aiLastError}
  6088. onClose={() => setShowAiModal(false)}
  6089. />
  6090. )}
  6091. {/* AMS Filament Backup status / control modal (#1762) */}
  6092. {amsBackupModalOpen && status && (
  6093. <AmsBackupModal
  6094. isOpen={amsBackupModalOpen}
  6095. state={status.ams_filament_backup}
  6096. amsUnits={status.ams}
  6097. amsExtruderMap={status.ams_extruder_map}
  6098. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6099. canToggle={hasPermission('printers:control')}
  6100. pending={setAmsBackupMutation.isPending}
  6101. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6102. onClose={() => setAmsBackupModalOpen(false)}
  6103. />
  6104. )}
  6105. {/* AMS History Modal */}
  6106. {amsHistoryModal && (
  6107. <AMSHistoryModal
  6108. isOpen={!!amsHistoryModal}
  6109. onClose={() => setAmsHistoryModal(null)}
  6110. printerId={printer.id}
  6111. printerName={printer.name}
  6112. amsId={amsHistoryModal.amsId}
  6113. amsLabel={amsHistoryModal.amsLabel}
  6114. initialMode={amsHistoryModal.mode}
  6115. thresholds={amsThresholds}
  6116. />
  6117. )}
  6118. {/* Heater History Modal (nozzle / bed / chamber) */}
  6119. {heaterHistoryModal && (
  6120. <HeaterHistoryModal
  6121. isOpen={!!heaterHistoryModal}
  6122. onClose={() => setHeaterHistoryModal(null)}
  6123. printerId={printer.id}
  6124. printerName={printer.name}
  6125. initialKind={heaterHistoryModal.initialKind}
  6126. availableKinds={heaterHistoryModal.availableKinds}
  6127. />
  6128. )}
  6129. {/* Link Spool Modal */}
  6130. {linkSpoolModal && (
  6131. <LinkSpoolModal
  6132. isOpen={!!linkSpoolModal}
  6133. onClose={() => setLinkSpoolModal(null)}
  6134. tagUid={linkSpoolModal.tagUid}
  6135. trayUuid={linkSpoolModal.trayUuid}
  6136. printerId={linkSpoolModal.printerId}
  6137. amsId={linkSpoolModal.amsId}
  6138. trayId={linkSpoolModal.trayId}
  6139. />
  6140. )}
  6141. {/* Assign Spool Modal */}
  6142. {assignSpoolModal && (
  6143. <AssignSpoolModal
  6144. isOpen={!!assignSpoolModal}
  6145. onClose={() => setAssignSpoolModal(null)}
  6146. printerId={assignSpoolModal.printerId}
  6147. amsId={assignSpoolModal.amsId}
  6148. trayId={assignSpoolModal.trayId}
  6149. trayInfo={assignSpoolModal.trayInfo}
  6150. spoolmanEnabled={!!spoolmanEnabled}
  6151. />
  6152. )}
  6153. {/* Configure AMS Slot Modal */}
  6154. {configureSlotModal && (
  6155. <ConfigureAmsSlotModal
  6156. isOpen={!!configureSlotModal}
  6157. onClose={() => setConfigureSlotModal(null)}
  6158. printerId={printer.id}
  6159. slotInfo={configureSlotModal}
  6160. printerModel={mapModelCode(printer.model) || undefined}
  6161. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6162. onSuccess={() => {
  6163. // Refresh slot presets to show updated profile name
  6164. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6165. // Printer status will update automatically via WebSocket when AMS data changes
  6166. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6167. }}
  6168. />
  6169. )}
  6170. {/* Edit Printer Modal */}
  6171. {showEditModal && (
  6172. <EditPrinterModal
  6173. printer={printer}
  6174. onClose={() => setShowEditModal(false)}
  6175. />
  6176. )}
  6177. {/* Firmware Update Modal */}
  6178. {showFirmwareModal && firmwareInfo && (
  6179. <FirmwareUpdateModal
  6180. printer={printer}
  6181. firmwareInfo={firmwareInfo}
  6182. onClose={() => setShowFirmwareModal(false)}
  6183. />
  6184. )}
  6185. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6186. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6187. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6188. const sliderMin = 35;
  6189. const sliderMax = maxTemp + 10;
  6190. return (
  6191. <>
  6192. {/* Backdrop */}
  6193. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  6194. {/* Popover */}
  6195. <div
  6196. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6197. style={{
  6198. top: dryingPopoverPos.top,
  6199. left: dryingPopoverPos.left,
  6200. // Cap to the space between the popover's top and the bottom
  6201. // viewport margin (8px, matching computePopoverPosition's
  6202. // margin). When the popover is taller than that space — short
  6203. // viewport, landscape phone, zoomed-in — the body scrolls and
  6204. // the footer stays pinned, so the Start button is always
  6205. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6206. // Safari's bottom toolbar overlay doesn't clip the footer
  6207. // (#1669, iPhone 17 Safari).
  6208. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6209. }}
  6210. onClick={e => e.stopPropagation()}
  6211. >
  6212. {/* Header */}
  6213. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6214. <Flame className="w-3.5 h-3.5 text-bambu-green" />
  6215. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6216. </div>
  6217. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6218. {/* Body */}
  6219. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6220. {/* Filament type select */}
  6221. <div>
  6222. <label className="text-[10px] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6223. <ToolbarDropdown
  6224. value={dryingFilament}
  6225. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6226. onChange={fil => {
  6227. setDryingFilament(fil);
  6228. const preset = dryingPresets[fil];
  6229. if (preset) {
  6230. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6231. setDryingTemp(preset[key]);
  6232. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6233. }
  6234. }}
  6235. fullWidth
  6236. />
  6237. </div>
  6238. {/* Temperature */}
  6239. <div>
  6240. <div className="flex items-center justify-between mb-1">
  6241. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6242. <div className="flex items-center gap-1">
  6243. <input
  6244. type="number"
  6245. min={45}
  6246. max={maxTemp}
  6247. value={dryingTemp}
  6248. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6249. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6250. />
  6251. <span className="text-[10px] text-bambu-gray">°C</span>
  6252. </div>
  6253. </div>
  6254. <input
  6255. type="range"
  6256. min={sliderMin}
  6257. max={sliderMax}
  6258. value={dryingTemp}
  6259. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6260. className="w-full h-1 accent-bambu-green cursor-pointer"
  6261. />
  6262. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6263. <span>45°C</span>
  6264. <span>{maxTemp}°C</span>
  6265. </div>
  6266. </div>
  6267. {/* Duration */}
  6268. <div>
  6269. <div className="flex items-center justify-between mb-1">
  6270. <label className="text-[10px] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6271. <div className="flex items-center gap-1">
  6272. <input
  6273. type="number"
  6274. min={1}
  6275. max={24}
  6276. value={dryingDuration}
  6277. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6278. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[11px] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6279. />
  6280. <span className="text-[10px] text-bambu-gray">{t('printers.drying.hours')}</span>
  6281. </div>
  6282. </div>
  6283. <input
  6284. type="range"
  6285. min={1}
  6286. max={24}
  6287. value={dryingDuration}
  6288. onChange={e => setDryingDuration(Number(e.target.value))}
  6289. className="w-full h-1 accent-bambu-green cursor-pointer"
  6290. />
  6291. <div className="flex justify-between text-[9px] text-bambu-gray/50 mt-0.5">
  6292. <span>1h</span>
  6293. <span>24h</span>
  6294. </div>
  6295. </div>
  6296. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6297. filament threaded out into the feed tube. The whole AMS
  6298. rotates as one mechanism (all 4 spools turn together), so a
  6299. single loaded slot locks the entire unit. Bambu per-tray
  6300. `state`: 9 = empty, 10 = spool present but not loaded
  6301. (rotation possible), 11 = loaded into tube (rotation impossible).
  6302. Catches both mid-print (active feed) AND idle-with-threaded-
  6303. filament — the H2D's post-print state leaves filament in the
  6304. tube but tray_now resets to 255, which a tray_now-only check
  6305. would silently miss. */}
  6306. {(() => {
  6307. const targetAms = dryingPopoverAmsId !== null
  6308. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6309. : undefined;
  6310. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6311. tray => tray.state === 11,
  6312. );
  6313. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6314. return (
  6315. <button
  6316. type="button"
  6317. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6318. aria-pressed={rotateChecked}
  6319. disabled={trayLoadedInThisAms}
  6320. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6321. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6322. rotateChecked
  6323. ? 'bg-bambu-green border-bambu-green text-white'
  6324. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6325. }`}
  6326. >
  6327. {t('printers.drying.rotateTray')}
  6328. </button>
  6329. );
  6330. })()}
  6331. </div>
  6332. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6333. {/* Footer */}
  6334. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6335. <button
  6336. onClick={() => {
  6337. if (dryingPopoverAmsId !== null) {
  6338. // Clamp rotateTray off when any tray in this AMS is loaded into
  6339. // the tube — the rotate UI is disabled there, but the state may
  6340. // linger as `true` from a previous AMS, or a print may have
  6341. // started while the popover was open. Without this clamp the
  6342. // Start payload would carry rotate_tray=true and firmware would
  6343. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  6344. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  6345. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6346. tray => tray.state === 11,
  6347. );
  6348. startDryingMutation.mutate({
  6349. amsId: dryingPopoverAmsId,
  6350. temp: dryingTemp,
  6351. duration: dryingDuration,
  6352. filament: dryingFilament,
  6353. rotateTray: dryingRotateTray && !trayLoadedInThisAms,
  6354. });
  6355. }
  6356. }}
  6357. disabled={startDryingMutation.isPending}
  6358. data-testid="drying-start-confirm"
  6359. 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"
  6360. >
  6361. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6362. </button>
  6363. </div>
  6364. </div>
  6365. </>
  6366. );
  6367. })()}
  6368. </Card>
  6369. );
  6370. }
  6371. export function AddPrinterModal({
  6372. onClose,
  6373. onAdd,
  6374. existingSerials,
  6375. }: {
  6376. onClose: () => void;
  6377. onAdd: (data: PrinterCreate) => void;
  6378. existingSerials: string[];
  6379. }) {
  6380. const { t } = useTranslation();
  6381. const [form, setForm] = useState<PrinterCreate>({
  6382. name: '',
  6383. serial_number: '',
  6384. ip_address: '',
  6385. access_code: '',
  6386. model: '',
  6387. location: '',
  6388. auto_archive: true,
  6389. });
  6390. // Discovery state
  6391. const [discovering, setDiscovering] = useState(false);
  6392. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6393. const [discoveryError, setDiscoveryError] = useState('');
  6394. const [hasScanned, setHasScanned] = useState(false);
  6395. const [isDocker, setIsDocker] = useState(false);
  6396. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6397. const [subnet, setSubnet] = useState('');
  6398. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6399. // text input so users can scan a subnet Bambuddy isn't directly on
  6400. // (printer behind a router on a different L3 segment — SSDP multicast
  6401. // won't cross that boundary, only an active unicast scan will). #1564
  6402. const [customSubnet, setCustomSubnet] = useState('');
  6403. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6404. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6405. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6406. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6407. // (not block) when checks fail, so the user doesn't add a printer that
  6408. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6409. // failed result awaiting an explicit "save anyway".
  6410. const [checkingSave, setCheckingSave] = useState(false);
  6411. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6412. // Fetch discovery info on mount + restore the last custom CIDR the user
  6413. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6414. // time they open this modal).
  6415. useEffect(() => {
  6416. discoveryApi.getInfo().then(info => {
  6417. setIsDocker(info.is_docker);
  6418. if (info.subnets.length > 0) {
  6419. setDetectedSubnets(info.subnets);
  6420. setSubnet(info.subnets[0]);
  6421. }
  6422. }).catch(() => {
  6423. // Ignore errors, assume not Docker
  6424. });
  6425. try {
  6426. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6427. if (saved) setCustomSubnet(saved);
  6428. } catch {
  6429. // localStorage unavailable (private mode, quota); recall is opportunistic
  6430. }
  6431. }, []);
  6432. // Filter out already-added printers
  6433. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6434. const handleAddSubmit = async (e: React.FormEvent) => {
  6435. e.preventDefault();
  6436. setCheckingSave(true);
  6437. try {
  6438. const result = await api.diagnoseConnection({
  6439. ip_address: form.ip_address.trim(),
  6440. serial_number: form.serial_number.trim() || undefined,
  6441. access_code: form.access_code || undefined,
  6442. });
  6443. if (result.checks.some((c) => c.status === 'fail')) {
  6444. setSaveWarning(result);
  6445. return;
  6446. }
  6447. } catch {
  6448. // Diagnostic infrastructure failed — never block the save on it.
  6449. } finally {
  6450. setCheckingSave(false);
  6451. }
  6452. onAdd(form);
  6453. };
  6454. const startDiscovery = async () => {
  6455. setDiscoveryError('');
  6456. setDiscovered([]);
  6457. setDiscovering(true);
  6458. setHasScanned(false);
  6459. setScanProgress({ scanned: 0, total: 0 });
  6460. // Native installs fall back to subnet scanning when the user picks
  6461. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6462. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6463. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6464. const wantsSubnetScan = isDocker || useCustomSubnet;
  6465. if (wantsSubnetScan && useCustomSubnet) {
  6466. try {
  6467. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6468. } catch {
  6469. // localStorage write best-effort; user just retypes next time
  6470. }
  6471. }
  6472. try {
  6473. if (wantsSubnetScan) {
  6474. await discoveryApi.startSubnetScan(scanCidr);
  6475. // Poll for scan status and results
  6476. const pollInterval = setInterval(async () => {
  6477. try {
  6478. const status = await discoveryApi.getScanStatus();
  6479. setScanProgress({ scanned: status.scanned, total: status.total });
  6480. const printers = await discoveryApi.getDiscoveredPrinters();
  6481. setDiscovered(printers);
  6482. if (!status.running) {
  6483. clearInterval(pollInterval);
  6484. setDiscovering(false);
  6485. setHasScanned(true);
  6486. }
  6487. } catch (e) {
  6488. console.error('Failed to get scan status:', e);
  6489. }
  6490. }, 500);
  6491. } else {
  6492. // Use SSDP discovery for native installs
  6493. await discoveryApi.startDiscovery(10);
  6494. // Poll for discovered printers every second
  6495. const pollInterval = setInterval(async () => {
  6496. try {
  6497. const printers = await discoveryApi.getDiscoveredPrinters();
  6498. setDiscovered(printers);
  6499. } catch (e) {
  6500. console.error('Failed to get discovered printers:', e);
  6501. }
  6502. }, 1000);
  6503. // Stop after 10 seconds
  6504. setTimeout(async () => {
  6505. clearInterval(pollInterval);
  6506. try {
  6507. await discoveryApi.stopDiscovery();
  6508. } catch {
  6509. // Ignore stop errors
  6510. }
  6511. setDiscovering(false);
  6512. setHasScanned(true);
  6513. // Final fetch
  6514. try {
  6515. const printers = await discoveryApi.getDiscoveredPrinters();
  6516. setDiscovered(printers);
  6517. } catch (e) {
  6518. console.error('Failed to get final discovered printers:', e);
  6519. }
  6520. }, 10000);
  6521. }
  6522. } catch (e) {
  6523. console.error('Failed to start discovery:', e);
  6524. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6525. setDiscovering(false);
  6526. setHasScanned(true);
  6527. }
  6528. };
  6529. // Reuse module-level mapModelCode
  6530. const selectPrinter = (printer: DiscoveredPrinter) => {
  6531. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6532. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6533. setForm({
  6534. ...form,
  6535. name: printer.name || '',
  6536. serial_number: serialNumber,
  6537. ip_address: printer.ip_address,
  6538. model: mapModelCode(printer.model),
  6539. });
  6540. // Clear discovery results after selection
  6541. setDiscovered([]);
  6542. };
  6543. // Cleanup discovery on unmount
  6544. useEffect(() => {
  6545. return () => {
  6546. discoveryApi.stopDiscovery().catch(() => {});
  6547. discoveryApi.stopSubnetScan().catch(() => {});
  6548. };
  6549. }, []);
  6550. // Close on Escape key
  6551. useEffect(() => {
  6552. const handleKeyDown = (e: KeyboardEvent) => {
  6553. if (e.key === 'Escape') onClose();
  6554. };
  6555. window.addEventListener('keydown', handleKeyDown);
  6556. return () => window.removeEventListener('keydown', handleKeyDown);
  6557. }, [onClose]);
  6558. return (
  6559. <>
  6560. <div
  6561. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6562. onClick={onClose}
  6563. >
  6564. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6565. <CardContent>
  6566. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6567. {/* Discovery Section */}
  6568. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6569. {/* Subnet picker — always visible. The dropdown lists detected
  6570. interface subnets and a "Custom..." sentinel that reveals
  6571. a CIDR text input for printers on a different L3 segment
  6572. (router, VLAN, etc.). #1564 */}
  6573. <div className="mb-3">
  6574. <label className="block text-sm text-bambu-gray mb-1">
  6575. {t('printers.discovery.subnetToScan')}
  6576. </label>
  6577. {detectedSubnets.length > 0 ? (
  6578. <select
  6579. 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"
  6580. value={useCustomSubnet ? '__custom__' : subnet}
  6581. onChange={(e) => {
  6582. if (e.target.value === '__custom__') {
  6583. setUseCustomSubnet(true);
  6584. } else {
  6585. setUseCustomSubnet(false);
  6586. setSubnet(e.target.value);
  6587. }
  6588. }}
  6589. disabled={discovering}
  6590. >
  6591. {detectedSubnets.map(s => (
  6592. <option key={s} value={s}>{s}</option>
  6593. ))}
  6594. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6595. </select>
  6596. ) : (
  6597. <input
  6598. type="text"
  6599. 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"
  6600. value={subnet}
  6601. onChange={(e) => setSubnet(e.target.value)}
  6602. placeholder="192.168.1.0/24"
  6603. disabled={discovering}
  6604. />
  6605. )}
  6606. {useCustomSubnet && (
  6607. <input
  6608. type="text"
  6609. aria-label={t('printers.discovery.customSubnetLabel')}
  6610. 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"
  6611. value={customSubnet}
  6612. onChange={(e) => setCustomSubnet(e.target.value)}
  6613. placeholder="10.1.1.0/24"
  6614. disabled={discovering}
  6615. />
  6616. )}
  6617. <p className="mt-1 text-xs text-bambu-gray">
  6618. {isDocker
  6619. ? t('printers.discovery.dockerNote')
  6620. : t('printers.discovery.customSubnetNote')}
  6621. </p>
  6622. </div>
  6623. <Button
  6624. type="button"
  6625. variant="secondary"
  6626. onClick={startDiscovery}
  6627. disabled={discovering}
  6628. className="w-full"
  6629. >
  6630. {discovering ? (
  6631. <>
  6632. <Loader2 className="w-4 h-4 animate-spin" />
  6633. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6634. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6635. : t('printers.discovery.scanning')}
  6636. </>
  6637. ) : (
  6638. <>
  6639. <Search className="w-4 h-4" />
  6640. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6641. </>
  6642. )}
  6643. </Button>
  6644. {discoveryError && (
  6645. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  6646. )}
  6647. {newPrinters.length > 0 && (
  6648. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6649. {newPrinters.map((printer) => (
  6650. <div
  6651. key={printer.serial}
  6652. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6653. onClick={() => selectPrinter(printer)}
  6654. >
  6655. <div className="min-w-0 flex-1">
  6656. <p className="font-medium text-white text-sm truncate">
  6657. {printer.name || printer.serial}
  6658. </p>
  6659. <p className="text-xs text-bambu-gray truncate">
  6660. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6661. {printer.serial.startsWith('unknown-') && (
  6662. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6663. )}
  6664. </p>
  6665. </div>
  6666. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6667. </div>
  6668. ))}
  6669. </div>
  6670. )}
  6671. {discovering && (
  6672. <p className="mt-2 text-sm text-bambu-gray text-center">
  6673. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6674. </p>
  6675. )}
  6676. {hasScanned && !discovering && discovered.length === 0 && (
  6677. <p className="mt-2 text-sm text-bambu-gray text-center">
  6678. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6679. </p>
  6680. )}
  6681. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6682. <p className="mt-2 text-sm text-bambu-gray text-center">
  6683. {t('printers.discovery.allConfigured')}
  6684. </p>
  6685. )}
  6686. </div>
  6687. <form onSubmit={handleAddSubmit} className="space-y-4">
  6688. <div>
  6689. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6690. <input
  6691. type="text"
  6692. required
  6693. 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"
  6694. value={form.name}
  6695. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6696. placeholder={t('printers.modal.myPrinter')}
  6697. />
  6698. </div>
  6699. <div>
  6700. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6701. <input
  6702. type="text"
  6703. required
  6704. 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])?)*)"
  6705. 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"
  6706. value={form.ip_address}
  6707. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6708. placeholder="192.168.1.100 or printer.local"
  6709. />
  6710. </div>
  6711. <div>
  6712. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6713. <input
  6714. type="text"
  6715. required
  6716. 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"
  6717. value={form.serial_number}
  6718. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6719. placeholder="01P00A000000000"
  6720. />
  6721. </div>
  6722. <div>
  6723. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6724. <input
  6725. type="password"
  6726. required
  6727. 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"
  6728. value={form.access_code}
  6729. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6730. placeholder={t('printers.modal.fromPrinterSettings')}
  6731. />
  6732. </div>
  6733. <div>
  6734. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  6735. <select
  6736. 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"
  6737. value={form.model || ''}
  6738. onChange={(e) => setForm({ ...form, model: e.target.value })}
  6739. >
  6740. <option value="">{t('printers.modal.selectModel')}</option>
  6741. <optgroup label="A1 Series">
  6742. <option value="A1">A1</option>
  6743. <option value="A1 Mini">A1 Mini</option>
  6744. </optgroup>
  6745. <optgroup label="A2 Series">
  6746. <option value="A2L">A2L</option>
  6747. </optgroup>
  6748. <optgroup label="H2 Series">
  6749. <option value="H2C">H2C</option>
  6750. <option value="H2D">H2D</option>
  6751. <option value="H2D Pro">H2D Pro</option>
  6752. <option value="H2S">H2S</option>
  6753. </optgroup>
  6754. <optgroup label="P Series">
  6755. <option value="P1P">P1P</option>
  6756. <option value="P1S">P1S</option>
  6757. <option value="P2S">P2S</option>
  6758. </optgroup>
  6759. <optgroup label="X1 Series">
  6760. <option value="X1">X1</option>
  6761. <option value="X1C">X1 Carbon</option>
  6762. <option value="X1E">X1E</option>
  6763. </optgroup>
  6764. <optgroup label="X2 Series">
  6765. <option value="X2D">X2D</option>
  6766. </optgroup>
  6767. </select>
  6768. </div>
  6769. <div>
  6770. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  6771. <input
  6772. type="text"
  6773. 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"
  6774. value={form.location || ''}
  6775. onChange={(e) => setForm({ ...form, location: e.target.value })}
  6776. placeholder={t('printers.modal.locationPlaceholder')}
  6777. />
  6778. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  6779. </div>
  6780. <div className="flex items-center gap-2">
  6781. <input
  6782. type="checkbox"
  6783. id="auto_archive"
  6784. checked={form.auto_archive}
  6785. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  6786. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  6787. />
  6788. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  6789. {t('printers.modal.autoArchiveLabel')}
  6790. </label>
  6791. </div>
  6792. <button
  6793. type="button"
  6794. onClick={() => setShowDiagnostic(true)}
  6795. disabled={!form.ip_address.trim()}
  6796. 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"
  6797. >
  6798. <Stethoscope className="w-4 h-4" />
  6799. {t('diagnostic.runButton')}
  6800. </button>
  6801. {saveWarning ? (
  6802. <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">
  6803. <div className="flex items-start gap-2">
  6804. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  6805. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  6806. </div>
  6807. <DiagnosticChecklist result={saveWarning} />
  6808. <div className="flex gap-3">
  6809. <Button
  6810. type="button"
  6811. variant="secondary"
  6812. onClick={() => setSaveWarning(null)}
  6813. className="flex-1"
  6814. >
  6815. {t('printers.addPreflight.back')}
  6816. </Button>
  6817. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  6818. {t('printers.addPreflight.saveAnyway')}
  6819. </Button>
  6820. </div>
  6821. </div>
  6822. ) : (
  6823. <div className="flex gap-3 pt-2">
  6824. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  6825. {t('common.cancel')}
  6826. </Button>
  6827. <Button type="submit" disabled={checkingSave} className="flex-1">
  6828. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  6829. </Button>
  6830. </div>
  6831. )}
  6832. </form>
  6833. </CardContent>
  6834. </Card>
  6835. </div>
  6836. {showDiagnostic && (
  6837. <ConnectionDiagnosticModal
  6838. connection={{
  6839. ip_address: form.ip_address.trim(),
  6840. serial_number: form.serial_number.trim() || undefined,
  6841. access_code: form.access_code || undefined,
  6842. }}
  6843. printerName={form.name || null}
  6844. onClose={() => setShowDiagnostic(false)}
  6845. />
  6846. )}
  6847. </>
  6848. );
  6849. }
  6850. function FirmwareUpdateModal({
  6851. printer,
  6852. firmwareInfo,
  6853. onClose,
  6854. }: {
  6855. printer: Printer;
  6856. firmwareInfo: FirmwareUpdateInfo;
  6857. onClose: () => void;
  6858. }) {
  6859. const { t } = useTranslation();
  6860. const queryClient = useQueryClient();
  6861. const { showToast } = useToast();
  6862. const { hasPermission } = useAuth();
  6863. const canUpdate = hasPermission('firmware:update');
  6864. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  6865. const [isUploading, setIsUploading] = useState(false);
  6866. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  6867. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  6868. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  6869. );
  6870. // Prepare check query — runs when a version is selected and user can update
  6871. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  6872. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  6873. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  6874. staleTime: 30000,
  6875. enabled: !!selectedVersion && canUpdate && !isUploading,
  6876. });
  6877. // Start upload mutation
  6878. const uploadMutation = useMutation({
  6879. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  6880. onSuccess: () => {
  6881. setIsUploading(true);
  6882. // Start polling for status
  6883. const interval = setInterval(async () => {
  6884. try {
  6885. const status = await firmwareApi.getUploadStatus(printer.id);
  6886. setUploadStatus(status);
  6887. if (status.status === 'complete' || status.status === 'error') {
  6888. clearInterval(interval);
  6889. setPollInterval(null);
  6890. setIsUploading(false);
  6891. if (status.status === 'complete') {
  6892. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  6893. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  6894. }
  6895. }
  6896. } catch {
  6897. // Ignore errors during polling
  6898. }
  6899. }, 2000);
  6900. setPollInterval(interval);
  6901. },
  6902. onError: (error: Error) => {
  6903. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  6904. setIsUploading(false);
  6905. },
  6906. });
  6907. // Cleanup on unmount
  6908. useEffect(() => {
  6909. return () => {
  6910. if (pollInterval) clearInterval(pollInterval);
  6911. };
  6912. }, [pollInterval]);
  6913. const handleStartUpload = () => {
  6914. setUploadStatus(null);
  6915. uploadMutation.mutate();
  6916. };
  6917. return (
  6918. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  6919. <Card className="w-full max-w-md mx-4">
  6920. <CardContent>
  6921. <div className="flex items-start gap-3 mb-4">
  6922. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  6923. {firmwareInfo.update_available
  6924. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  6925. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  6926. </div>
  6927. <div className="flex-1">
  6928. <h3 className="text-lg font-semibold text-white">
  6929. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  6930. </h3>
  6931. <p className="text-sm text-bambu-gray mt-1">
  6932. {printer.name}
  6933. </p>
  6934. </div>
  6935. </div>
  6936. {/* Version Info */}
  6937. {(() => {
  6938. const selectedEntry = selectedVersion
  6939. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  6940. : null;
  6941. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  6942. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  6943. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  6944. return (
  6945. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  6946. <div className="flex justify-between items-center text-sm">
  6947. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  6948. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  6949. {firmwareInfo.current_version || t('common.unknown')}
  6950. </span>
  6951. </div>
  6952. {showSecondLine && (
  6953. <div className="flex justify-between items-center text-sm mt-1">
  6954. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  6955. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  6956. </div>
  6957. )}
  6958. {displayNotes && (
  6959. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  6960. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  6961. {t('printers.firmwareModal.releaseNotes')}
  6962. </summary>
  6963. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  6964. {displayNotes}
  6965. </div>
  6966. </details>
  6967. )}
  6968. </div>
  6969. );
  6970. })()}
  6971. {/* Available versions list */}
  6972. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  6973. <div className="mb-4">
  6974. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  6975. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  6976. {firmwareInfo.available_versions.map((v) => {
  6977. const isCurrent = firmwareInfo.current_version === v.version;
  6978. const isSelected = selectedVersion === v.version;
  6979. const cmp = firmwareInfo.current_version
  6980. ? compareFwVersions(v.version, firmwareInfo.current_version)
  6981. : 0;
  6982. const relLabel = isCurrent
  6983. ? t('printers.firmwareModal.currentBadge')
  6984. : cmp > 0
  6985. ? t('printers.firmwareModal.newerBadge')
  6986. : t('printers.firmwareModal.olderBadge');
  6987. const relClass = isCurrent
  6988. ? 'text-bambu-gray'
  6989. : cmp > 0
  6990. ? 'text-orange-700 dark:text-orange-400'
  6991. : 'text-blue-700 dark:text-blue-400';
  6992. return (
  6993. <button
  6994. key={v.version}
  6995. type="button"
  6996. disabled={!v.file_available || !canUpdate || isCurrent}
  6997. onClick={() => setSelectedVersion(v.version)}
  6998. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  6999. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7000. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7001. >
  7002. <div className="flex items-center gap-2 min-w-0">
  7003. <span className="font-mono text-white">{v.version}</span>
  7004. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7005. </div>
  7006. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7007. isCurrent
  7008. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7009. : v.file_available
  7010. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7011. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7012. }`}>
  7013. {isCurrent
  7014. ? t('printers.firmwareModal.installed')
  7015. : v.file_available
  7016. ? t('printers.firmwareModal.usable')
  7017. : t('printers.firmwareModal.unavailable')}
  7018. </span>
  7019. </button>
  7020. );
  7021. })}
  7022. </div>
  7023. </div>
  7024. )}
  7025. {/* Status / Progress (only when a version is selected) */}
  7026. {!selectedVersion ? null : isPreparing ? (
  7027. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7028. <Loader2 className="w-4 h-4 animate-spin" />
  7029. {t('printers.firmwareModal.checkingPrereqs')}
  7030. </div>
  7031. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7032. <div className="mb-4">
  7033. {prepareInfo.can_proceed ? (
  7034. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7035. <Box className="w-4 h-4" />
  7036. {t('printers.firmwareModal.sdCardReady')}
  7037. </div>
  7038. ) : (
  7039. <div className="space-y-1">
  7040. {prepareInfo.errors.map((error, i) => (
  7041. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7042. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7043. {error}
  7044. </div>
  7045. ))}
  7046. </div>
  7047. )}
  7048. </div>
  7049. ) : null}
  7050. {/* Upload Progress */}
  7051. {(isUploading || uploadStatus) && uploadStatus && (
  7052. <div className="mb-4">
  7053. <div className="flex items-center justify-between text-sm mb-1">
  7054. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  7055. <span className="text-white">{uploadStatus.progress}%</span>
  7056. </div>
  7057. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  7058. <div
  7059. className={`h-2 rounded-full transition-all ${
  7060. uploadStatus.status === 'error' ? 'bg-status-error' :
  7061. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  7062. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  7063. style={{ width: `${uploadStatus.progress}%` }}
  7064. />
  7065. </div>
  7066. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  7067. {uploadStatus.error && (
  7068. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  7069. )}
  7070. </div>
  7071. )}
  7072. {/* Success Message */}
  7073. {uploadStatus?.status === 'complete' && (
  7074. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  7075. <p className="text-sm text-bambu-green font-medium mb-2">
  7076. {t('printers.firmwareModal.uploadedSuccess')}
  7077. </p>
  7078. <p className="text-xs text-bambu-gray">
  7079. {t('printers.firmwareModal.applyInstructions')}
  7080. </p>
  7081. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  7082. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  7083. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  7084. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  7085. <li>{t('printers.firmwareModal.step4')}</li>
  7086. </ol>
  7087. </div>
  7088. )}
  7089. {/* Buttons */}
  7090. <div className="flex gap-2 justify-end">
  7091. <Button variant="secondary" onClick={onClose}>
  7092. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  7093. </Button>
  7094. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  7095. <Button
  7096. onClick={handleStartUpload}
  7097. disabled={uploadMutation.isPending}
  7098. >
  7099. {uploadMutation.isPending ? (
  7100. <>
  7101. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  7102. {t('printers.firmwareModal.starting')}
  7103. </>
  7104. ) : (
  7105. <>
  7106. <Download className="w-4 h-4 mr-2" />
  7107. {t('printers.firmwareModal.uploadFirmware')}
  7108. </>
  7109. )}
  7110. </Button>
  7111. )}
  7112. </div>
  7113. </CardContent>
  7114. </Card>
  7115. </div>
  7116. );
  7117. }
  7118. function EditPrinterModal({
  7119. printer,
  7120. onClose,
  7121. }: {
  7122. printer: Printer;
  7123. onClose: () => void;
  7124. }) {
  7125. const { t } = useTranslation();
  7126. const queryClient = useQueryClient();
  7127. const { showToast } = useToast();
  7128. const [form, setForm] = useState({
  7129. name: printer.name,
  7130. ip_address: printer.ip_address,
  7131. access_code: '',
  7132. model: printer.model || '',
  7133. location: printer.location || '',
  7134. auto_archive: printer.auto_archive,
  7135. is_active: printer.is_active,
  7136. });
  7137. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7138. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7139. const [checkingSave, setCheckingSave] = useState(false);
  7140. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7141. const updateMutation = useMutation({
  7142. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7143. onSuccess: () => {
  7144. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7145. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7146. onClose();
  7147. },
  7148. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7149. });
  7150. // Close on Escape key
  7151. useEffect(() => {
  7152. const handleKeyDown = (e: KeyboardEvent) => {
  7153. if (e.key === 'Escape') onClose();
  7154. };
  7155. window.addEventListener('keydown', handleKeyDown);
  7156. return () => window.removeEventListener('keydown', handleKeyDown);
  7157. }, [onClose]);
  7158. const doSave = () => {
  7159. const data: Partial<PrinterCreate> = {
  7160. name: form.name,
  7161. ip_address: form.ip_address,
  7162. model: form.model || undefined,
  7163. location: form.location || undefined,
  7164. auto_archive: form.auto_archive,
  7165. is_active: form.is_active,
  7166. };
  7167. // Only include access_code if it was changed
  7168. if (form.access_code) {
  7169. data.access_code = form.access_code;
  7170. }
  7171. updateMutation.mutate(data);
  7172. };
  7173. const handleSubmit = async (e: React.FormEvent) => {
  7174. e.preventDefault();
  7175. setCheckingSave(true);
  7176. try {
  7177. const result = await api.diagnoseConnection({
  7178. ip_address: form.ip_address.trim(),
  7179. serial_number: printer.serial_number,
  7180. access_code: form.access_code || undefined,
  7181. });
  7182. if (result.checks.some((c) => c.status === 'fail')) {
  7183. setSaveWarning(result);
  7184. return;
  7185. }
  7186. } catch {
  7187. // Diagnostic infrastructure failed — never block the save on it.
  7188. } finally {
  7189. setCheckingSave(false);
  7190. }
  7191. doSave();
  7192. };
  7193. return (
  7194. <div
  7195. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7196. onClick={onClose}
  7197. >
  7198. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7199. <CardContent>
  7200. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7201. <form onSubmit={handleSubmit} className="space-y-4">
  7202. <div>
  7203. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7204. <input
  7205. type="text"
  7206. required
  7207. 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"
  7208. value={form.name}
  7209. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7210. placeholder={t('printers.modal.myPrinter')}
  7211. />
  7212. </div>
  7213. <div>
  7214. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7215. <input
  7216. type="text"
  7217. required
  7218. 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])?)*)"
  7219. 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"
  7220. value={form.ip_address}
  7221. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7222. placeholder="192.168.1.100 or printer.local"
  7223. />
  7224. </div>
  7225. <div>
  7226. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7227. <input
  7228. type="text"
  7229. disabled
  7230. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7231. value={printer.serial_number}
  7232. />
  7233. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7234. </div>
  7235. <div>
  7236. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7237. <input
  7238. type="password"
  7239. 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"
  7240. value={form.access_code}
  7241. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7242. placeholder={t('printers.accessCodePlaceholder')}
  7243. />
  7244. </div>
  7245. <div>
  7246. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7247. <select
  7248. 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"
  7249. value={form.model}
  7250. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7251. >
  7252. <option value="">{t('printers.modal.selectModel')}</option>
  7253. <optgroup label="A1 Series">
  7254. <option value="A1">A1</option>
  7255. <option value="A1 Mini">A1 Mini</option>
  7256. </optgroup>
  7257. <optgroup label="A2 Series">
  7258. <option value="A2L">A2L</option>
  7259. </optgroup>
  7260. <optgroup label="H2 Series">
  7261. <option value="H2C">H2C</option>
  7262. <option value="H2D">H2D</option>
  7263. <option value="H2D Pro">H2D Pro</option>
  7264. <option value="H2S">H2S</option>
  7265. </optgroup>
  7266. <optgroup label="P Series">
  7267. <option value="P1P">P1P</option>
  7268. <option value="P1S">P1S</option>
  7269. <option value="P2S">P2S</option>
  7270. </optgroup>
  7271. <optgroup label="X1 Series">
  7272. <option value="X1">X1</option>
  7273. <option value="X1C">X1 Carbon</option>
  7274. <option value="X1E">X1E</option>
  7275. </optgroup>
  7276. <optgroup label="X2 Series">
  7277. <option value="X2D">X2D</option>
  7278. </optgroup>
  7279. </select>
  7280. </div>
  7281. <div>
  7282. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7283. <input
  7284. type="text"
  7285. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  7286. value={form.location}
  7287. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7288. placeholder={t('printers.modal.locationPlaceholder')}
  7289. />
  7290. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7291. </div>
  7292. <div className="flex items-center gap-2">
  7293. <input
  7294. type="checkbox"
  7295. id="edit_auto_archive"
  7296. checked={form.auto_archive}
  7297. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7298. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7299. />
  7300. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7301. {t('printers.modal.autoArchiveLabel')}
  7302. </label>
  7303. </div>
  7304. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7305. is_active because the user-facing concept is "is this printer
  7306. in maintenance" not "is it active". */}
  7307. <div>
  7308. <div className="flex items-center gap-2">
  7309. <input
  7310. type="checkbox"
  7311. id="edit_maintenance_mode"
  7312. checked={!form.is_active}
  7313. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7314. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7315. />
  7316. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7317. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  7318. {t('printers.maintenance.editFieldLabel')}
  7319. </label>
  7320. </div>
  7321. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7322. {t('printers.maintenance.editFieldHelp')}
  7323. </p>
  7324. </div>
  7325. {saveWarning ? (
  7326. <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">
  7327. <div className="flex items-start gap-2">
  7328. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7329. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7330. </div>
  7331. <DiagnosticChecklist result={saveWarning} />
  7332. <div className="flex gap-3">
  7333. <Button
  7334. type="button"
  7335. variant="secondary"
  7336. onClick={() => setSaveWarning(null)}
  7337. className="flex-1"
  7338. >
  7339. {t('printers.addPreflight.back')}
  7340. </Button>
  7341. <Button
  7342. type="button"
  7343. onClick={doSave}
  7344. className="flex-1"
  7345. disabled={updateMutation.isPending}
  7346. >
  7347. {t('printers.addPreflight.saveAnyway')}
  7348. </Button>
  7349. </div>
  7350. </div>
  7351. ) : (
  7352. <div className="flex gap-3 pt-4">
  7353. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7354. {t('common.cancel')}
  7355. </Button>
  7356. <Button
  7357. type="submit"
  7358. className="flex-1"
  7359. disabled={updateMutation.isPending || checkingSave}
  7360. >
  7361. {checkingSave
  7362. ? t('printers.addPreflight.checking')
  7363. : updateMutation.isPending
  7364. ? t('common.saving')
  7365. : t('printers.modal.saveChanges')}
  7366. </Button>
  7367. </div>
  7368. )}
  7369. </form>
  7370. </CardContent>
  7371. </Card>
  7372. </div>
  7373. );
  7374. }
  7375. // Component to check if a printer is offline (for power dropdown)
  7376. function usePrinterOfflineStatus(printerId: number) {
  7377. const { data: status } = useQuery({
  7378. queryKey: ['printerStatus', printerId],
  7379. queryFn: () => api.getPrinterStatus(printerId),
  7380. refetchInterval: 30000,
  7381. });
  7382. return !status?.connected;
  7383. }
  7384. // Power dropdown item for an offline printer
  7385. function PowerDropdownItem({
  7386. printer,
  7387. plug,
  7388. onPowerOn,
  7389. isPowering,
  7390. }: {
  7391. printer: Printer;
  7392. plug: { id: number; name: string };
  7393. onPowerOn: (plugId: number) => void;
  7394. isPowering: boolean;
  7395. }) {
  7396. const isOffline = usePrinterOfflineStatus(printer.id);
  7397. // Fetch plug status
  7398. const { data: plugStatus } = useQuery({
  7399. queryKey: ['smartPlugStatus', plug.id],
  7400. queryFn: () => api.getSmartPlugStatus(plug.id),
  7401. refetchInterval: 10000,
  7402. });
  7403. // Only show if printer is offline
  7404. if (!isOffline) {
  7405. return null;
  7406. }
  7407. return (
  7408. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7409. <div className="flex items-center gap-2 min-w-0">
  7410. <span className="text-sm text-white truncate">{printer.name}</span>
  7411. {plugStatus && (
  7412. <span
  7413. className={`text-xs px-1.5 py-0.5 rounded ${
  7414. plugStatus.state === 'ON'
  7415. ? 'bg-bambu-green/20 text-bambu-green'
  7416. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  7417. }`}
  7418. >
  7419. {plugStatus.state || '?'}
  7420. </span>
  7421. )}
  7422. </div>
  7423. <button
  7424. onClick={() => onPowerOn(plug.id)}
  7425. disabled={isPowering || plugStatus?.state === 'ON'}
  7426. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7427. plugStatus?.state === 'ON'
  7428. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7429. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7430. }`}
  7431. >
  7432. <Power className="w-3 h-3" />
  7433. {isPowering ? '...' : 'On'}
  7434. </button>
  7435. </div>
  7436. );
  7437. }
  7438. export function PrintersPage() {
  7439. const { t } = useTranslation();
  7440. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7441. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7442. const accentButtonClass = {
  7443. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7444. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7445. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7446. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7447. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7448. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7449. }[activeAccent];
  7450. const [showAddModal, setShowAddModal] = useState(false);
  7451. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7452. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7453. });
  7454. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7455. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7456. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7457. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7458. });
  7459. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7460. return localStorage.getItem('printerSortAsc') !== 'false';
  7461. });
  7462. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7463. const [cardSize, setCardSize] = useState<number>(() => {
  7464. const saved = localStorage.getItem('printerCardSize');
  7465. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7466. });
  7467. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  7468. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  7469. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  7470. });
  7471. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  7472. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  7473. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  7474. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  7475. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  7476. });
  7477. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  7478. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  7479. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  7480. });
  7481. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  7482. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  7483. // Defaulting to 'full' because the cards already show this info — users who
  7484. // pick cam-wall view still want to glance the same details without flipping.
  7485. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  7486. const saved = localStorage.getItem('camWallStatusMode');
  7487. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  7488. });
  7489. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7490. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7491. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7492. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7493. requestAnimationFrame(() => {
  7494. requestAnimationFrame(() => {
  7495. const card = document.getElementById(`printer-card-${printerId}`);
  7496. if (!card) return;
  7497. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7498. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7499. window.scrollTo({
  7500. top: Math.max(0, top),
  7501. behavior: 'smooth',
  7502. });
  7503. });
  7504. });
  7505. }, []);
  7506. const openCompactCard = useCallback((printerId: number) => {
  7507. setCompactDrilldownPrinterId(printerId);
  7508. setCardSize(2);
  7509. localStorage.setItem('printerCardSize', '2');
  7510. scrollPrinterIntoView(printerId);
  7511. }, [scrollPrinterIntoView]);
  7512. const returnToCompactCards = useCallback(() => {
  7513. const printerId = compactDrilldownPrinterId;
  7514. setCompactDrilldownPrinterId(null);
  7515. setCardSize(1);
  7516. localStorage.setItem('printerCardSize', '1');
  7517. if (printerId != null) {
  7518. scrollPrinterIntoView(printerId);
  7519. }
  7520. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7521. const [search, setSearch] = useState('');
  7522. const [statusFilter, setStatusFilter] = useState<string>('all');
  7523. const [locationFilter, setLocationFilter] = useState<string>('all');
  7524. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7525. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7526. try {
  7527. const saved = localStorage.getItem('printerCollapsedSections');
  7528. return saved ? JSON.parse(saved) : {};
  7529. } catch { return {}; }
  7530. });
  7531. const queryClient = useQueryClient();
  7532. const { showToast } = useToast();
  7533. const { hasPermission } = useAuth();
  7534. // Embedded camera viewer state - supports multiple simultaneous viewers
  7535. // Persisted to localStorage so cameras reopen after navigation
  7536. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7537. // Initialize from localStorage if camera_view_mode is embedded
  7538. const saved = localStorage.getItem('openEmbeddedCameras');
  7539. if (saved) {
  7540. try {
  7541. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7542. return new Map(cameras.map(c => [c.id, c]));
  7543. } catch {
  7544. return new Map();
  7545. }
  7546. }
  7547. return new Map();
  7548. });
  7549. // Persist open cameras to localStorage when they change
  7550. useEffect(() => {
  7551. const cameras = Array.from(embeddedCameraPrinters.values());
  7552. if (cameras.length > 0) {
  7553. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7554. } else {
  7555. localStorage.removeItem('openEmbeddedCameras');
  7556. }
  7557. }, [embeddedCameraPrinters]);
  7558. const { data: printers, isLoading } = useQuery({
  7559. queryKey: ['printers'],
  7560. queryFn: api.getPrinters,
  7561. });
  7562. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7563. // so users with printers:read but no settings:read still get the values needed
  7564. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7565. const { data: settings } = useQuery({
  7566. queryKey: ['ui-preferences'],
  7567. queryFn: api.getUiPreferences,
  7568. });
  7569. // Parse user-configured temperature/fan presets once, with defensive fallback
  7570. // to built-in defaults on parse failure (validators on the backend already
  7571. // reject malformed writes, so this is just forward-compat).
  7572. const effectiveNozzleTempPresets = useMemo(
  7573. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7574. [settings?.nozzle_temp_presets],
  7575. );
  7576. const effectiveBedTempPresets = useMemo(
  7577. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7578. [settings?.bed_temp_presets],
  7579. );
  7580. const effectiveChamberTempPresets = useMemo(
  7581. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, 60),
  7582. [settings?.chamber_temp_presets],
  7583. );
  7584. const effectiveFanSpeedPresets = useMemo(
  7585. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7586. [settings?.fan_speed_presets],
  7587. );
  7588. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7589. const effectiveDryingPresets = useMemo(() => {
  7590. if (settings?.drying_presets) {
  7591. try {
  7592. const userPresets = JSON.parse(settings.drying_presets);
  7593. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7594. return { ...DRYING_PRESETS, ...userPresets };
  7595. }
  7596. } catch { /* ignore parse errors, use defaults */ }
  7597. }
  7598. return DRYING_PRESETS;
  7599. }, [settings?.drying_presets]);
  7600. // Close embedded cameras if mode changes to 'window'
  7601. useEffect(() => {
  7602. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7603. setEmbeddedCameraPrinters(new Map());
  7604. }
  7605. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7606. // Fetch all smart plugs to know which printers have them
  7607. const { data: smartPlugs } = useQuery({
  7608. queryKey: ['smart-plugs'],
  7609. queryFn: api.getSmartPlugs,
  7610. });
  7611. // Fetch maintenance overview for all printers to show badges
  7612. const { data: maintenanceOverview } = useQuery({
  7613. queryKey: ['maintenanceOverview'],
  7614. queryFn: api.getMaintenanceOverview,
  7615. staleTime: 60 * 1000, // 1 minute
  7616. });
  7617. // Live AI failure detection state for the card badges (#1546). Matches the
  7618. // 10s refetch of the Failure Detection settings panel.
  7619. const { data: obicoPrinterStatus } = useQuery({
  7620. queryKey: ['obico-printer-status'],
  7621. queryFn: api.getObicoPrinterStatus,
  7622. refetchInterval: 10000,
  7623. });
  7624. // Badge visibility: detection enabled AND this printer in the monitored set
  7625. // (monitored_printers null = all). Live per-print state is passed separately.
  7626. const isAiMonitored = useCallback(
  7627. (printerId: number) =>
  7628. obicoPrinterStatus?.enabled === true &&
  7629. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  7630. [obicoPrinterStatus],
  7631. );
  7632. // Fetch Spoolman status to enable link spool feature
  7633. const { data: spoolmanStatus } = useQuery({
  7634. queryKey: ['spoolman-status'],
  7635. queryFn: api.getSpoolmanStatus,
  7636. staleTime: 60 * 1000, // 1 minute
  7637. });
  7638. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7639. // Fetch Spoolman settings to get sync mode
  7640. const { data: spoolmanSettings } = useQuery({
  7641. queryKey: ['spoolman-settings'],
  7642. queryFn: api.getSpoolmanSettings,
  7643. enabled: !!spoolmanEnabled,
  7644. staleTime: 60 * 1000, // 1 minute
  7645. });
  7646. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7647. // Fetch unlinked spools to know if link button should be enabled
  7648. const { data: unlinkedSpools } = useQuery({
  7649. queryKey: ['unlinked-spools'],
  7650. queryFn: api.getUnlinkedSpools,
  7651. enabled: !!spoolmanEnabled,
  7652. staleTime: 30 * 1000, // 30 seconds
  7653. });
  7654. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7655. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7656. const { data: linkedSpoolsData } = useQuery({
  7657. queryKey: ['linked-spools'],
  7658. queryFn: api.getLinkedSpools,
  7659. enabled: !!spoolmanEnabled,
  7660. staleTime: 30 * 1000, // 30 seconds
  7661. });
  7662. const linkedSpools = linkedSpoolsData?.linked;
  7663. // Fetch spool assignments for inventory feature
  7664. const { data: spoolAssignments } = useQuery({
  7665. queryKey: ['spool-assignments'],
  7666. queryFn: () => api.getAssignments(),
  7667. enabled: hasPermission('inventory:view_assignments'),
  7668. staleTime: 30 * 1000,
  7669. });
  7670. const unassignMutation = useMutation({
  7671. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7672. api.unassignSpool(printerId, amsId, trayId),
  7673. onSuccess: () => {
  7674. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7675. },
  7676. });
  7677. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7678. queryKey: ['spoolman-inventory-spools'],
  7679. queryFn: () => api.getSpoolmanInventorySpools(false),
  7680. enabled: !!spoolmanEnabled,
  7681. staleTime: 30 * 1000,
  7682. });
  7683. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7684. queryKey: ['spoolman-slot-assignments'],
  7685. queryFn: () => api.getSpoolmanSlotAssignments(),
  7686. enabled: !!spoolmanEnabled,
  7687. staleTime: 30 * 1000,
  7688. });
  7689. const unassignSpoolmanMutation = useMutation({
  7690. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7691. onSuccess: () => {
  7692. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7693. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7694. },
  7695. });
  7696. // Helper to find assignment for a specific slot
  7697. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7698. return spoolAssignments?.find(
  7699. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7700. );
  7701. };
  7702. // Create a map of printer_id -> maintenance info for quick lookup
  7703. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7704. (acc, overview) => {
  7705. acc[overview.printer_id] = {
  7706. due_count: overview.due_count,
  7707. warning_count: overview.warning_count,
  7708. total_print_hours: overview.total_print_hours,
  7709. };
  7710. return acc;
  7711. },
  7712. {} as Record<number, PrinterMaintenanceInfo>
  7713. ) || {};
  7714. // Create a map of printer_id -> smart plug
  7715. const smartPlugByPrinter = smartPlugs?.reduce(
  7716. (acc, plug) => {
  7717. if (plug.printer_id) {
  7718. acc[plug.printer_id] = plug;
  7719. }
  7720. return acc;
  7721. },
  7722. {} as Record<number, typeof smartPlugs[0]>
  7723. ) || {};
  7724. const addMutation = useMutation({
  7725. mutationFn: api.createPrinter,
  7726. onSuccess: () => {
  7727. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7728. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  7729. setShowAddModal(false);
  7730. },
  7731. onError: (error: Error) => {
  7732. // Localized message when the backend returns a stable error code;
  7733. // the raw message is an English fallback for non-UI clients.
  7734. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  7735. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  7736. return;
  7737. }
  7738. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  7739. },
  7740. });
  7741. const powerOnMutation = useMutation({
  7742. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  7743. onSuccess: () => {
  7744. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  7745. setPoweringOn(null);
  7746. },
  7747. onError: () => {
  7748. setPoweringOn(null);
  7749. },
  7750. });
  7751. // Bulk selection state
  7752. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  7753. const [isSelectionMode, setIsSelectionMode] = useState(false);
  7754. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  7755. const [bulkActionPending, setBulkActionPending] = useState(false);
  7756. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  7757. const toggleSelect = useCallback((id: number) => {
  7758. setSelectedPrinterIds(prev => {
  7759. const next = new Set(prev);
  7760. if (next.has(id)) next.delete(id);
  7761. else next.add(id);
  7762. return next;
  7763. });
  7764. }, []);
  7765. const clearSelection = useCallback(() => {
  7766. setSelectedPrinterIds(new Set());
  7767. setIsSelectionMode(false);
  7768. }, []);
  7769. // Escape key exits selection mode
  7770. useEffect(() => {
  7771. const handleKeyDown = (e: KeyboardEvent) => {
  7772. if (e.key === 'Escape' && selectionMode) {
  7773. clearSelection();
  7774. }
  7775. };
  7776. window.addEventListener('keydown', handleKeyDown);
  7777. return () => window.removeEventListener('keydown', handleKeyDown);
  7778. }, [selectionMode, clearSelection]);
  7779. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7780. setBulkActionPending(true);
  7781. const ids = Array.from(selectedPrinterIds);
  7782. // Filter to only applicable printers based on cached state
  7783. const applicableIds = ids.filter(id => {
  7784. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  7785. if (!status?.connected) return false;
  7786. switch (action) {
  7787. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  7788. case 'pause': return status.state === 'RUNNING';
  7789. case 'resume': return status.state === 'PAUSE';
  7790. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  7791. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  7792. default: return false;
  7793. }
  7794. });
  7795. if (applicableIds.length === 0) {
  7796. showToast(t('printers.bulk.noneApplicable'), 'error');
  7797. setBulkActionPending(false);
  7798. setBulkConfirmAction(null);
  7799. return;
  7800. }
  7801. const apiCall = {
  7802. stop: api.stopPrint,
  7803. pause: api.pausePrint,
  7804. resume: api.resumePrint,
  7805. clearPlate: api.clearPlate,
  7806. clearHMS: api.clearHMSErrors,
  7807. }[action];
  7808. const results = await Promise.allSettled(
  7809. applicableIds.map(id => apiCall(id))
  7810. );
  7811. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  7812. const failed = results.filter(r => r.status === 'rejected').length;
  7813. if (failed === 0) {
  7814. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  7815. } else {
  7816. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  7817. }
  7818. // Invalidate status queries for affected printers
  7819. applicableIds.forEach(id => {
  7820. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  7821. });
  7822. setBulkActionPending(false);
  7823. setBulkConfirmAction(null);
  7824. }, [selectedPrinterIds, queryClient, showToast, t]);
  7825. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  7826. // Actions that need confirmation
  7827. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  7828. setBulkConfirmAction(action);
  7829. } else {
  7830. executeBulkAction(action);
  7831. }
  7832. }, [executeBulkAction]);
  7833. const toggleHideDisconnected = () => {
  7834. const newValue = !hideDisconnected;
  7835. setHideDisconnected(newValue);
  7836. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  7837. };
  7838. const handleSortChange = (newSort: SortOption) => {
  7839. setSortBy(newSort);
  7840. localStorage.setItem('printerSortBy', newSort);
  7841. };
  7842. const toggleSortDirection = () => {
  7843. const newAsc = !sortAsc;
  7844. setSortAsc(newAsc);
  7845. localStorage.setItem('printerSortAsc', String(newAsc));
  7846. };
  7847. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  7848. const getGridClasses = () => {
  7849. switch (cardSize) {
  7850. 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
  7851. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  7852. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  7853. case 4: return 'grid-cols-1'; // XL: single column, full width
  7854. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  7855. }
  7856. };
  7857. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  7858. // Increment version counter whenever a printer status cache entry is updated so
  7859. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  7860. useEffect(() => {
  7861. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  7862. if (
  7863. event.type === 'updated' &&
  7864. Array.isArray(event.query.queryKey) &&
  7865. event.query.queryKey[0] === 'printerStatus'
  7866. ) {
  7867. setStatusCacheVersion(v => v + 1);
  7868. }
  7869. });
  7870. return unsubscribe;
  7871. }, [queryClient]);
  7872. // Filter printers by search term, status, and location
  7873. const filteredPrinters = useMemo(() => {
  7874. if (!printers) return [];
  7875. let result = printers;
  7876. // Text search
  7877. if (search.trim()) {
  7878. const q = search.trim().toLowerCase();
  7879. result = result.filter(p =>
  7880. p.name.toLowerCase().includes(q) ||
  7881. (p.model || '').toLowerCase().includes(q) ||
  7882. (p.location || '').toLowerCase().includes(q) ||
  7883. (p.serial_number || '').toLowerCase().includes(q)
  7884. );
  7885. }
  7886. // Location filter
  7887. if (locationFilter !== 'all') {
  7888. result = result.filter(p => (p.location || '') === locationFilter);
  7889. }
  7890. // Status filter
  7891. if (statusFilter !== 'all') {
  7892. result = result.filter(p => {
  7893. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7894. if (!status?.connected) return statusFilter === 'offline';
  7895. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  7896. switch (statusFilter) {
  7897. case 'printing': return status.state === 'RUNNING';
  7898. case 'paused': return status.state === 'PAUSE';
  7899. case 'finished': return status.state === 'FINISH';
  7900. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  7901. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  7902. case 'offline': return false; // Connected printers are never offline
  7903. default: return true;
  7904. }
  7905. });
  7906. }
  7907. return result;
  7908. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  7909. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  7910. // Derive unique locations for the location filter dropdown
  7911. const availableLocations = useMemo(() => {
  7912. if (!printers) return [];
  7913. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  7914. }, [printers]);
  7915. // Sort printers based on selected option
  7916. const sortedPrinters = useMemo(() => {
  7917. const sorted = [...filteredPrinters];
  7918. switch (sortBy) {
  7919. case 'name':
  7920. sorted.sort((a, b) => a.name.localeCompare(b.name));
  7921. break;
  7922. case 'model':
  7923. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  7924. break;
  7925. case 'location':
  7926. // Sort by location, with ungrouped printers last
  7927. sorted.sort((a, b) => {
  7928. const locA = a.location || '';
  7929. const locB = b.location || '';
  7930. if (!locA && locB) return 1;
  7931. if (locA && !locB) return -1;
  7932. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  7933. });
  7934. break;
  7935. case 'status':
  7936. // Sort by status: HMS errors > printing > idle > offline
  7937. sorted.sort((a, b) => {
  7938. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  7939. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  7940. const getPriority = (s: typeof statusA) => {
  7941. if (!s?.connected) return 3; // offline
  7942. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  7943. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  7944. if (s.state === 'RUNNING') return 1; // printing
  7945. return 2; // idle
  7946. };
  7947. return getPriority(statusA) - getPriority(statusB);
  7948. });
  7949. break;
  7950. case 'eta':
  7951. sorted.sort((a, b) => {
  7952. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  7953. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  7954. const tier = (s: typeof statusA) => {
  7955. if (!s?.connected) return 3; // offline last
  7956. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  7957. if (s.state === 'RUNNING') return 1; // printing without ETA
  7958. return 2; // idle
  7959. };
  7960. const ta = tier(statusA);
  7961. const tb = tier(statusB);
  7962. if (ta !== tb) return ta - tb;
  7963. if (ta === 0) {
  7964. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  7965. if (diff !== 0) return diff;
  7966. }
  7967. return a.name.localeCompare(b.name);
  7968. });
  7969. break;
  7970. }
  7971. // Apply ascending/descending
  7972. if (!sortAsc) {
  7973. sorted.reverse();
  7974. }
  7975. return sorted;
  7976. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  7977. const selectAll = useCallback(() => {
  7978. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  7979. setIsSelectionMode(true);
  7980. }, [sortedPrinters]);
  7981. const selectByState = useCallback((state: PrinterState) => {
  7982. setSelectedPrinterIds(prev => {
  7983. const next = new Set(prev);
  7984. sortedPrinters.forEach(p => {
  7985. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  7986. if (classifyPrinterStatus(status) === state) next.add(p.id);
  7987. });
  7988. return next;
  7989. });
  7990. setIsSelectionMode(true);
  7991. }, [sortedPrinters, queryClient]);
  7992. const selectByLocation = useCallback((location: string) => {
  7993. setSelectedPrinterIds(prev => {
  7994. const next = new Set(prev);
  7995. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  7996. return next;
  7997. });
  7998. setIsSelectionMode(true);
  7999. }, [sortedPrinters]);
  8000. const selectByModel = useCallback((model: string) => {
  8001. setSelectedPrinterIds(prev => {
  8002. const next = new Set(prev);
  8003. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  8004. return next;
  8005. });
  8006. setIsSelectionMode(true);
  8007. }, [sortedPrinters]);
  8008. const toggleSectionCollapse = useCallback((key: string) => {
  8009. setCollapsedSections(prev => {
  8010. const next = { ...prev, [key]: !prev[key] };
  8011. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  8012. return next;
  8013. });
  8014. }, []);
  8015. // Group printers when sorted by location, status, or model
  8016. const groupedPrinters = useMemo(() => {
  8017. if (sortBy === 'name' || sortBy === 'eta') return null;
  8018. const groups: Record<string, typeof sortedPrinters> = {};
  8019. if (sortBy === 'location') {
  8020. sortedPrinters.forEach(printer => {
  8021. const location = printer.location || 'Ungrouped';
  8022. if (!groups[location]) groups[location] = [];
  8023. groups[location].push(printer);
  8024. });
  8025. } else if (sortBy === 'model') {
  8026. sortedPrinters.forEach(printer => {
  8027. const model = printer.model || 'Unknown';
  8028. if (!groups[model]) groups[model] = [];
  8029. groups[model].push(printer);
  8030. });
  8031. } else if (sortBy === 'status') {
  8032. sortedPrinters.forEach(printer => {
  8033. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  8034. const group = classifyPrinterStatus(status);
  8035. if (!groups[group]) groups[group] = [];
  8036. groups[group].push(printer);
  8037. });
  8038. }
  8039. return groups;
  8040. // 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
  8041. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  8042. const toolbarRef = useRef<HTMLDivElement>(null);
  8043. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  8044. const expandedToolbarWidthRef = useRef(0);
  8045. const [compactToolbar, setCompactToolbar] = useState(false);
  8046. const measureToolbar = useCallback(() => {
  8047. const toolbar = toolbarRef.current;
  8048. if (!toolbar) return;
  8049. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  8050. if (measuredControlsWidth) {
  8051. expandedToolbarWidthRef.current = measuredControlsWidth;
  8052. }
  8053. const searchMinimumWidth = 220;
  8054. const gapWidth = 8;
  8055. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  8056. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  8057. }, []);
  8058. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  8059. useLayoutEffect(() => {
  8060. measureToolbar();
  8061. const toolbar = toolbarRef.current;
  8062. if (!toolbar) return;
  8063. if (typeof ResizeObserver === 'undefined') {
  8064. window.addEventListener('resize', measureToolbar);
  8065. return () => window.removeEventListener('resize', measureToolbar);
  8066. }
  8067. const resizeObserver = new ResizeObserver(() => measureToolbar());
  8068. resizeObserver.observe(toolbar);
  8069. window.addEventListener('resize', measureToolbar);
  8070. return () => {
  8071. resizeObserver.disconnect();
  8072. window.removeEventListener('resize', measureToolbar);
  8073. };
  8074. }, [
  8075. measureToolbar,
  8076. printers?.length,
  8077. availableLocations.length,
  8078. hideDisconnected,
  8079. smartPlugCount,
  8080. ]);
  8081. const renderFilterControls = (inMenu = false) => (
  8082. <>
  8083. {/* Status filter */}
  8084. {printers && printers.length > 0 && (
  8085. <ToolbarDropdown
  8086. value={statusFilter}
  8087. onChange={setStatusFilter}
  8088. fullWidth={inMenu}
  8089. options={[
  8090. { value: 'all', label: t('printers.filter.allStatuses') },
  8091. { value: 'printing', label: t('printers.status.printing') },
  8092. { value: 'paused', label: t('printers.status.paused') },
  8093. { value: 'idle', label: t('printers.status.idle') },
  8094. { value: 'finished', label: t('printers.status.finished') },
  8095. { value: 'error', label: t('printers.status.error') },
  8096. { value: 'offline', label: t('printers.status.offline') },
  8097. ]}
  8098. />
  8099. )}
  8100. {/* Location filter — only shown when at least one printer has a location */}
  8101. {printers && printers.length > 0 && availableLocations.length > 0 && (
  8102. <ToolbarDropdown
  8103. value={locationFilter}
  8104. onChange={setLocationFilter}
  8105. fullWidth={inMenu}
  8106. options={[
  8107. { value: 'all', label: t('printers.filter.allLocations') },
  8108. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  8109. ]}
  8110. />
  8111. )}
  8112. <button
  8113. type="button"
  8114. onClick={toggleHideDisconnected}
  8115. aria-pressed={hideDisconnected}
  8116. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  8117. hideDisconnected
  8118. ? 'bg-bambu-green border-bambu-green text-white'
  8119. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8120. }`}
  8121. >
  8122. {t('printers.hideOffline')}
  8123. </button>
  8124. </>
  8125. );
  8126. const renderViewControls = (inMenu = false) => (
  8127. <>
  8128. {/* Sort dropdown */}
  8129. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8130. <ToolbarDropdown<SortOption>
  8131. value={sortBy}
  8132. onChange={handleSortChange}
  8133. fullWidth={inMenu}
  8134. options={[
  8135. { value: 'name', label: t('printers.sort.name') },
  8136. { value: 'status', label: t('printers.sort.status') },
  8137. { value: 'model', label: t('printers.sort.model') },
  8138. { value: 'location', label: t('printers.sort.location') },
  8139. { value: 'eta', label: t('printers.sort.eta') },
  8140. ]}
  8141. />
  8142. <button
  8143. onClick={toggleSortDirection}
  8144. 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"
  8145. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8146. >
  8147. {sortAsc ? (
  8148. <ArrowUp className="w-4 h-4 text-white" />
  8149. ) : (
  8150. <ArrowDown className="w-4 h-4 text-white" />
  8151. )}
  8152. </button>
  8153. </div>
  8154. {/* Page view toggle: Cards / Cam Wall */}
  8155. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8156. <button
  8157. type="button"
  8158. onClick={() => {
  8159. setPageView('cards');
  8160. localStorage.setItem('printerPageView', 'cards');
  8161. }}
  8162. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8163. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8164. }`}
  8165. title={t('printers.pageView.cards')}
  8166. aria-pressed={pageView === 'cards'}
  8167. >
  8168. <LayoutGrid className="w-3.5 h-3.5" />
  8169. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8170. </button>
  8171. <button
  8172. type="button"
  8173. onClick={() => {
  8174. setPageView('camwall');
  8175. localStorage.setItem('printerPageView', 'camwall');
  8176. }}
  8177. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8178. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8179. }`}
  8180. title={t('printers.pageView.camWall')}
  8181. aria-pressed={pageView === 'camwall'}
  8182. disabled={!hasPermission('camera:view')}
  8183. >
  8184. <MonitorPlay className="w-3.5 h-3.5" />
  8185. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8186. </button>
  8187. </div>
  8188. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8189. view, and the page a kiosk token points at. Only offered once the wall
  8190. is the active view, so it doesn't compete with the toggle above. */}
  8191. {pageView === 'camwall' && hasPermission('camera:view') && (
  8192. <RouterLink
  8193. to="/camwall"
  8194. 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' : ''}`}
  8195. title={t('printers.pageView.openCamWallPage')}
  8196. >
  8197. <ExternalLink className="w-3.5 h-3.5" />
  8198. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8199. </RouterLink>
  8200. )}
  8201. {/* Card size selector */}
  8202. <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' : ''}`}>
  8203. {cardSizeLabels.map((label, index) => {
  8204. const size = index + 1;
  8205. const isSelected = cardSize === size;
  8206. return (
  8207. <button
  8208. key={label}
  8209. onClick={() => {
  8210. setCompactDrilldownPrinterId(null);
  8211. setCardSize(size);
  8212. localStorage.setItem('printerCardSize', String(size));
  8213. }}
  8214. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8215. index === 0 ? 'rounded-l-lg' : ''
  8216. } ${
  8217. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8218. } ${
  8219. isSelected
  8220. ? 'bg-bambu-green text-white'
  8221. : 'text-white hover:bg-bambu-dark-tertiary'
  8222. }`}
  8223. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8224. >
  8225. {label}
  8226. </button>
  8227. );
  8228. })}
  8229. </div>
  8230. </>
  8231. );
  8232. const renderActionControls = (inMenu = false) => (
  8233. <>
  8234. {/* Bulk select toggle */}
  8235. <button
  8236. onClick={() => {
  8237. if (selectionMode) clearSelection();
  8238. else setIsSelectionMode(true);
  8239. }}
  8240. 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' : ''} ${
  8241. selectionMode
  8242. ? 'bg-bambu-green border-bambu-green text-white'
  8243. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8244. }`}
  8245. title={t('printers.bulk.select')}
  8246. disabled={!hasPermission('printers:control')}
  8247. >
  8248. <CheckSquare className="w-4 h-4" />
  8249. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8250. </button>
  8251. {/* Power dropdown for offline printers with smart plugs */}
  8252. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8253. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8254. <button
  8255. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8256. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8257. inMenu
  8258. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8259. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8260. }`}
  8261. >
  8262. <span className="flex items-center gap-1.5">
  8263. <Power className="w-4 h-4" />
  8264. {t('printers.powerOn')}
  8265. </span>
  8266. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8267. </button>
  8268. {showPowerDropdown && (
  8269. <>
  8270. {/* Backdrop to close dropdown */}
  8271. <div
  8272. className="fixed inset-0 z-10"
  8273. onClick={() => setShowPowerDropdown(false)}
  8274. />
  8275. <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">
  8276. <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">
  8277. {t('printers.offlinePrintersWithPlugs')}
  8278. </div>
  8279. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  8280. <PowerDropdownItem
  8281. key={printer.id}
  8282. printer={printer}
  8283. plug={smartPlugByPrinter[printer.id]}
  8284. onPowerOn={(plugId) => {
  8285. setPoweringOn(plugId);
  8286. powerOnMutation.mutate(plugId);
  8287. }}
  8288. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  8289. />
  8290. ))}
  8291. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  8292. <div className="px-3 py-2 text-sm text-bambu-gray">
  8293. No printers with smart plugs
  8294. </div>
  8295. )}
  8296. </div>
  8297. </>
  8298. )}
  8299. </div>
  8300. )}
  8301. <Button
  8302. onClick={() => setShowAddModal(true)}
  8303. disabled={!hasPermission('printers:create')}
  8304. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8305. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  8306. >
  8307. <Plus className="w-4 h-4" />
  8308. {t('printers.addPrinter')}
  8309. </Button>
  8310. </>
  8311. );
  8312. return (
  8313. <div className="p-4 md:p-8">
  8314. <div className="space-y-3 mb-6">
  8315. <div>
  8316. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  8317. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  8318. {t('printers.title')}
  8319. </h1>
  8320. <StatusSummaryBar printers={printers} />
  8321. </div>
  8322. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8323. {/* Only show search bar when printers exist */}
  8324. {printers && printers.length > 0 && (
  8325. <div className="relative min-w-0 flex-1">
  8326. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8327. <input
  8328. type="search"
  8329. name="printer-search"
  8330. autoComplete="off"
  8331. data-1p-ignore
  8332. data-lpignore="true"
  8333. value={search}
  8334. onChange={(e) => setSearch(e.target.value)}
  8335. placeholder={t('printers.search')}
  8336. aria-label={t('printers.search')}
  8337. 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"
  8338. />
  8339. {search && (
  8340. <button
  8341. type="button"
  8342. aria-label={t('common.clear')}
  8343. onClick={() => setSearch('')}
  8344. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8345. >
  8346. <X className="w-4 h-4" />
  8347. </button>
  8348. )}
  8349. </div>
  8350. )}
  8351. <div
  8352. ref={expandedToolbarControlsRef}
  8353. aria-hidden={compactToolbar}
  8354. inert={compactToolbar}
  8355. 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`}
  8356. >
  8357. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8358. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8359. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8360. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8361. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8362. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8363. </div>
  8364. {compactToolbar && (
  8365. <div className="ml-auto flex items-center justify-end gap-1">
  8366. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8367. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8368. </ToolbarMenu>
  8369. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8370. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8371. </ToolbarMenu>
  8372. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8373. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8374. </ToolbarMenu>
  8375. </div>
  8376. )}
  8377. </div>
  8378. </div>
  8379. {isLoading ? (
  8380. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8381. ) : printers?.length === 0 ? (
  8382. <Card>
  8383. <CardContent className="text-center py-12">
  8384. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8385. <Button
  8386. onClick={() => setShowAddModal(true)}
  8387. disabled={!hasPermission('printers:create')}
  8388. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8389. >
  8390. <Plus className="w-4 h-4" />
  8391. {t('printers.addPrinter')}
  8392. </Button>
  8393. </CardContent>
  8394. </Card>
  8395. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8396. <Card>
  8397. <CardContent className="text-center py-12">
  8398. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8399. </CardContent>
  8400. </Card>
  8401. ) : pageView === 'camwall' ? (
  8402. <CameraWall
  8403. printers={sortedPrinters}
  8404. maxLive={camWallMaxLive}
  8405. snapshotIntervalSec={camWallSnapshotSec}
  8406. onTileClick={(id, name) => {
  8407. const cameraMode = settings?.camera_view_mode || 'window';
  8408. if (cameraMode === 'embedded') {
  8409. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  8410. } else {
  8411. const saved = localStorage.getItem('cameraWindowState');
  8412. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  8413. const features = [
  8414. `width=${state.width}`,
  8415. `height=${state.height}`,
  8416. state.left !== undefined ? `left=${state.left}` : '',
  8417. state.top !== undefined ? `top=${state.top}` : '',
  8418. 'menubar=no,toolbar=no,location=no,status=no',
  8419. ].filter(Boolean).join(',');
  8420. window.open(`/camera/${id}`, `camera-${id}`, features);
  8421. }
  8422. }}
  8423. statusMode={camWallStatusMode}
  8424. onChangeMaxLive={(next) => {
  8425. setCamWallMaxLive(next);
  8426. localStorage.setItem('camWallMaxLive', String(next));
  8427. }}
  8428. onChangeSnapshotIntervalSec={(next) => {
  8429. setCamWallSnapshotSec(next);
  8430. localStorage.setItem('camWallSnapshotSec', String(next));
  8431. }}
  8432. onChangeStatusMode={(next) => {
  8433. setCamWallStatusMode(next);
  8434. localStorage.setItem('camWallStatusMode', next);
  8435. }}
  8436. />
  8437. ) : groupedPrinters ? (
  8438. /* Grouped view (location, status, or model) */
  8439. <div className="space-y-6">
  8440. {(() => {
  8441. const keys = sortBy === 'status'
  8442. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8443. : Object.keys(groupedPrinters);
  8444. // For status grouping, asc/desc flips the fixed priority order
  8445. // (asc = error→offline, desc = offline→error). This matches the
  8446. // sort-toggle behaviour for other groupings.
  8447. return (sortAsc ? keys : [...keys].reverse());
  8448. })().map((groupKey) => {
  8449. const groupPrinters = groupedPrinters[groupKey];
  8450. const collapseKey = `${sortBy}:${groupKey}`;
  8451. const isOpen = !collapsedSections[collapseKey];
  8452. const dot = sortBy === 'status'
  8453. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8454. : 'bg-bambu-green';
  8455. const label = sortBy === 'status'
  8456. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8457. : groupKey;
  8458. return (
  8459. <Collapsible
  8460. key={groupKey}
  8461. open={isOpen}
  8462. onToggle={() => toggleSectionCollapse(collapseKey)}
  8463. summaryClassName="py-1"
  8464. summary={
  8465. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8466. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8467. {label}
  8468. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8469. {selectionMode && (
  8470. <button
  8471. onClick={(e) => {
  8472. e.stopPropagation();
  8473. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8474. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8475. else if (sortBy === 'model') selectByModel(groupKey);
  8476. }}
  8477. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8478. >
  8479. {t('printers.bulk.selectAll')}
  8480. </button>
  8481. )}
  8482. </h2>
  8483. }
  8484. >
  8485. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8486. {groupPrinters.map((printer) => (
  8487. <PrinterCard
  8488. key={printer.id}
  8489. printer={printer}
  8490. hideIfDisconnected={hideDisconnected}
  8491. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8492. viewMode={viewMode}
  8493. cardSize={cardSize}
  8494. amsThresholds={settings ? {
  8495. humidityGood: Number(settings.ams_humidity_good) || 40,
  8496. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8497. tempGood: Number(settings.ams_temp_good) || 28,
  8498. tempFair: Number(settings.ams_temp_fair) || 35,
  8499. } : undefined}
  8500. spoolmanEnabled={spoolmanEnabled}
  8501. hasUnlinkedSpools={hasUnlinkedSpools}
  8502. linkedSpools={linkedSpools}
  8503. spoolmanUrl={spoolmanStatus?.url}
  8504. spoolmanSyncMode={spoolmanSyncMode}
  8505. onGetAssignment={getAssignment}
  8506. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8507. spoolmanSpools={spoolmanSpools}
  8508. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8509. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8510. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8511. timeFormat={settings?.time_format || 'system'}
  8512. cameraViewMode={settings?.camera_view_mode || 'window'}
  8513. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8514. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8515. dryingPresets={effectiveDryingPresets}
  8516. nozzleTempPresets={effectiveNozzleTempPresets}
  8517. bedTempPresets={effectiveBedTempPresets}
  8518. chamberTempPresets={effectiveChamberTempPresets}
  8519. fanSpeedPresets={effectiveFanSpeedPresets}
  8520. requirePlateClear={settings?.require_plate_clear === true}
  8521. selectionMode={selectionMode}
  8522. isSelected={selectedPrinterIds.has(printer.id)}
  8523. onToggleSelect={toggleSelect}
  8524. onOpenCompactCard={openCompactCard}
  8525. aiDetectionEnabled={isAiMonitored(printer.id)}
  8526. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8527. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8528. />
  8529. ))}
  8530. </div>
  8531. </Collapsible>
  8532. );
  8533. })}
  8534. </div>
  8535. ) : (
  8536. /* Regular grid view */
  8537. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8538. {sortedPrinters.map((printer) => (
  8539. <PrinterCard
  8540. key={printer.id}
  8541. printer={printer}
  8542. hideIfDisconnected={hideDisconnected}
  8543. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8544. viewMode={viewMode}
  8545. cardSize={cardSize}
  8546. spoolmanEnabled={spoolmanEnabled}
  8547. hasUnlinkedSpools={hasUnlinkedSpools}
  8548. linkedSpools={linkedSpools}
  8549. spoolmanUrl={spoolmanStatus?.url}
  8550. spoolmanSyncMode={spoolmanSyncMode}
  8551. onGetAssignment={getAssignment}
  8552. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8553. spoolmanSpools={spoolmanSpools}
  8554. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8555. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8556. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8557. amsThresholds={settings ? {
  8558. humidityGood: Number(settings.ams_humidity_good) || 40,
  8559. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8560. tempGood: Number(settings.ams_temp_good) || 28,
  8561. tempFair: Number(settings.ams_temp_fair) || 35,
  8562. } : undefined}
  8563. timeFormat={settings?.time_format || 'system'}
  8564. cameraViewMode={settings?.camera_view_mode || 'window'}
  8565. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8566. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8567. dryingPresets={effectiveDryingPresets}
  8568. nozzleTempPresets={effectiveNozzleTempPresets}
  8569. bedTempPresets={effectiveBedTempPresets}
  8570. chamberTempPresets={effectiveChamberTempPresets}
  8571. fanSpeedPresets={effectiveFanSpeedPresets}
  8572. requirePlateClear={settings?.require_plate_clear === true}
  8573. selectionMode={selectionMode}
  8574. isSelected={selectedPrinterIds.has(printer.id)}
  8575. onToggleSelect={toggleSelect}
  8576. onOpenCompactCard={openCompactCard}
  8577. aiDetectionEnabled={isAiMonitored(printer.id)}
  8578. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8579. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8580. />
  8581. ))}
  8582. </div>
  8583. )}
  8584. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8585. <button
  8586. type="button"
  8587. onClick={returnToCompactCards}
  8588. 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}`}
  8589. title={t('common.back', 'Back')}
  8590. >
  8591. <ArrowLeft className="w-4 h-4" />
  8592. {t('common.back', 'Back')}
  8593. </button>
  8594. )}
  8595. {showAddModal && (
  8596. <AddPrinterModal
  8597. onClose={() => setShowAddModal(false)}
  8598. onAdd={(data) => addMutation.mutate(data)}
  8599. existingSerials={printers?.map(p => p.serial_number) || []}
  8600. />
  8601. )}
  8602. {/* Bulk selection toolbar */}
  8603. {selectionMode && printers && (
  8604. <BulkPrinterToolbar
  8605. selectedIds={selectedPrinterIds}
  8606. printers={printers}
  8607. onClose={clearSelection}
  8608. onSelectAll={selectAll}
  8609. onSelectByLocation={selectByLocation}
  8610. onSelectByState={selectByState}
  8611. onAction={handleBulkAction}
  8612. actionPending={bulkActionPending}
  8613. />
  8614. )}
  8615. {/* Bulk action confirmation modals */}
  8616. {bulkConfirmAction === 'stop' && (
  8617. <ConfirmModal
  8618. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8619. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8620. confirmText={t('printers.bulk.confirm.stopButton')}
  8621. variant="danger"
  8622. isLoading={bulkActionPending}
  8623. onConfirm={() => executeBulkAction('stop')}
  8624. onCancel={() => setBulkConfirmAction(null)}
  8625. />
  8626. )}
  8627. {bulkConfirmAction === 'pause' && (
  8628. <ConfirmModal
  8629. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8630. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8631. confirmText={t('printers.bulk.confirm.pauseButton')}
  8632. isLoading={bulkActionPending}
  8633. onConfirm={() => executeBulkAction('pause')}
  8634. onCancel={() => setBulkConfirmAction(null)}
  8635. />
  8636. )}
  8637. {bulkConfirmAction === 'clearPlate' && (
  8638. <ConfirmModal
  8639. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8640. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8641. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8642. isLoading={bulkActionPending}
  8643. onConfirm={() => executeBulkAction('clearPlate')}
  8644. onCancel={() => setBulkConfirmAction(null)}
  8645. />
  8646. )}
  8647. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8648. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8649. <EmbeddedCameraViewer
  8650. key={camera.id}
  8651. printerId={camera.id}
  8652. printerName={camera.name}
  8653. viewerIndex={index}
  8654. onClose={() => setEmbeddedCameraPrinters(prev => {
  8655. const next = new Map(prev);
  8656. next.delete(camera.id);
  8657. return next;
  8658. })}
  8659. />
  8660. ))}
  8661. </div>
  8662. );
  8663. }