PrintersPage.tsx 455 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406
  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 { resolveDryingPresetKey, type DryingPreset } from '../utils/dryingPresets';
  7. import {
  8. isExternalSpoolHidden,
  9. setExternalSpoolHidden as persistExternalSpoolHidden,
  10. } from '../utils/printerCardPrefs';
  11. import {
  12. BED_TEMP_DEFAULTS,
  13. CHAMBER_TEMP_DEFAULTS,
  14. FAN_SPEED_DEFAULTS,
  15. NOZZLE_TEMP_DEFAULTS,
  16. buildPresetOptions,
  17. parsePresetTriple,
  18. } from '../utils/temperatureFanPresets';
  19. // AMS drying popover dimensions — w-[240px] on the popover, estimated height
  20. // covers header + filament select + temp slider + duration + rotate-tray
  21. // toggle + buttons. Over-estimating is fine (flip-above kicks in slightly
  22. // earlier); under-estimating leaves the popover clipped off the bottom (the
  23. // original bug at #1447).
  24. const DRYING_POPOVER_WIDTH = 240;
  25. const DRYING_POPOVER_ESTIMATED_HEIGHT = 320;
  26. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  27. import { useTranslation } from 'react-i18next';
  28. import { useTheme } from '../contexts/ThemeContext';
  29. import { useAuth } from '../contexts/AuthContext';
  30. import {
  31. Plus,
  32. Link,
  33. Unlink,
  34. Signal,
  35. Clock,
  36. MoreVertical,
  37. Trash2,
  38. RefreshCw,
  39. RotateCw,
  40. Box,
  41. HardDrive,
  42. AlertTriangle,
  43. AlertCircle,
  44. Terminal,
  45. Power,
  46. Zap,
  47. Wrench,
  48. ChevronDown,
  49. Eye,
  50. EyeOff,
  51. Filter,
  52. Pencil,
  53. ArrowLeft,
  54. ArrowRight,
  55. ArrowUp,
  56. ArrowDown,
  57. Layers,
  58. Video,
  59. Search,
  60. Loader2,
  61. Square,
  62. Pause,
  63. Play,
  64. X,
  65. Fan,
  66. Wind,
  67. AirVent,
  68. Download,
  69. ScanSearch,
  70. CheckCircle,
  71. CheckSquare,
  72. XCircle,
  73. User,
  74. Home,
  75. Printer as PrinterIcon,
  76. Info,
  77. Cable,
  78. Flame,
  79. Repeat,
  80. Snowflake,
  81. Gauge,
  82. DoorOpen,
  83. DoorClosed,
  84. Move,
  85. LogIn,
  86. LogOut,
  87. MoreHorizontal,
  88. SlidersHorizontal,
  89. Stethoscope,
  90. ScanEye,
  91. LineChart as LineChartIcon,
  92. LayoutGrid,
  93. MonitorPlay,
  94. ExternalLink,
  95. } from 'lucide-react';
  96. // Aliased: lucide-react already exports a `Link` icon into this module.
  97. import { Link as RouterLink, useNavigate } from 'react-router-dom';
  98. import { api, discoveryApi, firmwareApi, withStreamToken, ApiError } from '../api/client';
  99. import { formatDateOnly, formatETA, formatDuration, parseUTCDate } from '../utils/date';
  100. import type { Printer, PrinterCreate, PrinterStatus, AMSUnit, DiscoveredPrinter, FirmwareUpdateInfo, FirmwareUploadStatus, LinkedSpoolInfo, SpoolAssignment, HMSError, InventorySpool, SmartPlug, PrinterDiagnosticResult } from '../api/client';
  101. import { Card, CardContent } from '../components/Card';
  102. import { Button } from '../components/Button';
  103. import { ConfirmModal } from '../components/ConfirmModal';
  104. import { BulkPrinterToolbar, type PrinterState } from '../components/BulkPrinterToolbar';
  105. import { FileManagerModal } from '../components/FileManagerModal';
  106. import { EmbeddedCameraViewer } from '../components/EmbeddedCameraViewer';
  107. import { CameraWall } from '../components/CameraWall';
  108. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  109. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  110. import { AiDetectionModal } from '../components/AiDetectionModal';
  111. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  112. import { PrinterHASensorRow } from '../components/PrinterHASensorRow';
  113. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  114. import { AmsBackupModal } from '../components/AmsBackupModal';
  115. import { HeaterHistoryModal } from '../components/HeaterHistoryModal';
  116. import type { HeaterSensorKind } from '../api/client';
  117. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  118. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  119. import { AssignSpoolModal } from '../components/AssignSpoolModal';
  120. import { ConfigureAmsSlotModal } from '../components/ConfigureAmsSlotModal';
  121. import { useToast } from '../contexts/ToastContext';
  122. import { ChamberLight } from '../components/icons/ChamberLight';
  123. import { PlateClearedIcon } from '../components/icons/PlateClearedIcon';
  124. import { SkipObjectsModal, SkipObjectsIcon } from '../components/SkipObjectsModal';
  125. import { FileUploadModal } from '../components/FileUploadModal';
  126. import { PrintModal } from '../components/PrintModal';
  127. import { PrinterInfoModal } from '../components/PrinterInfoModal';
  128. import { getAmsLabel, getGlobalTrayId, getFillBarColor, getSpoolmanFillLevel, getFallbackSpoolTag, isBambuLabSpool, resolveSlotNozzleDiameter } from '../utils/amsHelpers';
  129. import { MAX_CHAMBER_TEMP_C, getPrinterImage, getWifiStrength, filterCompatibleQueueItems } from '../utils/printer';
  130. import { FilamentSlotCircle } from '../components/FilamentSlotCircle';
  131. import { Collapsible } from '../components/Collapsible';
  132. import { ConnectionDiagnosticModal, DiagnosticChecklist } from '../components/ConnectionDiagnostic';
  133. import { getColorName, parseFilamentColor, isLightColor } from '../utils/colors';
  134. // The status filter's options, and the only values it may hold. One list so a
  135. // saved filter cannot be validated against a set the dropdown has since moved
  136. // on from (#2833). Labels stay literal so they remain greppable.
  137. const STATUS_FILTER_OPTIONS = [
  138. { value: 'all', labelKey: 'printers.filter.allStatuses' },
  139. { value: 'printing', labelKey: 'printers.status.printing' },
  140. { value: 'paused', labelKey: 'printers.status.paused' },
  141. { value: 'idle', labelKey: 'printers.status.idle' },
  142. { value: 'finished', labelKey: 'printers.status.finished' },
  143. { value: 'error', labelKey: 'printers.status.error' },
  144. { value: 'offline', labelKey: 'printers.status.offline' },
  145. ] as const;
  146. function isKnownStatusFilter(value: string | null): boolean {
  147. return STATUS_FILTER_OPTIONS.some(option => option.value === value);
  148. }
  149. export interface SpoolmanSlotAssignmentRow {
  150. printer_id: number;
  151. ams_id: number;
  152. tray_id: number;
  153. spoolman_spool_id: number;
  154. }
  155. // Color names resolve via getColorName() which reads the backend color_catalog
  156. // (loaded once by ColorCatalogProvider). No hardcoded tables here — see #857.
  157. // Format K value with 3 decimal places, default to 0.020 if null
  158. function formatKValue(k: number | null | undefined): string {
  159. const value = k ?? 0.020;
  160. return value.toFixed(3);
  161. }
  162. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  163. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  164. const { mode } = useTheme();
  165. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  166. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  167. return (
  168. <span
  169. className="inline-flex items-center justify-center w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-[length:var(--pc-t10,10px)] font-bold rounded"
  170. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  171. >
  172. {side}
  173. </span>
  174. );
  175. }
  176. // Expand nozzle type codes to material names
  177. // Handles full text ("hardened_steel"), 2-char codes ("HS"/"HH"), and 4-char codes ("HS01")
  178. // Material mapping: 00=stainless steel, 01=hardened steel, 05=tungsten carbide
  179. function nozzleTypeName(type: string, t: (key: string) => string): string {
  180. if (!type) return '';
  181. // Full text names (from main nozzle info)
  182. if (type.includes('hardened')) return t('printers.nozzleHardenedSteel');
  183. if (type.includes('stainless')) return t('printers.nozzleStainlessSteel');
  184. if (type.includes('tungsten')) return t('printers.nozzleTungstenCarbide');
  185. // 4-char codes (e.g. "HS01"): last 2 digits = material
  186. if (type.length >= 4) {
  187. const material = type.slice(2, 4);
  188. if (material === '00') return t('printers.nozzleStainlessSteel');
  189. if (material === '01') return t('printers.nozzleHardenedSteel');
  190. if (material === '05') return t('printers.nozzleTungstenCarbide');
  191. }
  192. // 2-digit numeric codes
  193. if (type === '00') return t('printers.nozzleStainlessSteel');
  194. if (type === '01') return t('printers.nozzleHardenedSteel');
  195. if (type === '05') return t('printers.nozzleTungstenCarbide');
  196. // 2-char alpha codes: H prefix = hardened steel
  197. if (type.startsWith('H')) return t('printers.nozzleHardenedSteel');
  198. return type;
  199. }
  200. // Parse flow type from nozzle type code
  201. // HH = high flow, HS = standard/normal
  202. function nozzleFlowName(type: string, t: (key: string) => string): string {
  203. if (!type) return '';
  204. if (type.startsWith('HH')) return t('printers.nozzleHighFlow');
  205. if (type.startsWith('HS')) return t('printers.nozzleStandardFlow');
  206. return '';
  207. }
  208. // Per-slot hover card for nozzle rack
  209. // activeStatus: when true, show "Active" instead of "Mounted"/"Docked" (for hotend nozzles)
  210. function NozzleSlotHoverCard({ slot, index, activeStatus, filamentName, children }: {
  211. slot: import('../api/client').NozzleRackSlot;
  212. index: number;
  213. activeStatus?: boolean;
  214. filamentName?: string;
  215. children: React.ReactNode;
  216. }) {
  217. const { t } = useTranslation();
  218. const [isVisible, setIsVisible] = useState(false);
  219. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  220. const triggerRef = useRef<HTMLDivElement>(null);
  221. const cardRef = useRef<HTMLDivElement>(null);
  222. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  223. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  224. const isMounted = slot.stat === 1;
  225. useEffect(() => {
  226. if (isVisible && triggerRef.current && cardRef.current) {
  227. const triggerRect = triggerRef.current.getBoundingClientRect();
  228. const cardHeight = cardRef.current.offsetHeight;
  229. const headerHeight = 56;
  230. const spaceAbove = triggerRect.top - headerHeight;
  231. const spaceBelow = window.innerHeight - triggerRect.bottom;
  232. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  233. setPosition('bottom');
  234. } else {
  235. setPosition('top');
  236. }
  237. }
  238. }, [isVisible]);
  239. const handleMouseEnter = () => {
  240. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  241. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  242. };
  243. const handleMouseLeave = () => {
  244. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  245. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  246. };
  247. useEffect(() => {
  248. return () => {
  249. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  250. };
  251. }, []);
  252. const filamentCss = parseFilamentColor(slot.filament_color);
  253. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  254. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  255. return (
  256. <div
  257. ref={triggerRef}
  258. className="relative"
  259. onMouseEnter={handleMouseEnter}
  260. onMouseLeave={handleMouseLeave}
  261. >
  262. {children}
  263. {isVisible && (
  264. <div
  265. ref={cardRef}
  266. className={`
  267. absolute left-1/2 -translate-x-1/2 z-50
  268. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  269. animate-in fade-in-0 zoom-in-95 duration-150
  270. `}
  271. style={{ maxWidth: 'calc(100vw - 24px)' }}
  272. >
  273. <div className="w-44 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  274. {isEmpty ? (
  275. <div className="px-3 py-2 text-xs text-bambu-gray text-center whitespace-nowrap">
  276. Slot {index + 1} — Empty
  277. </div>
  278. ) : (
  279. <div className="p-2.5 space-y-1.5">
  280. {/* Diameter */}
  281. <div className="flex items-center justify-between">
  282. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleDiameter')}</span>
  283. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  284. </div>
  285. {/* Type */}
  286. {typeFull && (
  287. <div className="flex items-center justify-between">
  288. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleType')}</span>
  289. <span className="text-xs text-white font-semibold truncate max-w-[100px]">{typeFull}</span>
  290. </div>
  291. )}
  292. {/* Flow (hide if empty) */}
  293. {flowFull && (
  294. <div className="flex items-center justify-between">
  295. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFlow')}</span>
  296. <span className="text-xs text-white font-semibold">{flowFull}</span>
  297. </div>
  298. )}
  299. {/* Status badge */}
  300. <div className="flex items-center justify-between">
  301. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleStatus')}</span>
  302. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  303. activeStatus || isMounted
  304. ? 'bg-green-900/50 text-green-400'
  305. : 'bg-bambu-dark-tertiary text-bambu-gray'
  306. }`}>
  307. {activeStatus ? t('printers.nozzleActive') : isMounted ? t('printers.nozzleMounted') : t('printers.nozzleDocked')}
  308. </span>
  309. </div>
  310. {/* Wear (hide if null) */}
  311. {slot.wear != null && (
  312. <div className="flex items-center justify-between">
  313. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleWear')}</span>
  314. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  315. </div>
  316. )}
  317. {/* Max Temp (hide if 0) */}
  318. {slot.max_temp > 0 && (
  319. <div className="flex items-center justify-between">
  320. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleMaxTemp')}</span>
  321. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  322. </div>
  323. )}
  324. {/* Serial (hide if empty) */}
  325. {slot.serial_number && (
  326. <div className="flex items-center justify-between">
  327. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleSerial')}</span>
  328. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate max-w-[80px]">{slot.serial_number}</span>
  329. </div>
  330. )}
  331. {/* Filament: material type + color swatch (hide if no color) */}
  332. {(filamentCss || slot.filament_type) && (
  333. <div className="flex items-center justify-between">
  334. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{t('printers.nozzleFilament')}</span>
  335. <div className="flex items-center gap-1">
  336. {filamentCss && (
  337. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  338. )}
  339. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">{filamentName || slot.filament_type || slot.filament_id || ''}</span>
  340. </div>
  341. </div>
  342. )}
  343. </div>
  344. )}
  345. </div>
  346. {/* Arrow pointer */}
  347. <div
  348. className={`
  349. absolute left-1/2 -translate-x-1/2 w-0 h-0
  350. border-l-[6px] border-l-transparent
  351. border-r-[6px] border-r-transparent
  352. ${position === 'top'
  353. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  354. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  355. `}
  356. />
  357. </div>
  358. )}
  359. </div>
  360. );
  361. }
  362. // Dual-nozzle hover card showing L and R nozzle details side by side
  363. function DualNozzleHoverCard({ leftSlot, rightSlot, activeNozzle, filamentInfo, children }: {
  364. leftSlot?: import('../api/client').NozzleRackSlot;
  365. rightSlot?: import('../api/client').NozzleRackSlot;
  366. activeNozzle: 'L' | 'R';
  367. filamentInfo?: Record<string, { name: string; k: number | null }>;
  368. children: React.ReactNode;
  369. }) {
  370. const { t } = useTranslation();
  371. const [isVisible, setIsVisible] = useState(false);
  372. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  373. const triggerRef = useRef<HTMLDivElement>(null);
  374. const cardRef = useRef<HTMLDivElement>(null);
  375. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  376. useEffect(() => {
  377. if (isVisible && triggerRef.current && cardRef.current) {
  378. const triggerRect = triggerRef.current.getBoundingClientRect();
  379. const cardHeight = cardRef.current.offsetHeight;
  380. const headerHeight = 56;
  381. const spaceAbove = triggerRect.top - headerHeight;
  382. const spaceBelow = window.innerHeight - triggerRect.bottom;
  383. if (spaceAbove < cardHeight + 12 && spaceBelow > spaceAbove) {
  384. setPosition('bottom');
  385. } else {
  386. setPosition('top');
  387. }
  388. }
  389. }, [isVisible]);
  390. const handleMouseEnter = () => {
  391. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  392. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  393. };
  394. const handleMouseLeave = () => {
  395. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  396. timeoutRef.current = setTimeout(() => setIsVisible(false), 100);
  397. };
  398. useEffect(() => {
  399. return () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); };
  400. }, []);
  401. if (!leftSlot && !rightSlot) return <>{children}</>;
  402. const renderColumn = (slot: import('../api/client').NozzleRackSlot, side: 'L' | 'R') => {
  403. const isActive = activeNozzle === side;
  404. const typeFull = nozzleTypeName(slot.nozzle_type, t);
  405. const flowFull = nozzleFlowName(slot.nozzle_type, t);
  406. const filamentCss = parseFilamentColor(slot.filament_color);
  407. const filamentName = slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined;
  408. return (
  409. <div className="flex-1 space-y-1.5">
  410. <div className={`text-[length:var(--pc-t10,10px)] font-bold pb-1 border-b border-bambu-dark-tertiary/50 ${isActive ? 'text-amber-700 dark:text-amber-400' : 'text-bambu-gray'}`}>
  411. {side === 'L' ? t('common.left') : t('common.right')}
  412. </div>
  413. {slot.nozzle_diameter && (
  414. <div className="flex items-center justify-between">
  415. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleDiameter')}</span>
  416. <span className="text-xs text-white font-semibold">{slot.nozzle_diameter} mm</span>
  417. </div>
  418. )}
  419. {typeFull && (
  420. <div className="flex items-center justify-between">
  421. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleType')}</span>
  422. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{typeFull}</span>
  423. </div>
  424. )}
  425. {flowFull && (
  426. <div className="flex items-center justify-between">
  427. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFlow')}</span>
  428. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold">{flowFull}</span>
  429. </div>
  430. )}
  431. <div className="flex items-center justify-between">
  432. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleStatus')}</span>
  433. <span className={`text-[length:var(--pc-t10,10px)] font-bold px-1.5 py-0.5 rounded ${
  434. isActive
  435. ? 'bg-green-900/50 text-green-400'
  436. : 'bg-bambu-dark-tertiary text-bambu-gray'
  437. }`}>
  438. {isActive ? t('printers.nozzleActive') : t('printers.nozzleIdle')}
  439. </span>
  440. </div>
  441. {slot.wear != null && (
  442. <div className="flex items-center justify-between">
  443. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleWear')}</span>
  444. <span className="text-xs text-white font-semibold">{slot.wear}%</span>
  445. </div>
  446. )}
  447. {/* Serial and max temp only available on the right (removable) nozzle */}
  448. {side === 'R' && slot.max_temp > 0 && (
  449. <div className="flex items-center justify-between">
  450. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleMaxTemp')}</span>
  451. <span className="text-xs text-white font-semibold">{slot.max_temp}°C</span>
  452. </div>
  453. )}
  454. {side === 'R' && slot.serial_number && (
  455. <div className="flex items-center justify-between">
  456. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleSerial')}</span>
  457. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono">{slot.serial_number}</span>
  458. </div>
  459. )}
  460. {(filamentCss || slot.filament_type || slot.filament_id) && (
  461. <div className="flex items-center justify-between">
  462. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.nozzleFilament')}</span>
  463. <div className="flex items-center gap-1">
  464. {filamentCss && (
  465. <div className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] rounded-sm border border-white/20" style={{ backgroundColor: filamentCss }} />
  466. )}
  467. <span className="text-[length:var(--pc-t10,10px)] text-white font-semibold truncate max-w-[100px]">
  468. {filamentName || slot.filament_type || slot.filament_id || ''}
  469. </span>
  470. </div>
  471. </div>
  472. )}
  473. </div>
  474. );
  475. };
  476. return (
  477. <div
  478. ref={triggerRef}
  479. className="relative flex-1"
  480. onMouseEnter={handleMouseEnter}
  481. onMouseLeave={handleMouseLeave}
  482. >
  483. {children}
  484. {isVisible && (
  485. <div
  486. ref={cardRef}
  487. className={`
  488. absolute left-1/2 -translate-x-1/2 z-50
  489. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  490. animate-in fade-in-0 zoom-in-95 duration-150
  491. `}
  492. style={{ maxWidth: 'calc(100vw - 24px)' }}
  493. >
  494. <div className="w-96 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl overflow-hidden backdrop-blur-sm">
  495. <div className="p-2.5 flex gap-3">
  496. {leftSlot && renderColumn(leftSlot, 'L')}
  497. {leftSlot && rightSlot && <div className="w-px bg-bambu-dark-tertiary/50" />}
  498. {rightSlot && renderColumn(rightSlot, 'R')}
  499. </div>
  500. </div>
  501. {/* Arrow pointer */}
  502. <div
  503. className={`
  504. absolute left-1/2 -translate-x-1/2 w-0 h-0
  505. border-l-[6px] border-l-transparent
  506. border-r-[6px] border-r-transparent
  507. ${position === 'top'
  508. ? 'top-full border-t-[6px] border-t-bambu-dark-tertiary'
  509. : 'bottom-full border-b-[6px] border-b-bambu-dark-tertiary'}
  510. `}
  511. />
  512. </div>
  513. )}
  514. </div>
  515. );
  516. }
  517. // H2C Nozzle Rack Card — compact single row showing 6-position tool-changer dock
  518. function NozzleRackCard({ slots, filamentInfo }: { slots: import('../api/client').NozzleRackSlot[]; filamentInfo?: Record<string, { name: string; k: number | null }> }) {
  519. const { t } = useTranslation();
  520. // Rack nozzles only (IDs >= 2) — excludes L/R hotend nozzles (IDs 0, 1).
  521. // H2C rack slot IDs are fixed at 16..21. When a nozzle is picked up into the
  522. // hotend the firmware omits that rack ID entirely, so we must map by the fixed
  523. // base — computing it from min(present IDs) shifts everything left when slot 16
  524. // is the one currently mounted (#943).
  525. const rackNozzles = slots.filter(s => s.id >= 2);
  526. const RACK_SIZE = 6;
  527. const RACK_BASE_ID = 16;
  528. const rackSlots: (import('../api/client').NozzleRackSlot)[] = Array.from(
  529. { length: RACK_SIZE },
  530. (_, i) => rackNozzles.find(s => s.id === RACK_BASE_ID + i) ?? {
  531. id: -(i + 1), nozzle_type: '', nozzle_diameter: '', wear: null, stat: null,
  532. max_temp: 0, serial_number: '', filament_color: '', filament_id: '', filament_type: '',
  533. },
  534. );
  535. return (
  536. // Sized to its contents rather than growing: the six chips are a fixed
  537. // width at any one card size, so extra width would be dead space taken
  538. // from the temperature cards beside it — which are flex-1 with a 0 basis
  539. // and wrap their values ("220° / 220°") as soon as they lose it. Shrink
  540. // stays enabled so the card still gives way on a narrow printer card
  541. // instead of overflowing.
  542. <div className="text-center px-2.5 py-1.5 bg-bambu-dark rounded-lg flex-[0_1_auto] flex flex-col justify-center">
  543. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray mb-1">{t('printers.nozzleRack')}</p>
  544. <div className="flex gap-[3px] justify-center">
  545. {rackSlots.map((slot, i) => {
  546. const isEmpty = !slot.nozzle_diameter && !slot.nozzle_type;
  547. const filamentBg = !isEmpty ? parseFilamentColor(slot.filament_color) : null;
  548. const lightBg = filamentBg ? isLightColor(slot.filament_color) : false;
  549. return (
  550. <NozzleSlotHoverCard key={slot.id >= 0 ? slot.id : `empty-${i}`} slot={slot} index={i} filamentName={slot.filament_id ? filamentInfo?.[slot.filament_id]?.name : undefined}>
  551. <div className="flex flex-col items-center gap-0.5">
  552. <div
  553. className={`w-[var(--pc-i7,28px)] h-[var(--pc-i7,28px)] rounded flex items-center justify-center cursor-default transition-colors border-b-2 ${
  554. isEmpty
  555. ? 'bg-bambu-dark-tertiary/20 border-bambu-dark-tertiary/20'
  556. : 'bg-bambu-dark-tertiary/40 border-bambu-dark-tertiary/40'
  557. }`}
  558. style={filamentBg ? { backgroundColor: filamentBg } : undefined}
  559. >
  560. <span
  561. data-rack-diameter
  562. className={`text-[length:var(--pc-t10,10px)] font-semibold ${isEmpty ? 'text-bambu-gray/30' : lightBg ? 'text-black/80' : 'text-white'}`}
  563. style={filamentBg && !lightBg ? { textShadow: '0 1px 3px rgba(0,0,0,0.9)' } : undefined}
  564. >
  565. {isEmpty ? '—' : (slot.nozzle_diameter || '?')}
  566. </span>
  567. </div>
  568. {/* Physical rack position, so "swap the nozzle in slot 4" can be
  569. acted on without counting chips. Sits below the chip rather
  570. than inside it: the chip is barely wider than its own
  571. diameter text and already carries that over a
  572. filament-coloured background. */}
  573. <span className="text-[length:var(--pc-t8,8px)] leading-none tabular-nums text-bambu-gray/70">
  574. {i + 1}
  575. </span>
  576. </div>
  577. </NozzleSlotHoverCard>
  578. );
  579. })}
  580. </div>
  581. </div>
  582. );
  583. }
  584. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  585. function WaterDropEmpty({ className }: { className?: string }) {
  586. return (
  587. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  588. <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"/>
  589. </svg>
  590. );
  591. }
  592. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  593. function WaterDropHalf({ className }: { className?: string }) {
  594. return (
  595. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  596. <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"/>
  597. <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"/>
  598. </svg>
  599. );
  600. }
  601. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  602. function WaterDropFull({ className }: { className?: string }) {
  603. return (
  604. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  605. <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"/>
  606. <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"/>
  607. </svg>
  608. );
  609. }
  610. // Thermometer SVG - empty outline
  611. function ThermometerEmpty({ className }: { className?: string }) {
  612. return (
  613. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  614. <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"/>
  615. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  616. </svg>
  617. );
  618. }
  619. // Thermometer SVG - half filled (gold - same as humidity fair)
  620. function ThermometerHalf({ className }: { className?: string }) {
  621. return (
  622. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  623. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  624. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  625. <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"/>
  626. </svg>
  627. );
  628. }
  629. // Thermometer SVG - fully filled (red - same as humidity bad)
  630. function ThermometerFull({ className }: { className?: string }) {
  631. return (
  632. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  633. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  634. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  635. <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"/>
  636. </svg>
  637. );
  638. }
  639. // Nozzle icon - schematic hot-end view (filament body + heater block + tip).
  640. // Added for visual parity with the thermometer icons on the dual-nozzle card
  641. // that previously had no icon at all (#1115, design by @m4rtini2).
  642. function NozzleIcon({ className }: { className?: string }) {
  643. return (
  644. <svg
  645. className={className}
  646. viewBox="0 0 24 24"
  647. fill="none"
  648. xmlns="http://www.w3.org/2000/svg"
  649. stroke="currentColor"
  650. strokeWidth="1.5"
  651. strokeLinecap="round"
  652. strokeLinejoin="round"
  653. >
  654. <rect x="9.2" y="3.4" width="5.6" height="8.1" />
  655. <rect x="6" y="11.5" width="12.1" height="3.7" />
  656. <path d="M 7.3 15.2 L 12.1 19.6 L 16.7 15.2" />
  657. </svg>
  658. );
  659. }
  660. // Heater thermometer icon - filled when heating, outline when off
  661. interface HeaterThermometerProps {
  662. className?: string;
  663. color: string; // The color class (e.g., "text-orange-400")
  664. isHeating: boolean;
  665. }
  666. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  667. // Extract the actual color from Tailwind class for SVG fill
  668. const colorMap: Record<string, string> = {
  669. 'text-orange-400': '#fb923c',
  670. 'text-blue-400': '#60a5fa',
  671. 'text-green-400': '#4ade80',
  672. };
  673. const fillColor = colorMap[color] || '#888';
  674. // Glow style when heating
  675. const glowStyle = isHeating ? {
  676. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  677. } : {};
  678. if (isHeating) {
  679. // Filled thermometer with glow - heater is ON
  680. return (
  681. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  682. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  683. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  684. <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"/>
  685. </svg>
  686. );
  687. }
  688. // Empty thermometer - heater is OFF
  689. return (
  690. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  691. <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"/>
  692. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  693. </svg>
  694. );
  695. }
  696. // AMS Filament Backup tri-state indicator + toggle.
  697. // state=true → ON, click to disable
  698. // state=false → OFF, click opens modal
  699. // state=null → unknown/unsupported (e.g. A1 family), click disabled
  700. interface AmsBackupBadgeProps {
  701. state: boolean | null;
  702. onClick: () => void;
  703. }
  704. function AmsBackupBadge({ state, onClick }: AmsBackupBadgeProps) {
  705. const { t } = useTranslation();
  706. const known = state !== null;
  707. let className = 'flex items-center justify-center w-[18px] h-[18px] rounded text-[length:var(--pc-t10,10px)] transition-colors ';
  708. let title: string;
  709. if (state === true) {
  710. className += known
  711. ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-500/30 cursor-pointer'
  712. : 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 cursor-default';
  713. title = t('printers.amsBackup.titleOn');
  714. } else if (state === false) {
  715. className += known
  716. ? 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80 cursor-pointer'
  717. : 'bg-bambu-dark text-bambu-gray cursor-default';
  718. title = t('printers.amsBackup.titleOff');
  719. } else {
  720. className += 'bg-bambu-dark text-bambu-gray/50 cursor-default';
  721. title = t('printers.amsBackup.titleUnknown');
  722. }
  723. return (
  724. <button
  725. type="button"
  726. disabled={!known}
  727. onClick={() => known && onClick()}
  728. className={className}
  729. title={title}
  730. aria-label={title}
  731. >
  732. {known ? <Repeat className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <span>?</span>}
  733. </button>
  734. );
  735. }
  736. // Hide/show the external spool in the filament row (#1782). Sized and shaped
  737. // like AmsBackupBadge so the two sit together in the section header, but
  738. // pinned to the right-hand end of the rule: this is a view preference for the
  739. // row, not a property of the printer.
  740. interface ExternalSpoolToggleProps {
  741. hidden: boolean;
  742. onClick: () => void;
  743. }
  744. function ExternalSpoolToggle({ hidden, onClick }: ExternalSpoolToggleProps) {
  745. const { t } = useTranslation();
  746. const title = hidden ? t('printers.externalSpool.show') : t('printers.externalSpool.hide');
  747. return (
  748. <button
  749. type="button"
  750. onClick={onClick}
  751. aria-pressed={hidden}
  752. className={`flex items-center justify-center w-[18px] h-[18px] rounded transition-colors cursor-pointer ${
  753. hidden
  754. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  755. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  756. }`}
  757. title={title}
  758. aria-label={title}
  759. >
  760. {hidden ? <EyeOff className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Eye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  761. </button>
  762. );
  763. }
  764. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  765. // Reference: https://github.com/theicedmango/bambu-humidity
  766. interface HumidityIndicatorProps {
  767. humidity: number | string;
  768. goodThreshold?: number; // <= this is green
  769. fairThreshold?: number; // <= this is orange, > is red
  770. onClick?: () => void;
  771. compact?: boolean; // Smaller version for grid layout
  772. }
  773. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  774. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  775. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  776. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  777. // Status thresholds (configurable via settings)
  778. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  779. let textColor: string;
  780. let statusText: string;
  781. if (isNaN(humidityValue)) {
  782. textColor = '#C3C2C1';
  783. statusText = 'Unknown';
  784. } else if (humidityValue <= good) {
  785. textColor = '#22a352'; // Green - Good
  786. statusText = 'Good';
  787. } else if (humidityValue <= fair) {
  788. textColor = '#d4a017'; // Gold - Fair
  789. statusText = 'Fair';
  790. } else {
  791. textColor = '#c62828'; // Red - Bad
  792. statusText = 'Bad';
  793. }
  794. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  795. let DropComponent: React.FC<{ className?: string }>;
  796. if (isNaN(humidityValue)) {
  797. DropComponent = WaterDropEmpty;
  798. } else if (humidityValue <= good) {
  799. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  800. } else if (humidityValue <= fair) {
  801. DropComponent = WaterDropHalf; // Fair - half filled
  802. } else {
  803. DropComponent = WaterDropFull; // Bad - full (too humid)
  804. }
  805. return (
  806. <button
  807. type="button"
  808. onClick={onClick}
  809. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  810. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  811. >
  812. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  813. <span className={`font-medium tabular-nums ${compact ? 'text-[length:var(--pc-t10,10px)]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  814. </button>
  815. );
  816. }
  817. // Temperature indicator with dynamic icon and coloring
  818. interface TemperatureIndicatorProps {
  819. temp: number;
  820. goodThreshold?: number; // <= this is blue
  821. fairThreshold?: number; // <= this is orange, > is red
  822. onClick?: () => void;
  823. compact?: boolean; // Smaller version for grid layout
  824. }
  825. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  826. // Ensure thresholds are numbers
  827. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  828. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  829. let textColor: string;
  830. let statusText: string;
  831. let ThermoComponent: React.FC<{ className?: string }>;
  832. if (temp <= good) {
  833. textColor = '#22a352'; // Green - good (same as humidity)
  834. statusText = 'Good';
  835. ThermoComponent = ThermometerEmpty;
  836. } else if (temp <= fair) {
  837. textColor = '#d4a017'; // Gold - fair (same as humidity)
  838. statusText = 'Fair';
  839. ThermoComponent = ThermometerHalf;
  840. } else {
  841. textColor = '#c62828'; // Red - bad (same as humidity)
  842. statusText = 'Bad';
  843. ThermoComponent = ThermometerFull;
  844. }
  845. return (
  846. <button
  847. type="button"
  848. onClick={onClick}
  849. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  850. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  851. >
  852. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  853. <span className={`tabular-nums text-right ${compact ? 'text-[length:var(--pc-t10,10px)] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  854. </button>
  855. );
  856. }
  857. /** Classify an empty AMS slot for UI rendering (#1322 follow-up).
  858. *
  859. * "physical" — firmware positively confirmed no spool (state 9 or 10). The
  860. * bambu_mqtt handler now promotes tray_exist_bits=0 slots to state=9, so
  861. * every empty-by-bitmask slot lands here regardless of firmware payload
  862. * shape.
  863. *
  864. * "reset" — tray_type is missing/empty but firmware hasn't confirmed
  865. * emptiness (state is null, 3, or any non-9/10 value). Typically a slot
  866. * the user cleared with "Reset Slot" where a physical spool may still be
  867. * loaded but unassigned.
  868. *
  869. * Returns null when the slot is loaded (tray_type is present).
  870. */
  871. function getEmptySlotKind(tray: { tray_type?: string | null; state?: number | null; exists?: boolean | null } | null | undefined): 'physical' | 'reset' | null {
  872. if (tray?.tray_type) return null;
  873. // tray_exist_bits is firmware's authoritative presence signal: a non-RFID
  874. // spool the firmware can't identify is physically present (exists === true)
  875. // but carries no tray_type, so it must read as "?" (loaded, unconfigured),
  876. // never "Empty" (#2527). BambuStudio draws it the same way. Only fall back to
  877. // the state=9/10 heuristic when the bitmask was unavailable (exists == null).
  878. if (tray?.exists === true) return 'reset';
  879. if (tray?.exists === false) return 'physical';
  880. return (tray?.state === 9 || tray?.state === 10) ? 'physical' : 'reset';
  881. }
  882. // How long to wait for an AMS to report a live drying cycle after the printer
  883. // acked the start command (#2533). Firmware moves to DryStatus 1 (Checking)
  884. // within a couple of seconds; 30s covers the slowest observed push cadence
  885. // without leaving the user waiting on a verdict.
  886. const DRY_START_CONFIRM_MS = 30_000;
  887. export function CoverImage({
  888. url,
  889. printName,
  890. className = 'w-20 h-20',
  891. radiusClass = 'rounded-lg',
  892. }: {
  893. url: string | null;
  894. printName?: string;
  895. className?: string;
  896. radiusClass?: string;
  897. }) {
  898. const { t } = useTranslation();
  899. const [loaded, setLoaded] = useState(false);
  900. const [error, setError] = useState(false);
  901. const [showOverlay, setShowOverlay] = useState(false);
  902. const imgRef = useRef<HTMLImageElement>(null);
  903. // Cache-bust the image URL when the print name changes so the browser
  904. // fetches the new cover instead of serving the stale cached image.
  905. const cacheBustedUrl = useMemo(() => {
  906. if (!url) return null;
  907. const sep = url.includes('?') ? '&' : '?';
  908. return withStreamToken(`${url}${sep}v=${encodeURIComponent(printName || Date.now().toString())}`);
  909. }, [url, printName]);
  910. // Re-evaluate load state when the image URL changes, and ask the element
  911. // whether it is already showing something rather than assuming it is not.
  912. //
  913. // `onLoad` used to be the only thing that could set `loaded`, and this
  914. // effect reset it to false unconditionally. That is right when the URL
  915. // really changes, but it also runs on mount — and the two are not the same
  916. // situation (#2826). The URL is cache-busted on the print *name*, which is
  917. // constant for the duration of a print, so navigating away from the
  918. // printers page and back re-mounts with a byte-identical src that the
  919. // browser serves from its in-memory cache. The `load` event for a cache hit
  920. // and React's passive-effect flush are both plain tasks with no ordering
  921. // between them, so when `load` won, this effect ran afterwards and undid
  922. // it: `loaded` stayed false, the img stayed `hidden`, and the placeholder
  923. // sat there until a full reload. Nothing recovered it, because the URL
  924. // never changes again during the print and so this effect never re-runs.
  925. //
  926. // Being a race, it reproduced every time for #2826's reporter and not at
  927. // all here, which is also why the network panel showed no request: there
  928. // was no request to show.
  929. //
  930. // Asking `complete && naturalWidth > 0` settles it without needing to know
  931. // which of the two ran first. It is also correct for the case the reporter
  932. // proposed (a `load` that fires before React's handler is live), so the
  933. // fix stands whichever mechanism is really at work.
  934. useEffect(() => {
  935. setError(false);
  936. const el = imgRef.current;
  937. setLoaded(Boolean(el?.complete && el.naturalWidth > 0));
  938. }, [cacheBustedUrl]);
  939. return (
  940. <>
  941. <div
  942. className={`${className} flex-shrink-0 ${radiusClass} overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${cacheBustedUrl && loaded ? 'cursor-pointer' : ''}`}
  943. onClick={() => cacheBustedUrl && loaded && setShowOverlay(true)}
  944. >
  945. {cacheBustedUrl && !error ? (
  946. <>
  947. <img
  948. ref={imgRef}
  949. src={cacheBustedUrl}
  950. alt={t('printers.printPreview')}
  951. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  952. onLoad={() => setLoaded(true)}
  953. onError={() => setError(true)}
  954. />
  955. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  956. </>
  957. ) : (
  958. <Box className="w-8 h-8 text-bambu-gray" />
  959. )}
  960. </div>
  961. {/* Cover Image Overlay */}
  962. {showOverlay && cacheBustedUrl && (
  963. <div
  964. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  965. onClick={() => setShowOverlay(false)}
  966. >
  967. <div className="relative max-w-2xl max-h-full">
  968. <img
  969. src={cacheBustedUrl}
  970. alt={t('printers.printPreview')}
  971. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  972. />
  973. {printName && (
  974. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  975. )}
  976. </div>
  977. </div>
  978. )}
  979. </>
  980. );
  981. }
  982. interface PrinterMaintenanceInfo {
  983. due_count: number;
  984. warning_count: number;
  985. total_print_hours: number;
  986. }
  987. // Status summary bar component - uses queryClient to read cached statuses
  988. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  989. const { t } = useTranslation();
  990. const queryClient = useQueryClient();
  991. // Subscribe to query cache changes to re-render when status updates
  992. // Throttled to prevent rapid re-renders from causing tab crashes
  993. const [cacheTick, setCacheTick] = useState(0);
  994. useEffect(() => {
  995. let pending = false;
  996. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  997. if (!pending) {
  998. pending = true;
  999. requestAnimationFrame(() => {
  1000. setCacheTick(t => t + 1);
  1001. pending = false;
  1002. });
  1003. }
  1004. });
  1005. return () => unsubscribe();
  1006. }, [queryClient]);
  1007. const { counts, nextFinish } = useMemo(() => {
  1008. let printing = 0;
  1009. let paused = 0;
  1010. let finished = 0;
  1011. let idle = 0;
  1012. let offline = 0;
  1013. let loading = 0;
  1014. let error = 0;
  1015. let nextPrinterName: string | null = null;
  1016. let nextRemainingMin: number | null = null;
  1017. let nextProgress: number = 0;
  1018. printers?.forEach((printer) => {
  1019. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null; progress: number | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  1020. if (status === undefined) {
  1021. // Status not yet loaded - don't count as offline yet
  1022. loading++;
  1023. } else if (!status.connected) {
  1024. offline++;
  1025. } else {
  1026. // Count printers with active HMS errors as problems
  1027. const knownHmsCount =
  1028. status.hms_errors ? filterKnownHMSErrors(status.hms_errors).length : 0;
  1029. if (knownHmsCount > 0) {
  1030. error++;
  1031. }
  1032. switch (status.state) {
  1033. case 'RUNNING':
  1034. printing++;
  1035. if (status.remaining_time != null && status.remaining_time > 0) {
  1036. if (nextRemainingMin === null || status.remaining_time < nextRemainingMin) {
  1037. nextRemainingMin = status.remaining_time;
  1038. nextPrinterName = printer.name;
  1039. nextProgress = status.progress || 0;
  1040. }
  1041. }
  1042. break;
  1043. case 'PAUSE':
  1044. paused++;
  1045. break;
  1046. case 'FINISH':
  1047. finished++;
  1048. break;
  1049. case 'FAILED':
  1050. // FAILED is the printer's terminal gcode_state after a print stops —
  1051. // including user cancellations, where there's no actual fault. Only
  1052. // count it as a "problem" when an HMS error is also active; otherwise
  1053. // it's just a print that ended unsuccessfully and the plate needs
  1054. // clearing (same as FINISH from the operator's perspective).
  1055. if (knownHmsCount > 0) {
  1056. // Already counted above
  1057. } else {
  1058. finished++;
  1059. }
  1060. break;
  1061. default:
  1062. idle++;
  1063. break;
  1064. }
  1065. }
  1066. });
  1067. return {
  1068. counts: { printing, paused, finished, idle, offline, loading, error, total: (printers?.length || 0) },
  1069. nextFinish: nextPrinterName && nextRemainingMin ? { name: nextPrinterName, remainingMin: nextRemainingMin, progress: nextProgress } : null,
  1070. };
  1071. // eslint-disable-next-line react-hooks/exhaustive-deps
  1072. }, [printers, queryClient, cacheTick]);
  1073. if (!printers?.length) return null;
  1074. const badges: { count: number; dot: string; label: string }[] = [
  1075. { count: counts.printing, dot: 'bg-bambu-green animate-pulse', label: t('printers.status.printing').toLowerCase() },
  1076. { count: counts.paused, dot: 'bg-status-warning', label: t('printers.status.paused', 'paused').toLowerCase() },
  1077. { count: counts.finished, dot: 'bg-blue-400', label: t('printers.status.finished', 'finished').toLowerCase() },
  1078. { count: counts.idle, dot: counts.idle > 0 ? 'bg-bambu-green' : 'bg-gray-500', label: t('printers.status.available').toLowerCase() },
  1079. { count: counts.error, dot: 'bg-status-error', label: t('printers.status.problem').toLowerCase() },
  1080. { count: counts.offline, dot: 'bg-gray-400', label: t('printers.status.offline').toLowerCase() },
  1081. ];
  1082. return (
  1083. <div className="mt-1 flex flex-wrap items-center gap-4 gap-y-2 text-bambu-gray">
  1084. {badges.map(({ count, dot, label }) => count > 0 && (
  1085. <div key={label} className="flex items-center gap-1.5">
  1086. <div className={`w-2 h-2 rounded-full ${dot}`} />
  1087. <span className="text-bambu-gray">
  1088. <span className="text-white font-medium">{count}</span> {label}
  1089. </span>
  1090. </div>
  1091. ))}
  1092. {nextFinish && (
  1093. <>
  1094. <div className="w-px h-4 bg-bambu-dark-tertiary" />
  1095. <div className="flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
  1096. <div className="flex items-center gap-2">
  1097. <span className="text-bambu-green font-medium">{t('printers.nextAvailable')}:</span>
  1098. <span className="text-white font-medium">{nextFinish.name}</span>
  1099. </div>
  1100. <div className="flex items-center gap-2 w-full sm:w-auto">
  1101. <div className="w-full sm:w-16 bg-bambu-dark-tertiary rounded-full h-1.5">
  1102. <div
  1103. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1104. style={{ width: `${nextFinish.progress}%` }}
  1105. />
  1106. </div>
  1107. <span className="text-white font-medium">{Math.round(nextFinish.progress)}%</span>
  1108. <span className="text-bambu-gray">({formatDuration(nextFinish.remainingMin * 60)})</span>
  1109. </div>
  1110. </div>
  1111. </>
  1112. )}
  1113. </div>
  1114. );
  1115. }
  1116. type SortOption = 'name' | 'status' | 'model' | 'location' | 'eta';
  1117. type ViewMode = 'expanded' | 'compact';
  1118. type ToolbarDropdownOption<T extends string> = {
  1119. value: T;
  1120. label: string;
  1121. };
  1122. function ToolbarDropdown<T extends string>({
  1123. value,
  1124. options,
  1125. onChange,
  1126. fullWidth = false,
  1127. }: {
  1128. value: T;
  1129. options: ToolbarDropdownOption<T>[];
  1130. onChange: (value: T) => void;
  1131. fullWidth?: boolean;
  1132. }) {
  1133. const [isOpen, setIsOpen] = useState(false);
  1134. const selectedOption = options.find(option => option.value === value) ?? options[0];
  1135. return (
  1136. <div className={`relative ${fullWidth ? 'w-full min-w-0' : ''}`}>
  1137. <button
  1138. type="button"
  1139. onClick={() => setIsOpen(open => !open)}
  1140. 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'}`}
  1141. >
  1142. <span className="truncate">{selectedOption?.label}</span>
  1143. <ChevronDown className={`w-4 h-4 text-bambu-gray transition-transform ${isOpen ? 'rotate-180' : ''}`} />
  1144. </button>
  1145. {isOpen && (
  1146. <>
  1147. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1148. <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">
  1149. {options.map(option => (
  1150. <button
  1151. key={option.value}
  1152. type="button"
  1153. onClick={() => {
  1154. onChange(option.value);
  1155. setIsOpen(false);
  1156. }}
  1157. className={`w-full px-3 py-2 text-left text-sm transition-colors hover:bg-bambu-dark-tertiary ${
  1158. option.value === value ? 'text-bambu-green' : 'text-white'
  1159. }`}
  1160. >
  1161. {option.label}
  1162. </button>
  1163. ))}
  1164. </div>
  1165. </>
  1166. )}
  1167. </div>
  1168. );
  1169. }
  1170. function ToolbarMenu({
  1171. label,
  1172. icon,
  1173. children,
  1174. }: {
  1175. label: string;
  1176. icon: React.ReactNode;
  1177. children: React.ReactNode;
  1178. }) {
  1179. const [isOpen, setIsOpen] = useState(false);
  1180. return (
  1181. <div className="relative">
  1182. <button
  1183. type="button"
  1184. onClick={() => setIsOpen(open => !open)}
  1185. 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"
  1186. aria-label={label}
  1187. title={label}
  1188. >
  1189. {icon}
  1190. </button>
  1191. {isOpen && (
  1192. <>
  1193. <div className="fixed inset-0 z-10" onClick={() => setIsOpen(false)} />
  1194. <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">
  1195. {children}
  1196. </div>
  1197. </>
  1198. )}
  1199. </div>
  1200. );
  1201. }
  1202. function IndicatorControlPopover({
  1203. title,
  1204. options = [],
  1205. unit,
  1206. customMin,
  1207. customMax,
  1208. customStep = 1,
  1209. widthClass = 'w-[240px]',
  1210. popoverWidth = 240,
  1211. popoverHeight = 280,
  1212. isPending,
  1213. onClose,
  1214. onSubmit,
  1215. children,
  1216. }: {
  1217. title: string;
  1218. options?: Array<{ label: string; value: number }>;
  1219. unit?: string;
  1220. customMin?: number;
  1221. customMax?: number;
  1222. customStep?: number;
  1223. widthClass?: string;
  1224. popoverWidth?: number;
  1225. popoverHeight?: number;
  1226. isPending?: boolean;
  1227. onClose: () => void;
  1228. onSubmit?: (value: number) => void;
  1229. children?: React.ReactNode;
  1230. }) {
  1231. const anchorRef = useRef<HTMLSpanElement>(null);
  1232. const [coords, setCoords] = useState<{ top: number; left: number } | null>(null);
  1233. const [customValue, setCustomValue] = useState('');
  1234. // Anchor to the trigger (the popover's DOM parent before portaling) so we
  1235. // can position via fixed coords. Portaling to document.body escapes
  1236. // ancestor stacking contexts — sibling PrinterCard wrappers create their
  1237. // own contexts and would otherwise cover the popover even at z-[60].
  1238. useLayoutEffect(() => {
  1239. const trigger = anchorRef.current?.parentElement;
  1240. if (!trigger) return;
  1241. const measure = () => {
  1242. const rect = trigger.getBoundingClientRect();
  1243. setCoords(computePopoverPosition({
  1244. triggerRect: rect,
  1245. popoverWidth,
  1246. estimatedHeight: popoverHeight,
  1247. horizontalAlign: 'center',
  1248. }));
  1249. };
  1250. measure();
  1251. window.addEventListener('resize', measure);
  1252. window.addEventListener('scroll', measure, true);
  1253. return () => {
  1254. window.removeEventListener('resize', measure);
  1255. window.removeEventListener('scroll', measure, true);
  1256. };
  1257. }, [popoverWidth, popoverHeight]);
  1258. const showCustomInput = unit !== undefined;
  1259. const submitCustom = () => {
  1260. const value = Number(customValue);
  1261. if (!Number.isFinite(value)) return;
  1262. const bounded = Math.min(customMax ?? value, Math.max(customMin ?? value, value));
  1263. onSubmit?.(Math.round(bounded));
  1264. };
  1265. return (
  1266. <>
  1267. <span ref={anchorRef} className="hidden" aria-hidden="true" />
  1268. {createPortal(
  1269. <>
  1270. <div className="fixed inset-0 z-[1000]" onClick={onClose} />
  1271. <div
  1272. className={`fixed z-[1001] flex ${widthClass} flex-col overflow-hidden rounded-xl border border-bambu-dark-tertiary bg-bambu-dark-secondary shadow-2xl`}
  1273. style={{
  1274. top: coords?.top ?? -9999,
  1275. left: coords?.left ?? -9999,
  1276. visibility: coords ? 'visible' : 'hidden',
  1277. }}
  1278. onClick={e => e.stopPropagation()}
  1279. >
  1280. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">{title}</div>
  1281. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1282. {options.length > 0 && (
  1283. <div className="px-3 py-2.5">
  1284. <div className="grid grid-cols-2 gap-1.5">
  1285. {options.map(option => (
  1286. <button
  1287. key={`${option.label}-${option.value}`}
  1288. type="button"
  1289. disabled={isPending}
  1290. onClick={() => onSubmit?.(option.value)}
  1291. 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"
  1292. >
  1293. {option.label}
  1294. </button>
  1295. ))}
  1296. </div>
  1297. </div>
  1298. )}
  1299. {children}
  1300. {showCustomInput && (
  1301. <>
  1302. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  1303. <form
  1304. className="flex gap-1.5 px-3 pt-2.5 pb-3"
  1305. onSubmit={(e) => {
  1306. e.preventDefault();
  1307. submitCustom();
  1308. }}
  1309. >
  1310. <input
  1311. type="number"
  1312. min={customMin}
  1313. max={customMax}
  1314. step={customStep}
  1315. value={customValue}
  1316. onChange={e => setCustomValue(e.target.value)}
  1317. placeholder="Custom"
  1318. 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"
  1319. />
  1320. <button
  1321. type="submit"
  1322. disabled={isPending || customValue.trim() === ''}
  1323. 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"
  1324. >
  1325. Set
  1326. </button>
  1327. </form>
  1328. </>
  1329. )}
  1330. </div>
  1331. </>,
  1332. document.body
  1333. )}
  1334. </>
  1335. );
  1336. }
  1337. const NOZZLE_TEMPERATURE_OPTIONS = buildPresetOptions(NOZZLE_TEMP_DEFAULTS, 'C');
  1338. function NozzleTemperatureControlBox({
  1339. label,
  1340. current,
  1341. target,
  1342. isActive,
  1343. isPending,
  1344. onSubmit,
  1345. options = NOZZLE_TEMPERATURE_OPTIONS,
  1346. }: {
  1347. label: string;
  1348. current?: number;
  1349. target?: number;
  1350. isActive: boolean;
  1351. isPending?: boolean;
  1352. onSubmit: (value: number) => void;
  1353. options?: Array<{ label: string; value: number }>;
  1354. }) {
  1355. const [customValue, setCustomValue] = useState('');
  1356. const submitCustom = () => {
  1357. const value = Number(customValue);
  1358. if (!Number.isFinite(value)) return;
  1359. onSubmit(Math.min(320, Math.max(0, Math.round(value))));
  1360. };
  1361. return (
  1362. <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'}`}>
  1363. <div className="mb-1.5 flex items-center justify-between gap-2">
  1364. <span className={`text-xs font-medium ${isActive ? 'text-amber-700 dark:text-amber-300' : 'text-white'}`}>{label}</span>
  1365. <span className="text-[10px] text-bambu-gray">
  1366. {Math.round(current ?? 0)}°C
  1367. {target !== undefined ? ` / ${Math.round(target)}°` : ''}
  1368. </span>
  1369. </div>
  1370. <div className="grid grid-cols-2 gap-1">
  1371. {options.map(option => (
  1372. <button
  1373. key={`${label}-${option.value}`}
  1374. type="button"
  1375. disabled={isPending}
  1376. onClick={() => onSubmit(option.value)}
  1377. 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"
  1378. >
  1379. {option.label}
  1380. </button>
  1381. ))}
  1382. </div>
  1383. <form
  1384. className="mt-1.5 flex gap-1"
  1385. onSubmit={(e) => {
  1386. e.preventDefault();
  1387. submitCustom();
  1388. }}
  1389. >
  1390. <input
  1391. type="number"
  1392. min={0}
  1393. max={320}
  1394. step={1}
  1395. value={customValue}
  1396. onChange={e => setCustomValue(e.target.value)}
  1397. placeholder="Custom"
  1398. 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"
  1399. />
  1400. <button
  1401. type="submit"
  1402. disabled={isPending || customValue.trim() === ''}
  1403. 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"
  1404. >
  1405. Set
  1406. </button>
  1407. </form>
  1408. </div>
  1409. );
  1410. }
  1411. const STATUS_GROUP_ORDER: string[] = ['error', 'printing', 'paused', 'finished', 'idle', 'offline'];
  1412. const STATUS_GROUP_META: Record<string, { labelKey: string; dot: string }> = {
  1413. error: { labelKey: 'printers.status.problem', dot: 'bg-status-error' },
  1414. printing: { labelKey: 'printers.status.printing', dot: 'bg-bambu-green animate-pulse' },
  1415. paused: { labelKey: 'printers.status.paused', dot: 'bg-status-warning' },
  1416. finished: { labelKey: 'printers.status.finished', dot: 'bg-blue-400' },
  1417. idle: { labelKey: 'printers.status.idle', dot: 'bg-bambu-green' },
  1418. offline: { labelKey: 'printers.status.offline', dot: 'bg-gray-400' },
  1419. };
  1420. /** Classify a printer into one of the UI status buckets. */
  1421. function classifyPrinterStatus(
  1422. status: { connected: boolean; state: string | null; hms_errors?: HMSError[] } | undefined,
  1423. ): PrinterState {
  1424. if (!status?.connected) return 'offline';
  1425. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1426. if (hmsErrors.length > 0) return 'error';
  1427. switch (status.state) {
  1428. case 'RUNNING': return 'printing';
  1429. case 'PAUSE': return 'paused';
  1430. case 'FINISH': return 'finished';
  1431. // FAILED without an active HMS error is the printer's terminal state after
  1432. // any unsuccessful end — including user-cancellations. Treat the same as
  1433. // FINISH for grouping/badging purposes; only escalate to "error" when an
  1434. // HMS code is actually attached (handled by the early-return above).
  1435. case 'FAILED': return 'finished';
  1436. default: return 'idle';
  1437. }
  1438. }
  1439. /**
  1440. * Get human-readable status display text for a printer.
  1441. * Uses stg_cur_name for detailed calibration/preparation stages,
  1442. * otherwise formats the gcode_state nicely.
  1443. */
  1444. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  1445. // If we have a specific stage name (calibration, heating, etc.), use it
  1446. if (stg_cur_name) {
  1447. return stg_cur_name;
  1448. }
  1449. // Format the gcode_state nicely
  1450. switch (state) {
  1451. case 'RUNNING':
  1452. return 'Printing';
  1453. case 'PAUSE':
  1454. return 'Paused';
  1455. case 'FINISH':
  1456. return 'Finished';
  1457. case 'FAILED':
  1458. return 'Failed';
  1459. case 'IDLE':
  1460. return 'Idle';
  1461. default:
  1462. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  1463. }
  1464. }
  1465. // Bambu models that ship with an enclosure chamber fan (firmware field
  1466. // `big_fan2_speed`). Open-frame models (A1 / A1 Mini / A2L / P1P) have no
  1467. // chamber fan — `big_fan2_speed` is meaningless / always 0 there, so the
  1468. // widget is hidden in fanItems instead of rendered greyed-out.
  1469. const MODELS_WITH_CHAMBER_FAN: ReadonlySet<string> = new Set([
  1470. 'X1C',
  1471. 'X1',
  1472. 'X1E',
  1473. 'X2D',
  1474. 'P1S',
  1475. 'P2S',
  1476. 'H2D',
  1477. 'H2D Pro',
  1478. 'H2C',
  1479. 'H2S',
  1480. ]);
  1481. // On the P2S/X2D, the enclosure fan (big_fan2 / airduct part id 3) is a
  1482. // dedicated chamber EXHAUST fan: it's its own control and stays the same
  1483. // regardless of cooling/heating mode (unlike the aux fan, id 2, which a flap
  1484. // re-tasks between part-cooling and chamber-filter recirculation). Bambu's own
  1485. // firmware/UI and Bambu Studio (FAN_CHAMBER_0_IDX -> "Exhaust") label it
  1486. // "Exhaust" on these models. Other enclosed models (X1/P1S/H2*) keep "Chamber".
  1487. const MODELS_WITH_EXHAUST_LABEL: ReadonlySet<string> = new Set([
  1488. 'P2S',
  1489. 'X2D',
  1490. ]);
  1491. // Map SSDP model codes to display names
  1492. function mapModelCode(ssdpModel: string | null): string {
  1493. if (!ssdpModel) return '';
  1494. const modelMap: Record<string, string> = {
  1495. // H2 Series
  1496. 'O1D': 'H2D',
  1497. 'O1E': 'H2D Pro',
  1498. 'O2D': 'H2D Pro',
  1499. 'O1C': 'H2C',
  1500. 'O1C2': 'H2C',
  1501. 'O1S': 'H2S',
  1502. // X1 Series
  1503. 'BL-P001': 'X1C',
  1504. 'BL-P002': 'X1',
  1505. 'BL-P003': 'X1E',
  1506. // X2 Series
  1507. 'N6': 'X2D',
  1508. // A2 Series
  1509. 'N9': 'A2L',
  1510. // P Series
  1511. 'C11': 'P1S',
  1512. 'C12': 'P1P',
  1513. 'C13': 'P2S',
  1514. // A1 Series
  1515. 'N2S': 'A1',
  1516. 'N1': 'A1 Mini',
  1517. // Direct matches
  1518. 'X1C': 'X1C',
  1519. 'X1': 'X1',
  1520. 'X1E': 'X1E',
  1521. 'X2D': 'X2D',
  1522. 'P1S': 'P1S',
  1523. 'P1P': 'P1P',
  1524. 'P2S': 'P2S',
  1525. 'A1': 'A1',
  1526. 'A1 Mini': 'A1 Mini',
  1527. 'A2L': 'A2L',
  1528. 'H2D': 'H2D',
  1529. 'H2D Pro': 'H2D Pro',
  1530. 'H2C': 'H2C',
  1531. 'H2S': 'H2S',
  1532. };
  1533. return modelMap[ssdpModel] || ssdpModel;
  1534. }
  1535. // ─── AMS Name Hover Card ──────────────────────────────────────────────────────
  1536. // Wraps the AMS label (e.g. "AMS-A") and shows a popup with:
  1537. // • User-defined friendly name (editable, protected by printers:update)
  1538. // • AMS serial number
  1539. // • AMS firmware version
  1540. export function AmsNameHoverCard({
  1541. ams,
  1542. printerId,
  1543. label,
  1544. amsLabels,
  1545. canEdit,
  1546. onSaved,
  1547. children,
  1548. }: {
  1549. ams: import('../api/client').AMSUnit;
  1550. printerId: number;
  1551. label: string; // auto-generated label, e.g. "AMS-A"
  1552. amsLabels?: Record<number, string>;
  1553. canEdit: boolean;
  1554. onSaved: () => void;
  1555. children: React.ReactNode;
  1556. }) {
  1557. const { t } = useTranslation();
  1558. const [isVisible, setIsVisible] = useState(false);
  1559. const [position, setPosition] = useState<'top' | 'bottom'>('top');
  1560. const [editValue, setEditValue] = useState('');
  1561. const [isSaving, setIsSaving] = useState(false);
  1562. const [saveError, setSaveError] = useState<string | null>(null);
  1563. const [isInputFocused, setIsInputFocused] = useState(false);
  1564. const triggerRef = useRef<HTMLDivElement>(null);
  1565. const cardRef = useRef<HTMLDivElement>(null);
  1566. const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1567. useEffect(() => {
  1568. if (isVisible) {
  1569. setEditValue(amsLabels?.[ams.id] ?? '');
  1570. setSaveError(null);
  1571. requestAnimationFrame(() => {
  1572. if (triggerRef.current && cardRef.current) {
  1573. const rect = triggerRef.current.getBoundingClientRect();
  1574. const spaceAbove = rect.top - 56;
  1575. const spaceBelow = window.innerHeight - rect.bottom;
  1576. setPosition(spaceAbove < cardRef.current.offsetHeight + 12 && spaceBelow > spaceAbove ? 'bottom' : 'top');
  1577. }
  1578. });
  1579. }
  1580. }, [isVisible, amsLabels, ams.id]);
  1581. const handleMouseEnter = () => {
  1582. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1583. timeoutRef.current = setTimeout(() => setIsVisible(true), 80);
  1584. };
  1585. const handleMouseLeave = () => {
  1586. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1587. if (!isInputFocused) {
  1588. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1589. }
  1590. };
  1591. useEffect(() => () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); }, []);
  1592. const handleSave = async () => {
  1593. if (!canEdit) return;
  1594. setIsSaving(true);
  1595. setSaveError(null);
  1596. try {
  1597. const trimmed = editValue.trim();
  1598. if (trimmed) {
  1599. await api.saveAmsLabel(printerId, ams.id, trimmed, ams.serial_number);
  1600. } else {
  1601. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1602. }
  1603. onSaved();
  1604. setIsVisible(false);
  1605. } catch (err) {
  1606. setSaveError(err instanceof Error ? err.message : String(err));
  1607. } finally {
  1608. setIsSaving(false);
  1609. }
  1610. };
  1611. const handleClear = async () => {
  1612. if (!canEdit) return;
  1613. setIsSaving(true);
  1614. setSaveError(null);
  1615. try {
  1616. await api.deleteAmsLabel(printerId, ams.id, ams.serial_number);
  1617. onSaved();
  1618. setIsVisible(false);
  1619. } catch (err) {
  1620. setSaveError(err instanceof Error ? err.message : String(err));
  1621. } finally {
  1622. setIsSaving(false);
  1623. }
  1624. };
  1625. return (
  1626. <div
  1627. ref={triggerRef}
  1628. className="relative inline-block"
  1629. onMouseEnter={handleMouseEnter}
  1630. onMouseLeave={handleMouseLeave}
  1631. >
  1632. {children}
  1633. {isVisible && (
  1634. <div
  1635. ref={cardRef}
  1636. className={`
  1637. absolute left-0 z-50
  1638. ${position === 'top' ? 'bottom-full mb-2' : 'top-full mt-2'}
  1639. animate-in fade-in-0 zoom-in-95 duration-150
  1640. `}
  1641. style={{ maxWidth: 'calc(100vw - 24px)' }}
  1642. onMouseEnter={handleMouseEnter}
  1643. onMouseLeave={handleMouseLeave}
  1644. >
  1645. <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">
  1646. {/* AMS auto-label */}
  1647. <div className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">{label}</div>
  1648. {/* Serial number */}
  1649. <div className="flex items-center justify-between gap-2">
  1650. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1651. {t('printers.amsPopup.serialNumber')}
  1652. </span>
  1653. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.serial_number || '—'}</span>
  1654. </div>
  1655. {/* Firmware version */}
  1656. <div className="flex items-center justify-between gap-2">
  1657. <span className="text-[length:var(--pc-t10,10px)] tracking-wide text-bambu-gray font-medium shrink-0">
  1658. {t('printers.amsPopup.firmwareVersion')}
  1659. </span>
  1660. <span className="text-[length:var(--pc-t10,10px)] text-white font-mono truncate">{ams.sw_ver || '—'}</span>
  1661. </div>
  1662. {/* Friendly name editor */}
  1663. <div className="space-y-1">
  1664. <div className="flex items-center gap-2">
  1665. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray font-medium shrink-0">
  1666. {t('printers.amsPopup.friendlyName')}
  1667. </span>
  1668. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary/50" />
  1669. </div>
  1670. <input
  1671. type="text"
  1672. value={editValue}
  1673. onChange={(e) => canEdit && setEditValue(e.target.value)}
  1674. onKeyDown={(e) => e.key === 'Enter' && handleSave()}
  1675. onFocus={() => setIsInputFocused(true)}
  1676. onBlur={() => {
  1677. setIsInputFocused(false);
  1678. if (timeoutRef.current) clearTimeout(timeoutRef.current);
  1679. timeoutRef.current = setTimeout(() => setIsVisible(false), 200);
  1680. }}
  1681. placeholder={canEdit ? t('printers.amsPopup.friendlyNamePlaceholder') : (amsLabels?.[ams.id] || '—')}
  1682. disabled={!canEdit}
  1683. title={!canEdit ? t('printers.amsPopup.noEditPermission') : undefined}
  1684. 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"
  1685. maxLength={100}
  1686. />
  1687. {canEdit && (
  1688. <div className="space-y-1">
  1689. {saveError && (
  1690. <p className="text-[length:var(--pc-t10,10px)] text-red-700 dark:text-red-400 break-words">{saveError}</p>
  1691. )}
  1692. <div className="flex gap-1 justify-end">
  1693. <button
  1694. onClick={handleSave}
  1695. disabled={isSaving}
  1696. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-green text-white rounded hover:bg-bambu-green/80 disabled:opacity-50"
  1697. >
  1698. {t('printers.amsPopup.save')}
  1699. </button>
  1700. {amsLabels?.[ams.id] && (
  1701. <button
  1702. onClick={handleClear}
  1703. disabled={isSaving}
  1704. className="px-2 py-0.5 text-[length:var(--pc-t10,10px)] bg-bambu-dark-tertiary text-bambu-gray rounded hover:bg-bambu-dark-tertiary/70 disabled:opacity-50"
  1705. >
  1706. {t('printers.amsPopup.clear')}
  1707. </button>
  1708. )}
  1709. </div>
  1710. </div>
  1711. )}
  1712. </div>
  1713. </div>
  1714. </div>
  1715. )}
  1716. </div>
  1717. );
  1718. }
  1719. // AMS drying presets from BambuStudio filament profiles (idle mode temps)
  1720. // Format: { n3f temp, n3s temp, n3f hours, n3s hours }
  1721. const DRYING_PRESETS: Record<string, DryingPreset> = {
  1722. 'PLA': { n3f: 45, n3s: 45, n3f_hours: 12, n3s_hours: 12 },
  1723. 'PETG': { n3f: 65, n3s: 65, n3f_hours: 12, n3s_hours: 12 },
  1724. 'TPU': { n3f: 65, n3s: 75, n3f_hours: 12, n3s_hours: 18 },
  1725. 'ABS': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1726. 'ASA': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1727. 'PA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 12 },
  1728. 'PC': { n3f: 65, n3s: 80, n3f_hours: 12, n3s_hours: 8 },
  1729. 'PVA': { n3f: 65, n3s: 85, n3f_hours: 12, n3s_hours: 18 },
  1730. };
  1731. // How much the printer card's body type and icons grow at each card size
  1732. // (#1848). S is the dense fleet view and M is the default, so both stay at
  1733. // 1.0 and an existing install looks identical until the user picks L or XL --
  1734. // the same control the request asked to have this follow.
  1735. const CARD_BODY_SCALE: Record<number, number> = { 1: 1, 2: 1, 3: 1.2, 4: 1.4 };
  1736. // The scaled sizes, handed to the card subtree as custom properties. Every
  1737. // converted class names its old fixed value as the fallback, so anything that
  1738. // renders outside a card root -- the portalled temperature popover -- keeps
  1739. // exactly the size it has today.
  1740. function buildCardScaleStyle(cardSize: number): React.CSSProperties {
  1741. const scale = CARD_BODY_SCALE[cardSize] ?? 1;
  1742. // Rounded to a tenth so the values stay readable in devtools.
  1743. const px = (base: number) => `${Math.round(base * scale * 10) / 10}px`;
  1744. return {
  1745. '--pc-t8': px(8),
  1746. '--pc-t9': px(9),
  1747. '--pc-t10': px(10),
  1748. '--pc-t11': px(11),
  1749. '--pc-i2': px(8),
  1750. '--pc-i25': px(10),
  1751. '--pc-i3': px(12),
  1752. '--pc-i35': px(14),
  1753. '--pc-i4': px(16),
  1754. '--pc-i5': px(20),
  1755. '--pc-i7': px(28),
  1756. } as React.CSSProperties;
  1757. }
  1758. function PrinterCard({
  1759. printer,
  1760. hideIfDisconnected,
  1761. maintenanceInfo,
  1762. viewMode = 'expanded',
  1763. cardSize = 2,
  1764. amsThresholds,
  1765. spoolmanEnabled = false,
  1766. linkedSpools,
  1767. spoolmanUrl,
  1768. spoolmanSyncMode,
  1769. onGetAssignment,
  1770. onUnassignSpool,
  1771. spoolmanSpools,
  1772. spoolmanSlotAssignments,
  1773. spoolmanLoading = false,
  1774. onUnassignSpoolmanSpool,
  1775. timeFormat = 'system',
  1776. cameraViewMode = 'window',
  1777. onOpenEmbeddedCamera,
  1778. checkPrinterFirmware = true,
  1779. dryingPresets = DRYING_PRESETS,
  1780. requirePlateClear = false,
  1781. selectionMode = false,
  1782. isSelected = false,
  1783. onToggleSelect,
  1784. onOpenCompactCard,
  1785. nozzleTempPresets = NOZZLE_TEMP_DEFAULTS,
  1786. bedTempPresets = BED_TEMP_DEFAULTS,
  1787. chamberTempPresets = CHAMBER_TEMP_DEFAULTS,
  1788. fanSpeedPresets = FAN_SPEED_DEFAULTS,
  1789. aiDetectionEnabled = false,
  1790. aiDetection,
  1791. aiLastError = null,
  1792. }: {
  1793. printer: Printer;
  1794. hideIfDisconnected?: boolean;
  1795. maintenanceInfo?: PrinterMaintenanceInfo;
  1796. viewMode?: ViewMode;
  1797. cardSize?: number;
  1798. amsThresholds?: {
  1799. humidityGood: number;
  1800. humidityFair: number;
  1801. tempGood: number;
  1802. tempFair: number;
  1803. };
  1804. spoolmanEnabled?: boolean;
  1805. hasUnlinkedSpools?: boolean;
  1806. linkedSpools?: Record<string, LinkedSpoolInfo>;
  1807. spoolmanUrl?: string | null;
  1808. spoolmanSyncMode?: string | null;
  1809. spoolAssignments?: SpoolAssignment[];
  1810. onGetAssignment?: (printerId: number, amsId: number, trayId: number) => SpoolAssignment | undefined;
  1811. onUnassignSpool?: (printerId: number, amsId: number, trayId: number) => void;
  1812. spoolmanSpools?: InventorySpool[];
  1813. spoolmanSlotAssignments?: SpoolmanSlotAssignmentRow[];
  1814. spoolmanLoading?: boolean;
  1815. onUnassignSpoolmanSpool?: (spoolmanSpoolId: number) => void;
  1816. timeFormat?: 'system' | '12h' | '24h';
  1817. cameraViewMode?: 'window' | 'embedded';
  1818. onOpenEmbeddedCamera?: (printerId: number, printerName: string) => void;
  1819. checkPrinterFirmware?: boolean;
  1820. dryingPresets?: Record<string, DryingPreset>;
  1821. requirePlateClear?: boolean;
  1822. selectionMode?: boolean;
  1823. isSelected?: boolean;
  1824. onToggleSelect?: (id: number) => void;
  1825. onOpenCompactCard?: (id: number) => void;
  1826. nozzleTempPresets?: readonly [number, number, number];
  1827. bedTempPresets?: readonly [number, number, number];
  1828. chamberTempPresets?: readonly [number, number, number];
  1829. fanSpeedPresets?: readonly [number, number, number];
  1830. aiDetectionEnabled?: boolean;
  1831. aiDetection?: { class: string; frame_count: number; score: number };
  1832. aiLastError?: string | null;
  1833. }) {
  1834. const { t } = useTranslation();
  1835. const queryClient = useQueryClient();
  1836. const navigate = useNavigate();
  1837. const { showToast } = useToast();
  1838. const { hasPermission } = useAuth();
  1839. const [showMenu, setShowMenu] = useState(false);
  1840. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  1841. const [deleteArchives, setDeleteArchives] = useState(true);
  1842. const [showEditModal, setShowEditModal] = useState(false);
  1843. const [showFileManager, setShowFileManager] = useState(false);
  1844. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  1845. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  1846. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  1847. const [haToggleConfirm, setHaToggleConfirm] = useState<SmartPlug | null>(null);
  1848. const [showHMSModal, setShowHMSModal] = useState(false);
  1849. // #1546: AI failure detection modal — opens from the AI badge.
  1850. const [showAiModal, setShowAiModal] = useState(false);
  1851. // #1762: AMS Filament Backup status / control modal — opens from the badge.
  1852. const [amsBackupModalOpen, setAmsBackupModalOpen] = useState(false);
  1853. // External spool visibility (#1782) — browser-local, per printer. Read once
  1854. // per card; the toggle that writes it is the only thing that changes it.
  1855. const [externalSpoolHidden, setExternalSpoolHidden] = useState(() =>
  1856. isExternalSpoolHidden(printer.id),
  1857. );
  1858. const toggleExternalSpool = useCallback(() => {
  1859. setExternalSpoolHidden((prev) => {
  1860. const next = !prev;
  1861. persistExternalSpoolHidden(printer.id, next);
  1862. return next;
  1863. });
  1864. }, [printer.id]);
  1865. const [showStopConfirm, setShowStopConfirm] = useState(false);
  1866. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  1867. const [showSpeedMenu, setShowSpeedMenu] = useState<number | null>(null);
  1868. const [showAirductMenu, setShowAirductMenu] = useState<number | null>(null);
  1869. const [showBedJogMenu, setShowBedJogMenu] = useState<number | null>(null);
  1870. const [statusControlMenu, setStatusControlMenu] = useState<string | null>(null);
  1871. const [bedJogStep, setBedJogStep] = useState<number>(10);
  1872. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  1873. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  1874. const [showUploadForPrint, setShowUploadForPrint] = useState(false);
  1875. const [showPrinterInfo, setShowPrinterInfo] = useState(false);
  1876. const [showDiagnostic, setShowDiagnostic] = useState(false);
  1877. const closePrinterInfo = useCallback(() => setShowPrinterInfo(false), []);
  1878. const [printAfterUpload, setPrintAfterUpload] = useState<{ id: number; filename: string } | null>(null);
  1879. // AMS drying popover state: which AMS unit has the popover open
  1880. const [dryingPopoverAmsId, setDryingPopoverAmsId] = useState<number | null>(null);
  1881. const [dryingPopoverModuleType, setDryingPopoverModuleType] = useState<string>('n3f');
  1882. const [dryingFilament, setDryingFilament] = useState('PLA');
  1883. const [dryingTemp, setDryingTemp] = useState(50);
  1884. const [dryingDuration, setDryingDuration] = useState(4);
  1885. const [dryingRotateTray, setDryingRotateTray] = useState(false);
  1886. const [dryingPopoverPos, setDryingPopoverPos] = useState<{ top: number; left: number } | null>(null);
  1887. // Which AMS we are waiting on to actually enter a drying cycle (#2533). Held as
  1888. // an object rather than a bare id so restarting drying on the SAME unit produces
  1889. // a new identity and rearms the timeout below.
  1890. const [dryStartWatch, setDryStartWatch] = useState<{ amsId: number } | null>(null);
  1891. const [isDraggingFile, setIsDraggingFile] = useState(false);
  1892. const [isDropUploading, setIsDropUploading] = useState(false);
  1893. const printerActionsMenuRef = useRef<HTMLDivElement>(null);
  1894. const dragCounterRef = useRef(0);
  1895. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  1896. amsId: number;
  1897. amsLabel: string;
  1898. mode: 'humidity' | 'temperature';
  1899. } | null>(null);
  1900. const [heaterHistoryModal, setHeaterHistoryModal] = useState<{
  1901. initialKind: HeaterSensorKind;
  1902. availableKinds: HeaterSensorKind[];
  1903. } | null>(null);
  1904. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  1905. tagUid: string;
  1906. trayUuid: string;
  1907. printerId: number;
  1908. amsId: number;
  1909. trayId: number;
  1910. } | null>(null);
  1911. const [assignSpoolModal, setAssignSpoolModal] = useState<{
  1912. printerId: number;
  1913. amsId: number;
  1914. trayId: number;
  1915. trayInfo: { type: string; color: string; location: string; material?: string; profile?: string };
  1916. } | null>(null);
  1917. const [configureSlotModal, setConfigureSlotModal] = useState<{
  1918. amsId: number;
  1919. trayId: number;
  1920. trayCount: number;
  1921. trayType?: string;
  1922. trayColor?: string;
  1923. traySubBrands?: string;
  1924. trayInfoIdx?: string;
  1925. extruderId?: number;
  1926. caliIdx?: number | null;
  1927. savedPresetId?: string;
  1928. } | null>(null);
  1929. const [showFirmwareModal, setShowFirmwareModal] = useState(false);
  1930. const [plateCheckResult, setPlateCheckResult] = useState<{
  1931. is_empty: boolean;
  1932. confidence: number;
  1933. difference_percent: number;
  1934. message: string;
  1935. debug_image_url?: string;
  1936. needs_calibration: boolean;
  1937. light_warning?: boolean;
  1938. reference_count?: number;
  1939. max_references?: number;
  1940. roi?: { x: number; y: number; w: number; h: number };
  1941. } | null>(null);
  1942. const [isCheckingPlate, setIsCheckingPlate] = useState(false);
  1943. const [isCalibrating, setIsCalibrating] = useState(false);
  1944. const [editingRoi, setEditingRoi] = useState<{ x: number; y: number; w: number; h: number } | null>(null);
  1945. const [isSavingRoi, setIsSavingRoi] = useState(false);
  1946. const [plateCheckLightWasOff, setPlateCheckLightWasOff] = useState(false);
  1947. const { data: status } = useQuery({
  1948. queryKey: ['printerStatus', printer.id],
  1949. queryFn: () => api.getPrinterStatus(printer.id),
  1950. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  1951. });
  1952. // Check for firmware updates (cached for 5 minutes, can be disabled in settings)
  1953. const { data: firmwareInfo } = useQuery({
  1954. queryKey: ['firmwareUpdate', printer.id],
  1955. queryFn: () => firmwareApi.checkPrinterUpdate(printer.id),
  1956. staleTime: 5 * 60 * 1000,
  1957. refetchInterval: 5 * 60 * 1000,
  1958. enabled: checkPrinterFirmware && hasPermission('firmware:read'),
  1959. });
  1960. // Collect unique tray_info_idx values for cloud filament info lookup
  1961. const trayInfoIds = useMemo(() => {
  1962. const ids = new Set<string>();
  1963. if (status?.ams) {
  1964. for (const ams of status.ams) {
  1965. for (const tray of ams.tray || []) {
  1966. if (tray.tray_info_idx) {
  1967. ids.add(tray.tray_info_idx);
  1968. }
  1969. }
  1970. }
  1971. }
  1972. for (const vt of status?.vt_tray ?? []) {
  1973. if (vt.tray_info_idx) ids.add(vt.tray_info_idx);
  1974. }
  1975. if (status?.nozzle_rack) {
  1976. for (const slot of status.nozzle_rack) {
  1977. if (slot.filament_id) {
  1978. ids.add(slot.filament_id);
  1979. }
  1980. }
  1981. }
  1982. return Array.from(ids);
  1983. }, [status?.ams, status?.vt_tray, status?.nozzle_rack]);
  1984. // Collect loaded filament types for queue widget filtering
  1985. const loadedFilamentTypes = useMemo(() => {
  1986. const types = new Set<string>();
  1987. if (status?.ams) {
  1988. for (const ams of status.ams) {
  1989. for (const tray of ams.tray || []) {
  1990. if (tray.tray_type) types.add(tray.tray_type.toUpperCase());
  1991. }
  1992. }
  1993. }
  1994. for (const vt of status?.vt_tray ?? []) {
  1995. if (vt.tray_type) types.add(vt.tray_type.toUpperCase());
  1996. }
  1997. return types;
  1998. }, [status?.ams, status?.vt_tray]);
  1999. // Collect loaded filament type+color pairs for queue widget override matching
  2000. // Format: "TYPE:rrggbb" (e.g., "PETG:ffffff") — mirrors backend _count_override_color_matches()
  2001. const loadedFilaments = useMemo(() => {
  2002. const filaments = new Set<string>();
  2003. if (status?.ams) {
  2004. for (const ams of status.ams) {
  2005. for (const tray of ams.tray || []) {
  2006. if (tray.tray_type && tray.tray_color) {
  2007. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2008. filaments.add(`${tray.tray_type.toUpperCase()}:${color}`);
  2009. }
  2010. }
  2011. }
  2012. }
  2013. for (const vt of status?.vt_tray ?? []) {
  2014. if (vt.tray_type && vt.tray_color) {
  2015. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2016. filaments.add(`${vt.tray_type.toUpperCase()}:${color}`);
  2017. }
  2018. }
  2019. return filaments;
  2020. }, [status?.ams, status?.vt_tray]);
  2021. // Collect loaded type+color+tray_info_idx triples for variant-aware force-color
  2022. // matching. Format: "TYPE:rrggbb:idx" (idx "" for custom/third-party spools) —
  2023. // distinguishes Bambu PLA sub-variants that share a base type+colour (#2650).
  2024. const loadedVariants = useMemo(() => {
  2025. const variants = new Set<string>();
  2026. if (status?.ams) {
  2027. for (const ams of status.ams) {
  2028. for (const tray of ams.tray || []) {
  2029. if (tray.tray_type && tray.tray_color) {
  2030. const color = tray.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2031. variants.add(`${tray.tray_type.toUpperCase()}:${color}:${tray.tray_info_idx || ''}`);
  2032. }
  2033. }
  2034. }
  2035. }
  2036. for (const vt of status?.vt_tray ?? []) {
  2037. if (vt.tray_type && vt.tray_color) {
  2038. const color = vt.tray_color.replace('#', '').toLowerCase().slice(0, 6);
  2039. variants.add(`${vt.tray_type.toUpperCase()}:${color}:${vt.tray_info_idx || ''}`);
  2040. }
  2041. }
  2042. return variants;
  2043. }, [status?.ams, status?.vt_tray]);
  2044. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  2045. const { data: filamentInfo } = useQuery({
  2046. queryKey: ['filamentInfo', trayInfoIds],
  2047. queryFn: () => api.getFilamentInfo(trayInfoIds),
  2048. enabled: trayInfoIds.length > 0,
  2049. staleTime: 5 * 60 * 1000, // 5 minutes
  2050. });
  2051. // Fetch slot preset mappings (stores preset name for user-configured slots)
  2052. const { data: slotPresets } = useQuery({
  2053. queryKey: ['slotPresets', printer.id],
  2054. queryFn: () => api.getSlotPresets(printer.id),
  2055. staleTime: 2 * 60 * 1000, // 2 minutes
  2056. });
  2057. // Fetch plate list for the archive linked to the active print (#881 follow-up).
  2058. // Only queried when there's a running print backed by an archive; shared
  2059. // React Query cache with the Queue / Archives pages keeps it cheap.
  2060. const activeArchiveId =
  2061. (status?.state === 'RUNNING' || status?.state === 'PAUSE') ? status?.current_archive_id ?? null : null;
  2062. const { data: activeArchivePlates } = useQuery({
  2063. queryKey: ['archive-plates', activeArchiveId],
  2064. queryFn: () => api.getArchivePlates(activeArchiveId!),
  2065. enabled: activeArchiveId != null,
  2066. staleTime: 5 * 60 * 1000,
  2067. });
  2068. const activePlateLabel = (() => {
  2069. if (!activeArchivePlates?.is_multi_plate || status?.current_plate_id == null) return null;
  2070. const plate = activeArchivePlates.plates.find(p => p.index === status.current_plate_id);
  2071. return plate?.name || t('printers.plateNumber', 'Plate {{number}}', { number: status.current_plate_id });
  2072. })();
  2073. // Fetch user-defined AMS friendly names from the database
  2074. const { data: amsLabels, refetch: refetchAmsLabels } = useQuery({
  2075. queryKey: ['amsLabels', printer.id],
  2076. queryFn: () => api.getAmsLabels(printer.id),
  2077. staleTime: 5 * 60 * 1000, // 5 minutes
  2078. });
  2079. // Cache WiFi signal to prevent it disappearing on updates
  2080. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  2081. useEffect(() => {
  2082. if (status?.wifi_signal != null) {
  2083. setCachedWifiSignal(status.wifi_signal);
  2084. }
  2085. }, [status?.wifi_signal]);
  2086. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  2087. // Cache connected state to prevent flicker when status briefly becomes undefined
  2088. const cachedConnected = useRef<boolean | undefined>(undefined);
  2089. useEffect(() => {
  2090. if (status?.connected !== undefined) {
  2091. cachedConnected.current = status.connected;
  2092. }
  2093. }, [status?.connected]);
  2094. const isConnected = status?.connected ?? cachedConnected.current;
  2095. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  2096. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  2097. useEffect(() => {
  2098. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  2099. cachedAmsExtruderMap.current = status.ams_extruder_map;
  2100. }
  2101. }, [status?.ams_extruder_map]);
  2102. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  2103. ? status.ams_extruder_map
  2104. : cachedAmsExtruderMap.current;
  2105. // Cache AMS data to prevent it disappearing on idle/offline printers
  2106. const cachedAmsData = useRef<AMSUnit[]>([]);
  2107. useEffect(() => {
  2108. if (status?.ams && status.ams.length > 0) {
  2109. cachedAmsData.current = status.ams;
  2110. }
  2111. }, [status?.ams]);
  2112. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  2113. // Confirm a drying cycle actually started (#2533). Firmware answers
  2114. // ams_filament_drying with result=success even when it then silently declines,
  2115. // and P1-family firmware never publishes dry_sf_reason — so the server-side
  2116. // reason guard is blind there and the card just sits unchanged. Watch the unit
  2117. // after the ack: leaving DryStatus 0 means the cycle is live, staying there
  2118. // means the printer took the command and dropped it.
  2119. useEffect(() => {
  2120. if (!dryStartWatch) return;
  2121. const unit = amsData.find(a => a.id === dryStartWatch.amsId);
  2122. if (unit && (unit.dry_time > 0 || unit.dry_status > 0)) setDryStartWatch(null);
  2123. }, [dryStartWatch, amsData]);
  2124. // Deps deliberately exclude amsData: status pushes arrive continuously and would
  2125. // otherwise rearm the timeout on every frame, so it would never elapse.
  2126. useEffect(() => {
  2127. if (!dryStartWatch) return;
  2128. const timer = setTimeout(() => {
  2129. setDryStartWatch(null);
  2130. showToast(t('printers.drying.toastNotStarted'), 'error');
  2131. }, DRY_START_CONFIRM_MS);
  2132. return () => clearTimeout(timer);
  2133. }, [dryStartWatch, showToast, t]);
  2134. // Cache tray_now to prevent flickering when undefined values come in
  2135. // Valid tray IDs: 0-253 for AMS, 254 for external spool
  2136. // tray_now=255 means "no tray loaded" (Bambu protocol sentinel) — never active
  2137. const cachedTrayNow = useRef<number | undefined>(undefined);
  2138. const currentTrayNow = status?.tray_now;
  2139. // Update cache: 255 means "no tray" so clear cache; valid values get cached
  2140. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  2141. cachedTrayNow.current = currentTrayNow;
  2142. } else if (currentTrayNow === 255) {
  2143. cachedTrayNow.current = undefined;
  2144. }
  2145. const effectiveTrayNow = (currentTrayNow !== undefined && currentTrayNow !== 255)
  2146. ? currentTrayNow
  2147. : cachedTrayNow.current;
  2148. // Runout / filament-replacement guidance (#2587). The backend fills these only
  2149. // while the print is PAUSED (global tray IDs, or null when idle/unresolvable):
  2150. // expectedTray = the slot the firmware now expects filament in
  2151. // previousTray = the slot that ran out
  2152. // With AMS Filament Backup the firmware advances to the next compatible slot,
  2153. // so these are often different — the graphic highlights the expected one.
  2154. const expectedTray = status?.expected_tray ?? null;
  2155. const previousTray = status?.previous_tray ?? null;
  2156. // Pre-format the runout slot labels (honoring user AMS friendly names) for the
  2157. // HMS modal (#2587). null when the slot can't be placed → honest fallback copy.
  2158. const formatRunoutSlotLabel = (globalId: number | null): string | null => {
  2159. if (globalId === null) return null;
  2160. if (globalId === 254) return t('printers.expectedSlot.external');
  2161. if (globalId >= 128 && globalId <= 135) {
  2162. return amsLabels?.[globalId] || getAmsLabel(globalId, 1);
  2163. }
  2164. const amsId = Math.floor(globalId / 4);
  2165. const slot = globalId % 4;
  2166. const amsName = amsLabels?.[amsId] || getAmsLabel(amsId, 4);
  2167. return t('printers.expectedSlot.label', { ams: amsName, slot: slot + 1 });
  2168. };
  2169. const runoutGuidance = status?.state === 'PAUSE'
  2170. ? {
  2171. expectedSlotLabel: formatRunoutSlotLabel(expectedTray),
  2172. ranOutSlotLabel: formatRunoutSlotLabel(previousTray),
  2173. }
  2174. : null;
  2175. // Fetch smart plug for this printer
  2176. const { data: smartPlug } = useQuery({
  2177. queryKey: ['smartPlugByPrinter', printer.id],
  2178. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  2179. });
  2180. // Fetch script plugs for this printer (for multi-device control)
  2181. const { data: scriptPlugs } = useQuery({
  2182. queryKey: ['scriptPlugsByPrinter', printer.id],
  2183. queryFn: () => api.getScriptPlugsByPrinter(printer.id),
  2184. });
  2185. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  2186. const { data: plugStatus } = useQuery({
  2187. queryKey: ['smartPlugStatus', smartPlug?.id],
  2188. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  2189. enabled: !!smartPlug,
  2190. refetchInterval: 10000, // 10 seconds for real-time power display
  2191. });
  2192. // Fetch queue count for this printer
  2193. const { data: queueItems } = useQuery({
  2194. queryKey: ['queue', printer.id, 'pending'],
  2195. queryFn: () => api.getQueue(printer.id, 'pending'),
  2196. });
  2197. // Filter queue items by filament compatibility (same logic as PrinterQueueWidget)
  2198. // so the badge only shows on printers that can actually run the queued jobs.
  2199. // An empty Set means no filaments are loaded — jobs requiring specific types are incompatible.
  2200. const queueCount = useMemo(() => {
  2201. if (!queueItems?.length) return 0;
  2202. return filterCompatibleQueueItems(queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants).length;
  2203. }, [queueItems, loadedFilamentTypes, loadedFilaments, loadedVariants]);
  2204. // Fetch currently printing queue item to show who started it (Issue #206)
  2205. const { data: printingQueueItems } = useQuery({
  2206. queryKey: ['queue', printer.id, 'printing'],
  2207. queryFn: () => api.getQueue(printer.id, 'printing'),
  2208. enabled: status?.state === 'RUNNING',
  2209. });
  2210. // Fetch reprint user info (for prints started via Reprint, not queue - Issue #206)
  2211. const { data: reprintUser } = useQuery({
  2212. queryKey: ['currentPrintUser', printer.id],
  2213. queryFn: () => api.getCurrentPrintUser(printer.id),
  2214. enabled: status?.state === 'RUNNING',
  2215. });
  2216. // Combine both sources: queue item user takes precedence, then reprint user
  2217. const currentPrintUser = printingQueueItems?.[0]?.created_by_username || reprintUser?.username;
  2218. // Fetch last completed print for this printer
  2219. const { data: lastPrints } = useQuery({
  2220. queryKey: ['archives', printer.id, 'last'],
  2221. queryFn: () => api.getArchives(printer.id, 1, 0),
  2222. enabled: status?.connected && status?.state !== 'RUNNING',
  2223. });
  2224. const lastPrint = lastPrints?.[0];
  2225. const isPrintingOrPaused = status?.state === 'RUNNING' || status?.state === 'PAUSE';
  2226. const needsPlateClear = requirePlateClear && status?.awaiting_plate_clear === true;
  2227. const showClearPlateButton = status?.connected && needsPlateClear && !isPrintingOrPaused;
  2228. const activePrintName = status?.current_print && isPrintingOrPaused
  2229. ? formatPrintName(status.subtask_name || status.current_print || null, status.gcode_file, t, activePlateLabel)
  2230. : null;
  2231. const [retainedPrintJob, setRetainedPrintJob] = useState<{ name: string; coverUrl: string | null } | null>(null);
  2232. useEffect(() => {
  2233. if (activePrintName) {
  2234. setRetainedPrintJob({ name: activePrintName, coverUrl: status?.cover_url ?? null });
  2235. } else if (!needsPlateClear) {
  2236. setRetainedPrintJob(null);
  2237. }
  2238. }, [activePrintName, needsPlateClear, status?.cover_url]);
  2239. const plateStatus = (() => {
  2240. if (!requirePlateClear || !status?.connected) return null;
  2241. if (isPrintingOrPaused) {
  2242. return {
  2243. label: t('printers.plateStatus.inUse'),
  2244. className: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400',
  2245. };
  2246. }
  2247. if (status.awaiting_plate_clear) {
  2248. return {
  2249. label: t('printers.plateStatus.notCleared'),
  2250. className: 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400',
  2251. };
  2252. }
  2253. return {
  2254. label: t('printers.plateStatus.cleared'),
  2255. className: 'bg-status-ok/20 text-status-ok',
  2256. };
  2257. })();
  2258. const plateStatusPill = plateStatus ? (
  2259. <span className={`inline-flex flex-shrink-0 items-center rounded-full px-2 py-0.5 text-[length:var(--pc-t10,10px)] font-medium ${plateStatus.className}`}>
  2260. {plateStatus.label}
  2261. </span>
  2262. ) : null;
  2263. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  2264. const shouldHide = hideIfDisconnected && isConnected === false;
  2265. const deleteMutation = useMutation({
  2266. mutationFn: (options: { deleteArchives: boolean }) =>
  2267. api.deletePrinter(printer.id, options.deleteArchives),
  2268. onSuccess: () => {
  2269. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2270. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2271. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  2272. },
  2273. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToDelete'), 'error'),
  2274. });
  2275. const connectMutation = useMutation({
  2276. mutationFn: () => api.connectPrinter(printer.id),
  2277. onSuccess: () => {
  2278. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2279. },
  2280. });
  2281. const forceRefreshMutation = useMutation({
  2282. mutationFn: () => api.refreshPrinterStatus(printer.id),
  2283. onSuccess: () => {
  2284. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2285. showToast(t('printers.forceRefreshSuccess'), 'success');
  2286. },
  2287. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2288. });
  2289. const unlinkSpoolMutation = useMutation({
  2290. mutationFn: (spoolId: number) => api.unlinkSpool(spoolId),
  2291. onSuccess: (result) => {
  2292. showToast(t('spoolman.unlinkSuccess') || result?.message, 'success');
  2293. queryClient.invalidateQueries({ queryKey: ['linked-spools'] });
  2294. queryClient.invalidateQueries({ queryKey: ['unlinked-spools'] });
  2295. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  2296. },
  2297. onError: (error: Error) => {
  2298. showToast(error.message || t('spoolman.unlinkFailed'), 'error');
  2299. },
  2300. });
  2301. // AMS drying mutations
  2302. const startDryingMutation = useMutation({
  2303. mutationFn: ({ amsId, temp, duration, filament, rotateTray }: { amsId: number; temp: number; duration: number; filament: string; rotateTray: boolean }) =>
  2304. api.startDrying(printer.id, amsId, temp, duration, filament, rotateTray),
  2305. onSuccess: (_data, { amsId }) => {
  2306. setDryingPopoverAmsId(null);
  2307. setDryStartWatch({ amsId });
  2308. // "Command sent", not "drying started" — at this point the printer has only
  2309. // taken the command. The amber countdown badge (dry_time > 0) is what says
  2310. // the cycle is genuinely live; the watcher below covers the case where it
  2311. // never appears.
  2312. showToast(t('printers.drying.toastCommandSent'), 'success');
  2313. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2314. },
  2315. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2316. });
  2317. const stopDryingMutation = useMutation({
  2318. mutationFn: (amsId: number) => api.stopDrying(printer.id, amsId),
  2319. onSuccess: () => {
  2320. setDryStartWatch(null);
  2321. showToast(t('printers.drying.toastStopped'), 'success');
  2322. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2323. },
  2324. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2325. });
  2326. // AMS Filament Backup toggle (auto-switch to a backup spool when one runs out).
  2327. // Invalidate BOTH printer-status cache keys — the codebase has two conventions
  2328. // ('printerStatus' camelCase + 'printer-status' kebab-case used by PrintModal /
  2329. // useMultiPrinterFilamentMapping). Hitting only one would leave PrintModal
  2330. // showing the old backup state until the user reopens it.
  2331. const setAmsBackupMutation = useMutation({
  2332. mutationFn: (enabled: boolean) => api.setAmsFilamentBackup(printer.id, enabled),
  2333. onSuccess: (_data, enabled) => {
  2334. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2335. queryClient.invalidateQueries({ queryKey: ['printer-status', printer.id] });
  2336. showToast(t(enabled ? 'printers.amsBackup.toastEnabled' : 'printers.amsBackup.toastDisabled'), 'success');
  2337. },
  2338. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2339. });
  2340. // Smart plug control mutations
  2341. const powerControlMutation = useMutation({
  2342. mutationFn: (action: 'on' | 'off') =>
  2343. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  2344. onSuccess: () => {
  2345. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  2346. },
  2347. });
  2348. const toggleAutoOffMutation = useMutation({
  2349. mutationFn: (enabled: boolean) =>
  2350. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  2351. onSuccess: () => {
  2352. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  2353. // Also invalidate the smart-plugs list to keep Settings page in sync
  2354. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  2355. },
  2356. });
  2357. // Run HA entity mutation — scripts use 'on' (trigger), switches use 'toggle'
  2358. const runScriptMutation = useMutation({
  2359. mutationFn: ({ id, action }: { id: number; action: 'on' | 'toggle' }) => api.controlSmartPlug(id, action),
  2360. onSuccess: () => {
  2361. showToast(t('printers.toast.scriptTriggered'));
  2362. },
  2363. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToRunScript'), 'error'),
  2364. });
  2365. // Print control mutations
  2366. const stopPrintMutation = useMutation({
  2367. mutationFn: () => api.stopPrint(printer.id),
  2368. onSuccess: () => {
  2369. showToast(t('printers.toast.printStopped'));
  2370. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2371. },
  2372. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToStopPrint'), 'error'),
  2373. });
  2374. const pausePrintMutation = useMutation({
  2375. mutationFn: () => api.pausePrint(printer.id),
  2376. onSuccess: () => {
  2377. showToast(t('printers.toast.printPaused'));
  2378. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2379. },
  2380. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToPausePrint'), 'error'),
  2381. });
  2382. const resumePrintMutation = useMutation({
  2383. mutationFn: () => api.resumePrint(printer.id),
  2384. onSuccess: () => {
  2385. showToast(t('printers.toast.printResumed'));
  2386. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2387. },
  2388. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToResumePrint'), 'error'),
  2389. });
  2390. const clearPlateMutation = useMutation({
  2391. mutationFn: () => api.clearPlate(printer.id),
  2392. onSuccess: () => {
  2393. showToast(t('queue.clearPlateSuccess'));
  2394. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2395. old ? { ...old, awaiting_plate_clear: false } : old
  2396. );
  2397. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2398. queryClient.invalidateQueries({ queryKey: ['queue', printer.id] });
  2399. },
  2400. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2401. });
  2402. const nozzleTemperatureMutation = useMutation({
  2403. mutationFn: ({ target, nozzle }: { target: number; nozzle: number }) =>
  2404. api.setNozzleTemperature(printer.id, target, nozzle),
  2405. onSuccess: (result) => {
  2406. setStatusControlMenu(null);
  2407. showToast(result.message);
  2408. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2409. },
  2410. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2411. });
  2412. const bedTemperatureMutation = useMutation({
  2413. mutationFn: (target: number) => api.setBedTemperature(printer.id, target),
  2414. onSuccess: (result) => {
  2415. setStatusControlMenu(null);
  2416. showToast(result.message);
  2417. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2418. },
  2419. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2420. });
  2421. const chamberTemperatureMutation = useMutation({
  2422. mutationFn: (target: number) => api.setChamberTemperature(printer.id, target),
  2423. onSuccess: (result) => {
  2424. setStatusControlMenu(null);
  2425. showToast(result.message);
  2426. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2427. },
  2428. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2429. });
  2430. const fanSpeedMutation = useMutation({
  2431. mutationFn: ({ fan, speed }: { fan: 'part' | 'aux' | 'aux2' | 'chamber'; speed: number }) =>
  2432. api.setFanSpeed(printer.id, fan, speed),
  2433. onMutate: async ({ fan, speed }) => {
  2434. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2435. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2436. const fanField = {
  2437. part: 'cooling_fan_speed',
  2438. aux: 'big_fan1_speed',
  2439. aux2: 'left_aux_fan_speed',
  2440. chamber: 'big_fan2_speed',
  2441. }[fan];
  2442. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2443. old ? { ...old, [fanField]: speed } : old
  2444. );
  2445. return { previousStatus };
  2446. },
  2447. onSuccess: (result) => {
  2448. setStatusControlMenu(null);
  2449. showToast(result.message);
  2450. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2451. },
  2452. onError: (error: Error, _variables, context) => {
  2453. if (context?.previousStatus) {
  2454. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2455. }
  2456. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2457. },
  2458. });
  2459. const selectExtruderMutation = useMutation({
  2460. mutationFn: (extruder: number) => api.selectExtruder(printer.id, extruder),
  2461. onMutate: async (extruder) => {
  2462. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2463. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2464. queryClient.setQueryData(['printerStatus', printer.id], (old: PrinterStatus | undefined) =>
  2465. old ? { ...old, active_extruder: extruder } : old
  2466. );
  2467. return { previousStatus };
  2468. },
  2469. onSuccess: (result) => {
  2470. setStatusControlMenu(null);
  2471. showToast(result.message);
  2472. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2473. },
  2474. onError: (error: Error, _extruder, context) => {
  2475. if (context?.previousStatus) {
  2476. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2477. }
  2478. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2479. },
  2480. });
  2481. // Chamber light mutation with optimistic update
  2482. const chamberLightMutation = useMutation({
  2483. mutationFn: (on: boolean) => api.setChamberLight(printer.id, on),
  2484. onMutate: async (on) => {
  2485. // Cancel any outgoing refetches
  2486. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2487. // Snapshot the previous value
  2488. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2489. // Optimistically update
  2490. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2491. ...old,
  2492. chamber_light: on,
  2493. }));
  2494. return { previousStatus };
  2495. },
  2496. onSuccess: (_, on) => {
  2497. showToast(`Chamber light ${on ? 'on' : 'off'}`);
  2498. },
  2499. onError: (error: Error, _, context) => {
  2500. // Rollback on error
  2501. if (context?.previousStatus) {
  2502. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2503. }
  2504. showToast(error.message || t('printers.toast.failedToControlChamberLight'), 'error');
  2505. },
  2506. });
  2507. // Print speed mutation with optimistic update
  2508. const printSpeedMutation = useMutation({
  2509. mutationFn: (mode: number) => api.setPrintSpeed(printer.id, mode),
  2510. onMutate: async (mode) => {
  2511. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2512. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2513. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2514. ...old,
  2515. speed_level: mode,
  2516. }));
  2517. return { previousStatus };
  2518. },
  2519. onError: (error: Error, _, context) => {
  2520. if (context?.previousStatus) {
  2521. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2522. }
  2523. showToast(error.message || t('printers.toast.failedToSetSpeed'), 'error');
  2524. },
  2525. });
  2526. const airductMutation = useMutation({
  2527. mutationFn: (mode: 'cooling' | 'heating') => api.setAirductMode(printer.id, mode),
  2528. onMutate: async (mode) => {
  2529. await queryClient.cancelQueries({ queryKey: ['printerStatus', printer.id] });
  2530. const previousStatus = queryClient.getQueryData(['printerStatus', printer.id]);
  2531. queryClient.setQueryData(['printerStatus', printer.id], (old: typeof status) => ({
  2532. ...old,
  2533. airduct_mode: mode === 'cooling' ? 0 : 1,
  2534. }));
  2535. return { previousStatus };
  2536. },
  2537. onError: (error: Error, _, context) => {
  2538. if (context?.previousStatus) {
  2539. queryClient.setQueryData(['printerStatus', printer.id], context.previousStatus);
  2540. }
  2541. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error');
  2542. },
  2543. });
  2544. const bedJogMutation = useMutation({
  2545. mutationFn: ({ distance }: { distance: number }) =>
  2546. api.bedJog(printer.id, distance),
  2547. onError: (error: Error) =>
  2548. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2549. });
  2550. const xyJogMutation = useMutation({
  2551. mutationFn: ({ x, y }: { x: number; y: number }) =>
  2552. api.xyJog(printer.id, x, y),
  2553. onError: (error: Error) =>
  2554. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2555. });
  2556. const extruderJogMutation = useMutation({
  2557. mutationFn: (distance: number) =>
  2558. api.extruderJog(printer.id, distance),
  2559. onError: (error: Error) =>
  2560. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2561. });
  2562. const homeAxesMutation = useMutation({
  2563. mutationFn: (axes: 'z' | 'xy' | 'all') => api.homeAxes(printer.id, axes),
  2564. onSuccess: () => {
  2565. showToast(t('printers.bedJog.homingStarted'));
  2566. },
  2567. onError: (error: Error) =>
  2568. showToast(error.message || t('printers.toast.failedToSendCommand'), 'error'),
  2569. });
  2570. // Plate detection setting mutation
  2571. const plateDetectionMutation = useMutation({
  2572. mutationFn: (enabled: boolean) => api.updatePrinter(printer.id, { plate_detection_enabled: enabled }),
  2573. onSuccess: () => {
  2574. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2575. showToast(plateDetectionMutation.variables ? t('printers.toast.plateCheckEnabled') : t('printers.toast.plateCheckDisabled'));
  2576. },
  2577. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2578. });
  2579. // Maintenance mode toggle (#1476). Wraps the `is_active` backend field that
  2580. // already gates MQTT connection, queue dispatch, scheduler eligibility,
  2581. // metrics, and the print picker — so flipping this flag puts the printer
  2582. // out of service across every consumer in one place. Used from the
  2583. // overflow menu and EditPrinterModal.
  2584. const maintenanceMutation = useMutation({
  2585. mutationFn: (isActive: boolean) => api.updatePrinter(printer.id, { is_active: isActive }),
  2586. onSuccess: (_data, isActive) => {
  2587. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2588. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2589. showToast(
  2590. isActive
  2591. ? t('printers.maintenance.toastExited', { name: printer.name })
  2592. : t('printers.maintenance.toastEntered', { name: printer.name }),
  2593. 'success',
  2594. );
  2595. },
  2596. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdateSetting'), 'error'),
  2597. });
  2598. // Confirm before entering maintenance on a printing printer (entering mode
  2599. // disconnects MQTT, which stops progress tracking + completion notifications
  2600. // for the in-flight job).
  2601. const [confirmMaintenanceEnter, setConfirmMaintenanceEnter] = useState(false);
  2602. const handleEnterMaintenance = () => {
  2603. if (status?.state === 'RUNNING' || status?.state === 'PAUSE') {
  2604. setConfirmMaintenanceEnter(true);
  2605. } else {
  2606. maintenanceMutation.mutate(false);
  2607. }
  2608. };
  2609. // Query for printable objects (for skip functionality)
  2610. // Fetch when printing with 2+ objects OR when modal is open
  2611. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE') && (status?.printable_objects_count ?? 0) >= 2;
  2612. const { data: objectsData } = useQuery({
  2613. queryKey: ['printableObjects', printer.id],
  2614. queryFn: () => api.getPrintableObjects(printer.id),
  2615. enabled: showSkipObjectsModal || isPrintingWithObjects,
  2616. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  2617. });
  2618. // State for tracking which AMS slot is being refreshed
  2619. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  2620. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  2621. const seenBusyStateRef = useRef<boolean>(false);
  2622. // Fallback timeout ref
  2623. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2624. // Minimum display time passed
  2625. const minTimePassedRef = useRef<boolean>(false);
  2626. // AMS slot refresh mutation
  2627. const refreshAmsSlotMutation = useMutation({
  2628. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  2629. api.refreshAmsSlot(printer.id, amsId, slotId),
  2630. onMutate: ({ amsId, slotId }) => {
  2631. // Clear any existing timeout
  2632. if (refreshTimeoutRef.current) {
  2633. clearTimeout(refreshTimeoutRef.current);
  2634. }
  2635. // Reset state
  2636. seenBusyStateRef.current = false;
  2637. minTimePassedRef.current = false;
  2638. setRefreshingSlot({ amsId, slotId });
  2639. // Minimum display time (2 seconds)
  2640. setTimeout(() => {
  2641. minTimePassedRef.current = true;
  2642. }, 2000);
  2643. // Fallback timeout (30 seconds max)
  2644. refreshTimeoutRef.current = setTimeout(() => {
  2645. setRefreshingSlot(null);
  2646. }, 30000);
  2647. },
  2648. onSuccess: (data) => {
  2649. showToast(data.message || t('printers.toast.rfidRereadInitiated'));
  2650. },
  2651. onError: (error: Error) => {
  2652. showToast(error.message || t('printers.toast.failedToRereadRfid'), 'error');
  2653. if (refreshTimeoutRef.current) {
  2654. clearTimeout(refreshTimeoutRef.current);
  2655. }
  2656. setRefreshingSlot(null);
  2657. },
  2658. });
  2659. // AMS load/unload mutations (#891)
  2660. const loadAmsTrayMutation = useMutation({
  2661. mutationFn: ({ trayId }: { trayId: number }) => api.loadAmsTray(printer.id, trayId),
  2662. onSuccess: (data) => {
  2663. showToast(data.message || t('printers.toast.loadInitiated'));
  2664. },
  2665. onError: (error: Error) => {
  2666. showToast(error.message || t('printers.toast.failedToLoad'), 'error');
  2667. },
  2668. });
  2669. const unloadAmsMutation = useMutation({
  2670. mutationFn: () => api.unloadAms(printer.id),
  2671. onSuccess: (data) => {
  2672. showToast(data.message || t('printers.toast.unloadInitiated'));
  2673. },
  2674. onError: (error: Error) => {
  2675. showToast(error.message || t('printers.toast.failedToUnload'), 'error');
  2676. },
  2677. });
  2678. // Plate references state
  2679. const [plateReferences, setPlateReferences] = useState<{
  2680. references: Array<{ index: number; label: string; timestamp: string; has_image: boolean; thumbnail_url: string }>;
  2681. max_references: number;
  2682. } | null>(null);
  2683. const [editingRefLabel, setEditingRefLabel] = useState<{ index: number; label: string } | null>(null);
  2684. // Fetch plate references
  2685. const fetchPlateReferences = async () => {
  2686. try {
  2687. const data = await api.getPlateReferences(printer.id);
  2688. setPlateReferences(data);
  2689. } catch {
  2690. // Ignore errors - references will show as empty
  2691. }
  2692. };
  2693. // Toggle plate detection enabled/disabled
  2694. const handleTogglePlateDetection = () => {
  2695. plateDetectionMutation.mutate(!printer.plate_detection_enabled);
  2696. };
  2697. // Open plate detection management modal (for calibration/references)
  2698. const handleOpenPlateManagement = async () => {
  2699. setIsCheckingPlate(true);
  2700. setPlateCheckResult(null);
  2701. // Auto-turn on light if it's off
  2702. const lightWasOff = status?.chamber_light === false;
  2703. setPlateCheckLightWasOff(lightWasOff);
  2704. if (lightWasOff) {
  2705. await api.setChamberLight(printer.id, true);
  2706. // Wait for light to physically turn on and camera to adjust exposure
  2707. // (MQTT command is async, light takes ~1s to turn on, camera needs time to adjust)
  2708. await new Promise(resolve => setTimeout(resolve, 2500));
  2709. }
  2710. try {
  2711. const result = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2712. setPlateCheckResult(result);
  2713. fetchPlateReferences();
  2714. } catch (error) {
  2715. showToast(error instanceof Error ? error.message : t('printers.toast.failedToCheckPlate'), 'error');
  2716. // Restore light if check failed
  2717. if (lightWasOff) {
  2718. await api.setChamberLight(printer.id, false);
  2719. setPlateCheckLightWasOff(false);
  2720. }
  2721. } finally {
  2722. setIsCheckingPlate(false);
  2723. }
  2724. };
  2725. // Close plate check modal and restore light state
  2726. const closePlateCheckModal = useCallback(async () => {
  2727. setPlateCheckResult(null);
  2728. // Restore light to original state if we turned it on
  2729. if (plateCheckLightWasOff) {
  2730. await api.setChamberLight(printer.id, false);
  2731. setPlateCheckLightWasOff(false);
  2732. }
  2733. }, [plateCheckLightWasOff, printer.id]);
  2734. // Calibrate plate detection handler
  2735. const handleCalibratePlate = async (label?: string) => {
  2736. setIsCalibrating(true);
  2737. try {
  2738. const result = await api.calibratePlateDetection(printer.id, { label });
  2739. if (result.success) {
  2740. showToast(result.message || t('printers.toast.calibrationSaved'), 'success');
  2741. // Refresh references and re-check
  2742. fetchPlateReferences();
  2743. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2744. setPlateCheckResult(checkResult);
  2745. } else {
  2746. showToast(result.message || t('printers.toast.calibrationFailed'), 'error');
  2747. }
  2748. } catch (error) {
  2749. showToast(error instanceof Error ? error.message : t('printers.toast.calibrationFailed'), 'error');
  2750. } finally {
  2751. setIsCalibrating(false);
  2752. }
  2753. };
  2754. // Update reference label
  2755. const handleUpdateRefLabel = async (index: number, label: string) => {
  2756. try {
  2757. await api.updatePlateReferenceLabel(printer.id, index, label);
  2758. setEditingRefLabel(null);
  2759. fetchPlateReferences();
  2760. } catch (error) {
  2761. showToast(error instanceof Error ? error.message : t('printers.toast.failedToUpdateLabel'), 'error');
  2762. }
  2763. };
  2764. // Delete reference
  2765. const handleDeleteRef = async (index: number) => {
  2766. try {
  2767. await api.deletePlateReference(printer.id, index);
  2768. showToast(t('printers.toast.referenceDeleted'), 'success');
  2769. fetchPlateReferences();
  2770. // Re-check to update counts
  2771. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2772. setPlateCheckResult(checkResult);
  2773. } catch (error) {
  2774. showToast(error instanceof Error ? error.message : t('printers.toast.failedToDeleteReference'), 'error');
  2775. }
  2776. };
  2777. // Save ROI settings
  2778. const handleSaveRoi = async () => {
  2779. if (!editingRoi) return;
  2780. setIsSavingRoi(true);
  2781. try {
  2782. await api.updatePrinter(printer.id, { plate_detection_roi: editingRoi });
  2783. showToast(t('printers.toast.detectionAreaSaved'), 'success');
  2784. setEditingRoi(null);
  2785. // Re-check to see new ROI in action
  2786. const checkResult = await api.checkPlateEmpty(printer.id, { includeDebugImage: true });
  2787. setPlateCheckResult(checkResult);
  2788. } catch (error) {
  2789. showToast(error instanceof Error ? error.message : t('printers.toast.failedToSaveDetectionArea'), 'error');
  2790. } finally {
  2791. setIsSavingRoi(false);
  2792. }
  2793. };
  2794. // Close plate check modal on Escape key
  2795. useEffect(() => {
  2796. const handleEscape = (e: KeyboardEvent) => {
  2797. if (e.key === 'Escape' && plateCheckResult) {
  2798. closePlateCheckModal();
  2799. }
  2800. };
  2801. window.addEventListener('keydown', handleEscape);
  2802. return () => window.removeEventListener('keydown', handleEscape);
  2803. }, [plateCheckResult, closePlateCheckModal]);
  2804. // Watch ams_status_main to detect when RFID read completes
  2805. // ams_status_main: 0=idle, 2=rfid_identifying
  2806. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  2807. useEffect(() => {
  2808. if (!refreshingSlot) return;
  2809. const amsStatus = status?.ams_status_main ?? 0;
  2810. // Track when we see non-idle state (printer is working)
  2811. if (amsStatus !== 0) {
  2812. seenBusyStateRef.current = true;
  2813. // Cancel any deferred clear since we're back to busy
  2814. if (deferredClearRef.current) {
  2815. clearTimeout(deferredClearRef.current);
  2816. deferredClearRef.current = null;
  2817. }
  2818. }
  2819. // When we've seen busy and now idle, clear (with min time check)
  2820. if (seenBusyStateRef.current && amsStatus === 0) {
  2821. if (minTimePassedRef.current) {
  2822. // Min time passed - clear now
  2823. if (refreshTimeoutRef.current) {
  2824. clearTimeout(refreshTimeoutRef.current);
  2825. }
  2826. setRefreshingSlot(null);
  2827. } else {
  2828. // Schedule clear after min time (2 seconds from start)
  2829. if (!deferredClearRef.current) {
  2830. deferredClearRef.current = setTimeout(() => {
  2831. if (refreshTimeoutRef.current) {
  2832. clearTimeout(refreshTimeoutRef.current);
  2833. }
  2834. setRefreshingSlot(null);
  2835. }, 2000);
  2836. }
  2837. }
  2838. }
  2839. return () => {
  2840. if (deferredClearRef.current) {
  2841. clearTimeout(deferredClearRef.current);
  2842. }
  2843. };
  2844. }, [status?.ams_status_main, refreshingSlot]);
  2845. useEffect(() => {
  2846. if (!showMenu) return;
  2847. const handleClickOutside = (event: MouseEvent) => {
  2848. const target = event.target as Node;
  2849. if (!printerActionsMenuRef.current?.contains(target)) {
  2850. setShowMenu(false);
  2851. }
  2852. };
  2853. document.addEventListener('mousedown', handleClickOutside);
  2854. return () => document.removeEventListener('mousedown', handleClickOutside);
  2855. }, [showMenu]);
  2856. if (shouldHide) {
  2857. return null;
  2858. }
  2859. // Size-based styling helpers
  2860. // Body type and icon scale (#1848). S/M/L/XL already scaled the card's
  2861. // width, its thumbnail and the printer name, but every label inside the
  2862. // body was pinned at 8-11px, so an XL card showed the same tiny text as an
  2863. // S one -- the disparity was worst exactly where someone asking for more
  2864. // room ends up. These custom properties carry the scaled sizes into the
  2865. // card's subtree. S and M are deliberately 1.0: nobody's card changes
  2866. // unless they reach for a size that is already asking for more space.
  2867. // Plain computation rather than useMemo: this sits after the card's early
  2868. // returns, where a hook would break the rules-of-hooks ordering, and
  2869. // building ten strings per render costs nothing.
  2870. const cardScaleStyle = buildCardScaleStyle(cardSize);
  2871. const getImageSize = () => {
  2872. switch (cardSize) {
  2873. case 1: return 'w-10 h-10';
  2874. case 2: return 'w-14 h-14';
  2875. case 3: return 'w-16 h-16';
  2876. case 4: return 'w-20 h-20';
  2877. default: return 'w-14 h-14';
  2878. }
  2879. };
  2880. const getTitleSize = () => {
  2881. switch (cardSize) {
  2882. case 1: return 'text-base truncate';
  2883. case 2: return 'text-lg';
  2884. case 3: return 'text-xl';
  2885. case 4: return 'text-2xl';
  2886. default: return 'text-lg';
  2887. }
  2888. };
  2889. const getSpacing = () => {
  2890. switch (cardSize) {
  2891. case 1: return 'mb-2';
  2892. case 2: return 'mb-4';
  2893. case 3: return 'mb-5';
  2894. case 4: return 'mb-6';
  2895. default: return 'mb-4';
  2896. }
  2897. };
  2898. const canDrop = isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && hasPermission('printers:control');
  2899. const handleCardDragEnter = (e: React.DragEvent) => {
  2900. e.preventDefault();
  2901. dragCounterRef.current++;
  2902. if (dragCounterRef.current === 1) setIsDraggingFile(true);
  2903. };
  2904. const handleCardDragOver = (e: React.DragEvent) => {
  2905. e.preventDefault();
  2906. e.dataTransfer.dropEffect = canDrop ? 'copy' : 'none';
  2907. };
  2908. const handleCardDragLeave = (e: React.DragEvent) => {
  2909. e.preventDefault();
  2910. dragCounterRef.current--;
  2911. if (dragCounterRef.current === 0) setIsDraggingFile(false);
  2912. };
  2913. const handleCardDrop = async (e: React.DragEvent) => {
  2914. e.preventDefault();
  2915. dragCounterRef.current = 0;
  2916. setIsDraggingFile(false);
  2917. if (!canDrop) return;
  2918. const droppedFiles = Array.from(e.dataTransfer.files);
  2919. const file = droppedFiles[0];
  2920. if (!file) return;
  2921. // Only accept sliced/printable files (.gcode, .gcode.3mf, etc.)
  2922. const lower = file.name.toLowerCase();
  2923. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  2924. showToast(t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed'), 'error');
  2925. return;
  2926. }
  2927. setIsDropUploading(true);
  2928. try {
  2929. const result = await api.uploadLibraryFile(file, null);
  2930. // Check printer compatibility if sliced_for_model is available in metadata
  2931. const slicedFor = (result.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  2932. const printerModel = mapModelCode(printer.model);
  2933. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  2934. await api.deleteLibraryFile(result.id).catch(() => {});
  2935. showToast(
  2936. t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel }),
  2937. 'error'
  2938. );
  2939. return;
  2940. }
  2941. setPrintAfterUpload({ id: result.id, filename: result.filename });
  2942. } catch {
  2943. showToast(t('common.uploadFailed', 'Upload failed'), 'error');
  2944. } finally {
  2945. setIsDropUploading(false);
  2946. }
  2947. };
  2948. const handleCardClick = (e: React.MouseEvent) => {
  2949. if (viewMode !== 'compact' || selectionMode) return;
  2950. const target = e.target as HTMLElement;
  2951. if (target.closest('button, a, input, select, textarea, [role="button"]')) return;
  2952. onOpenCompactCard?.(printer.id);
  2953. };
  2954. const footerActionButtonClass = '!h-8 !min-h-8 !px-2 !py-0';
  2955. const footerIconButtonClass = '!h-8 !min-h-8 !w-8 !px-0 !py-0';
  2956. const renderAmsSlotActions = ({
  2957. amsId,
  2958. slotId,
  2959. loadTrayId,
  2960. isRefreshing,
  2961. includeRfid = true,
  2962. }: {
  2963. amsId: number;
  2964. slotId: number;
  2965. loadTrayId: number;
  2966. isRefreshing?: boolean;
  2967. includeRfid?: boolean;
  2968. }) => {
  2969. const printerBusy = status?.state === 'RUNNING';
  2970. return (
  2971. <>
  2972. {includeRfid && (
  2973. <button
  2974. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2975. hasPermission('printers:ams_rfid')
  2976. ? 'text-white hover:bg-bambu-dark-tertiary'
  2977. : 'text-bambu-gray/50 cursor-not-allowed'
  2978. }`}
  2979. onClick={(e) => {
  2980. e.stopPropagation();
  2981. if (printerBusy || !hasPermission('printers:ams_rfid')) return;
  2982. refreshAmsSlotMutation.mutate({ amsId, slotId });
  2983. }}
  2984. disabled={printerBusy || isRefreshing || !hasPermission('printers:ams_rfid')}
  2985. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:ams_rfid') ? t('printers.permission.noAmsRfid') : undefined}
  2986. >
  2987. <RefreshCw className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] ${isRefreshing ? 'animate-spin' : ''}`} />
  2988. {t('printers.rfid.reread')}
  2989. </button>
  2990. )}
  2991. <button
  2992. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  2993. hasPermission('printers:control')
  2994. ? 'text-white hover:bg-bambu-dark-tertiary'
  2995. : 'text-bambu-gray/50 cursor-not-allowed'
  2996. }`}
  2997. onClick={(e) => {
  2998. e.stopPropagation();
  2999. if (printerBusy || !hasPermission('printers:control')) return;
  3000. loadAmsTrayMutation.mutate({ trayId: loadTrayId });
  3001. }}
  3002. disabled={printerBusy || !hasPermission('printers:control')}
  3003. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3004. >
  3005. <LogIn className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3006. {t('printers.ams.load')}
  3007. </button>
  3008. <button
  3009. className={`w-full px-2 py-1.5 text-left text-xs flex items-center gap-2 rounded transition-colors ${
  3010. hasPermission('printers:control')
  3011. ? 'text-white hover:bg-bambu-dark-tertiary'
  3012. : 'text-bambu-gray/50 cursor-not-allowed'
  3013. }`}
  3014. onClick={(e) => {
  3015. e.stopPropagation();
  3016. if (printerBusy || !hasPermission('printers:control')) return;
  3017. unloadAmsMutation.mutate();
  3018. }}
  3019. disabled={printerBusy || !hasPermission('printers:control')}
  3020. title={printerBusy ? t('printers.bedJog.disabledWhilePrinting') : !hasPermission('printers:control') ? t('printers.permission.noControl') : undefined}
  3021. >
  3022. <LogOut className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3023. {t('printers.ams.unload')}
  3024. </button>
  3025. </>
  3026. );
  3027. };
  3028. const printerActionsMenu = (
  3029. <div ref={printerActionsMenuRef} className="relative flex-shrink-0">
  3030. <Button
  3031. variant="secondary"
  3032. size="sm"
  3033. onClick={() => setShowMenu(!showMenu)}
  3034. title={t('common.more', 'More')}
  3035. className={footerIconButtonClass}
  3036. >
  3037. <MoreVertical className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3038. </Button>
  3039. {showMenu && (
  3040. <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">
  3041. <button
  3042. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3043. hasPermission('printers:update')
  3044. ? 'hover:bg-bambu-dark-tertiary'
  3045. : 'opacity-50 cursor-not-allowed'
  3046. }`}
  3047. onClick={() => {
  3048. if (!hasPermission('printers:update')) return;
  3049. setShowEditModal(true);
  3050. setShowMenu(false);
  3051. }}
  3052. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3053. >
  3054. <Pencil className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3055. {t('common.edit')}
  3056. </button>
  3057. <button
  3058. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3059. onClick={() => {
  3060. setShowPrinterInfo(true);
  3061. setShowMenu(false);
  3062. }}
  3063. >
  3064. <Info className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3065. {t('printers.printerInformation')}
  3066. </button>
  3067. {/* Maintenance Mode toggle (#1476) — leverages backend is_active flag */}
  3068. <button
  3069. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3070. hasPermission('printers:update')
  3071. ? 'hover:bg-bambu-dark-tertiary'
  3072. : 'opacity-50 cursor-not-allowed'
  3073. }`}
  3074. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3075. onClick={() => {
  3076. if (!hasPermission('printers:update')) return;
  3077. setShowMenu(false);
  3078. if (printer.is_active !== false) {
  3079. handleEnterMaintenance();
  3080. } else {
  3081. maintenanceMutation.mutate(true);
  3082. }
  3083. }}
  3084. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3085. >
  3086. <Wrench className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3087. {printer.is_active !== false
  3088. ? t('printers.maintenance.menuEnter')
  3089. : t('printers.maintenance.menuExit')}
  3090. </button>
  3091. <button
  3092. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3093. onClick={() => {
  3094. connectMutation.mutate();
  3095. setShowMenu(false);
  3096. }}
  3097. >
  3098. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3099. {t('printers.reconnect')}
  3100. </button>
  3101. <button
  3102. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2 disabled:opacity-50"
  3103. disabled={forceRefreshMutation.isPending}
  3104. onClick={() => {
  3105. forceRefreshMutation.mutate();
  3106. setShowMenu(false);
  3107. }}
  3108. >
  3109. <RotateCw className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${forceRefreshMutation.isPending ? 'animate-spin' : ''}`} />
  3110. {t('printers.forceRefresh')}
  3111. </button>
  3112. <button
  3113. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3114. onClick={() => {
  3115. setShowMQTTDebug(true);
  3116. setShowMenu(false);
  3117. }}
  3118. >
  3119. <Terminal className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3120. {t('printers.mqttDebug')}
  3121. </button>
  3122. <button
  3123. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  3124. onClick={() => {
  3125. setShowDiagnostic(true);
  3126. setShowMenu(false);
  3127. }}
  3128. >
  3129. <Stethoscope className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3130. {t('diagnostic.runButton')}
  3131. </button>
  3132. <button
  3133. className={`w-full px-4 py-2 text-left text-sm flex items-center gap-2 ${
  3134. hasPermission('printers:delete')
  3135. ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark-tertiary'
  3136. : 'text-red-700/50 dark:text-red-400/50 cursor-not-allowed'
  3137. }`}
  3138. onClick={() => {
  3139. if (!hasPermission('printers:delete')) return;
  3140. setShowDeleteConfirm(true);
  3141. setShowMenu(false);
  3142. }}
  3143. title={!hasPermission('printers:delete') ? t('printers.permission.noDelete') : undefined}
  3144. >
  3145. <Trash2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3146. {t('common.delete')}
  3147. </button>
  3148. </div>
  3149. )}
  3150. </div>
  3151. );
  3152. return (
  3153. <Card
  3154. id={`printer-card-${printer.id}`}
  3155. className={`relative flex h-full flex-col ${isSelected ? 'ring-2 ring-bambu-green' : ''} ${selectionMode || viewMode === 'compact' ? 'cursor-pointer' : ''}`}
  3156. style={cardScaleStyle}
  3157. onClick={handleCardClick}
  3158. onDragEnter={handleCardDragEnter}
  3159. onDragOver={handleCardDragOver}
  3160. onDragLeave={handleCardDragLeave}
  3161. onDrop={handleCardDrop}
  3162. >
  3163. {/* Selection mode click overlay — captures all clicks, preventing nested interactions */}
  3164. {selectionMode && (
  3165. <div
  3166. className="absolute inset-0 z-20 flex items-start p-2"
  3167. onClick={(e) => { e.stopPropagation(); onToggleSelect?.(printer.id); }}
  3168. >
  3169. {isSelected ? (
  3170. <CheckSquare className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-green" />
  3171. ) : (
  3172. <Square className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-bambu-gray" />
  3173. )}
  3174. </div>
  3175. )}
  3176. {/* Drop zone overlay */}
  3177. {(isDraggingFile || isDropUploading) && (
  3178. <div
  3179. className={`absolute inset-0 z-10 rounded-xl border-2 border-dashed flex items-center justify-center transition-colors ${
  3180. isDropUploading
  3181. ? 'bg-bambu-green/10 border-bambu-green/50'
  3182. : canDrop
  3183. ? 'bg-bambu-green/10 border-bambu-green'
  3184. : 'bg-red-50 dark:bg-red-500/10 border-red-300 dark:border-red-500/50'
  3185. }`}
  3186. >
  3187. <div className="text-center">
  3188. {isDropUploading ? (
  3189. <>
  3190. <Loader2 className="w-8 h-8 mx-auto mb-2 text-bambu-green animate-spin" />
  3191. <p className="text-sm font-medium text-bambu-green">{t('common.uploading', 'Uploading...')}</p>
  3192. </>
  3193. ) : canDrop ? (
  3194. <>
  3195. <PrinterIcon className="w-8 h-8 mx-auto mb-2 text-bambu-green" />
  3196. <p className="text-sm font-medium text-bambu-green">{t('printers.dropToPrint', 'Drop to print')}</p>
  3197. </>
  3198. ) : (
  3199. <>
  3200. <X className="w-8 h-8 mx-auto mb-2 text-red-600 dark:text-red-400" />
  3201. <p className="text-sm font-medium text-red-700 dark:text-red-400">{t('printers.cannotPrint', 'Printer busy')}</p>
  3202. </>
  3203. )}
  3204. </div>
  3205. </div>
  3206. )}
  3207. <CardContent className={`${cardSize >= 3 ? 'p-5' : ''} flex flex-1 flex-col`}>
  3208. {/* Header */}
  3209. <div className={getSpacing()}>
  3210. {/* Top row: Image, Name, Menu */}
  3211. <div className="flex items-start justify-between gap-2">
  3212. <div className="flex items-center gap-3 min-w-0 flex-1">
  3213. {/* Printer Model Image */}
  3214. <img
  3215. src={getPrinterImage(printer.model)}
  3216. alt={printer.model || t('common.printer')}
  3217. className={`object-contain rounded-lg flex-shrink-0 ${getImageSize()}`}
  3218. />
  3219. <div className="min-w-0 flex-1">
  3220. <div className="flex items-center justify-between gap-2">
  3221. <div className="flex min-w-0 items-center gap-2">
  3222. <h3 className={`font-semibold text-white ${getTitleSize()}`}>{printer.name}</h3>
  3223. {/* Connection indicator dot for compact mode */}
  3224. {viewMode === 'compact' && (() => {
  3225. const hmsErrors = status?.connected && status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3226. const hasSevere = hmsErrors.some(e => e.severity <= 2);
  3227. const hasWarning = hmsErrors.length > 0;
  3228. const pipColor = !status?.connected
  3229. ? 'bg-status-error'
  3230. : hasSevere
  3231. ? 'bg-status-error'
  3232. : hasWarning
  3233. ? 'bg-status-warning'
  3234. : 'bg-status-ok';
  3235. const pipTitle = !status?.connected
  3236. ? t('printers.connection.offline')
  3237. : hasWarning
  3238. ? `${hmsErrors.length} HMS ${hmsErrors.length === 1 ? 'error' : 'errors'}`
  3239. : t('printers.connection.connected');
  3240. return (
  3241. <div
  3242. className={`w-[var(--pc-i2,0.5rem)] h-[var(--pc-i2,0.5rem)] rounded-full flex-shrink-0 ${pipColor}`}
  3243. title={pipTitle}
  3244. />
  3245. );
  3246. })()}
  3247. </div>
  3248. {viewMode === 'compact' && showClearPlateButton && (
  3249. <button
  3250. type="button"
  3251. onClick={() => clearPlateMutation.mutate()}
  3252. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  3253. aria-label={t('printers.plateStatus.markCleared')}
  3254. 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"
  3255. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  3256. >
  3257. {clearPlateMutation.isPending ? (
  3258. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  3259. ) : (
  3260. <PlateClearedIcon className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3261. )}
  3262. </button>
  3263. )}
  3264. </div>
  3265. <p className="text-sm text-bambu-gray">
  3266. {printer.model || 'Unknown Model'}
  3267. {/* Nozzle Info - only in expanded */}
  3268. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  3269. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  3270. • {status.nozzles[0].nozzle_diameter}mm
  3271. </span>
  3272. )}
  3273. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  3274. <span className="ml-2 text-bambu-gray">
  3275. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] inline-block mr-1" />
  3276. {Math.round(maintenanceInfo.total_print_hours)}h
  3277. </span>
  3278. )}
  3279. </p>
  3280. </div>
  3281. </div>
  3282. </div>
  3283. {/* Badges row - only in expanded mode */}
  3284. {viewMode === 'expanded' && (
  3285. <div className="mt-2">
  3286. <div className="flex flex-wrap items-center gap-2">
  3287. {/* Connection status badge (or Maintenance pill when out of service).
  3288. Defensive: only swap when is_active is EXPLICITLY false. An
  3289. undefined / missing field defaults to "active" so the regular
  3290. pill renders — matches the backend default and prevents test
  3291. fixtures (or stale clients) from accidentally tripping the
  3292. maintenance UI. */}
  3293. {printer.is_active === false ? (
  3294. <span
  3295. 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"
  3296. title={t('printers.maintenance.subtitle')}
  3297. >
  3298. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3299. {t('printers.maintenance.pillLabel')}
  3300. </span>
  3301. ) : (
  3302. <span
  3303. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  3304. status?.connected
  3305. ? 'bg-status-ok/20 text-status-ok'
  3306. : 'bg-status-error/20 text-status-error'
  3307. }`}
  3308. >
  3309. {status?.connected ? (
  3310. <Link className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3311. ) : (
  3312. <Unlink className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3313. )}
  3314. {status?.connected ? t('printers.connection.connected') : t('printers.connection.offline')}
  3315. </span>
  3316. )}
  3317. {/* Run connection diagnostic — offered when the printer is offline, NOT in maintenance */}
  3318. {printer.is_active !== false && !status?.connected && (
  3319. <button
  3320. onClick={() => setShowDiagnostic(true)}
  3321. 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"
  3322. title={t('diagnostic.runButton')}
  3323. >
  3324. <Stethoscope className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3325. {t('diagnostic.runButton')}
  3326. </button>
  3327. )}
  3328. {/* Network connection indicator */}
  3329. {status?.connected && status?.wired_network && (
  3330. <span
  3331. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-status-ok/20 text-status-ok"
  3332. title={t('printers.connection.ethernet', 'Ethernet')}
  3333. >
  3334. <Cable className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3335. {t('printers.connection.ethernet', 'Ethernet')}
  3336. </span>
  3337. )}
  3338. {/* WiFi signal indicator */}
  3339. {status?.connected && !status?.wired_network && wifiSignal != null && (
  3340. <span
  3341. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  3342. wifiSignal >= -50
  3343. ? 'bg-status-ok/20 text-status-ok'
  3344. : wifiSignal >= -60
  3345. ? 'bg-status-ok/20 text-status-ok'
  3346. : wifiSignal >= -70
  3347. ? 'bg-status-warning/20 text-status-warning'
  3348. : wifiSignal >= -80
  3349. ? 'bg-orange-500/20 text-orange-600'
  3350. : 'bg-status-error/20 text-status-error'
  3351. }`}
  3352. title={`WiFi: ${wifiSignal} dBm - ${t(getWifiStrength(wifiSignal).labelKey)}`}
  3353. >
  3354. <Signal className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3355. {wifiSignal}dBm
  3356. </span>
  3357. )}
  3358. {/* HMS Status Indicator */}
  3359. {status?.connected && (() => {
  3360. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3361. return (
  3362. <button
  3363. onClick={() => setShowHMSModal(true)}
  3364. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3365. knownErrors.length > 0
  3366. ? knownErrors.some(e => e.severity <= 2)
  3367. ? 'bg-status-error/20 text-status-error'
  3368. : 'bg-status-warning/20 text-status-warning'
  3369. : 'bg-status-ok/20 text-status-ok'
  3370. }`}
  3371. title={t('printers.clickToViewHmsErrors')}
  3372. >
  3373. <AlertTriangle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3374. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  3375. </button>
  3376. );
  3377. })()}
  3378. {/* AI failure detection badge (#1546) — always shown while detection
  3379. is enabled for this printer, like the other health badges. Gray
  3380. "Idle" outside a monitored print, class-colored during one. */}
  3381. {aiDetectionEnabled && (() => {
  3382. const cls = aiDetection
  3383. ? (aiDetection.class === 'failure' || aiDetection.class === 'warning' ? aiDetection.class : 'safe')
  3384. : 'idle';
  3385. const colorClass =
  3386. cls === 'failure'
  3387. ? 'bg-status-error/20 text-status-error'
  3388. : cls === 'warning'
  3389. ? 'bg-status-warning/20 text-status-warning'
  3390. : cls === 'safe'
  3391. ? 'bg-status-ok/20 text-status-ok'
  3392. : 'bg-bambu-dark-tertiary text-bambu-gray';
  3393. return (
  3394. <button
  3395. onClick={() => setShowAiModal(true)}
  3396. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${colorClass}`}
  3397. title={
  3398. aiDetection
  3399. ? t('printers.aiDetection.tooltip', {
  3400. status: t(`printers.aiDetection.${cls}`),
  3401. score: aiDetection.score.toFixed(3),
  3402. })
  3403. : t('printers.aiDetection.tooltipIdle')
  3404. }
  3405. >
  3406. <ScanEye className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3407. {t(`printers.aiDetection.${cls}`)}
  3408. </button>
  3409. );
  3410. })()}
  3411. {/* Maintenance Status Indicator */}
  3412. {maintenanceInfo && (
  3413. <button
  3414. onClick={() => navigate('/maintenance')}
  3415. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  3416. maintenanceInfo.due_count > 0
  3417. ? 'bg-status-error/20 text-status-error'
  3418. : maintenanceInfo.warning_count > 0
  3419. ? 'bg-status-warning/20 text-status-warning'
  3420. : 'bg-status-ok/20 text-status-ok'
  3421. }`}
  3422. title={
  3423. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3424. ? `${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`
  3425. : t('printers.maintenanceUpToDate')
  3426. }
  3427. >
  3428. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3429. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  3430. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  3431. : 'OK'}
  3432. </button>
  3433. )}
  3434. {/* Queue Count Badge */}
  3435. {queueCount > 0 && (
  3436. <button
  3437. onClick={() => navigate('/queue')}
  3438. 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"
  3439. title={t('printers.queue.inQueue', { count: queueCount })}
  3440. >
  3441. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3442. {queueCount}
  3443. </button>
  3444. )}
  3445. {/* Firmware Version Badge */}
  3446. {checkPrinterFirmware && firmwareInfo?.current_version && firmwareInfo?.latest_version ? (
  3447. <button
  3448. onClick={() => setShowFirmwareModal(true)}
  3449. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs hover:opacity-80 transition-opacity ${
  3450. firmwareInfo.update_available
  3451. ? 'bg-orange-100 dark:bg-orange-500/20 text-orange-700 dark:text-orange-400'
  3452. : 'bg-status-ok/20 text-status-ok'
  3453. }`}
  3454. title={
  3455. firmwareInfo.update_available
  3456. ? t('printers.firmwareUpdateAvailable', { current: firmwareInfo.current_version, latest: firmwareInfo.latest_version })
  3457. : t('printers.firmwareUpToDate', { version: firmwareInfo.current_version })
  3458. }
  3459. >
  3460. {firmwareInfo.update_available ? <Download className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <CheckCircle className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3461. {firmwareInfo.current_version}
  3462. </button>
  3463. ) : status?.firmware_version ? (
  3464. <span className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-bambu-dark-tertiary/50 text-bambu-gray">
  3465. {status.firmware_version}
  3466. </span>
  3467. ) : null}
  3468. {/* Enclosure Door Badge — models with an actual door sensor.
  3469. P1S has an enclosure door but no sensor; P1P has no enclosure at all. */}
  3470. {status?.connected && ['X1C', 'X1', 'X1E', 'X2D', 'P2S', 'H2D', 'H2D Pro', 'H2C', 'H2S'].includes(printer.model ?? '') && (
  3471. <span
  3472. className={`flex items-center px-2 py-1 rounded-full text-xs ${
  3473. status.door_open
  3474. ? 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400'
  3475. : 'bg-status-ok/20 text-status-ok'
  3476. }`}
  3477. title={status.door_open ? t('printers.door.open') : t('printers.door.closed')}
  3478. >
  3479. {status.door_open ? <DoorOpen className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <DoorClosed className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  3480. </span>
  3481. )}
  3482. </div>
  3483. </div>
  3484. )}
  3485. </div>
  3486. {/* Delete Confirmation */}
  3487. {showDeleteConfirm && (
  3488. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  3489. <Card className="w-full max-w-md mx-4">
  3490. <CardContent>
  3491. <div className="flex items-start gap-3 mb-4">
  3492. <div className="p-2 rounded-full bg-red-100 dark:bg-red-500/20">
  3493. <AlertTriangle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-red-600 dark:text-red-400" />
  3494. </div>
  3495. <div>
  3496. <h3 className="text-lg font-semibold text-white">{t('printers.confirm.deleteTitle')}</h3>
  3497. <p className="text-sm text-bambu-gray mt-1">
  3498. {t('printers.confirm.deleteMessage', { name: printer.name })}
  3499. </p>
  3500. </div>
  3501. </div>
  3502. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  3503. <label className="flex items-start gap-3 cursor-pointer">
  3504. <input
  3505. type="checkbox"
  3506. checked={deleteArchives}
  3507. onChange={(e) => setDeleteArchives(e.target.checked)}
  3508. className="mt-0.5 w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  3509. />
  3510. <div>
  3511. <span className="text-sm text-white">{t('printers.deleteArchives')}</span>
  3512. <p className="text-xs text-bambu-gray mt-0.5">
  3513. {deleteArchives
  3514. ? t('printers.confirm.deleteArchivesNote')
  3515. : t('printers.confirm.keepArchivesNote')}
  3516. </p>
  3517. </div>
  3518. </label>
  3519. </div>
  3520. <div className="flex justify-end gap-2">
  3521. <Button
  3522. variant="secondary"
  3523. onClick={() => {
  3524. setShowDeleteConfirm(false);
  3525. setDeleteArchives(true);
  3526. }}
  3527. >
  3528. {t('common.cancel')}
  3529. </Button>
  3530. <Button
  3531. variant="danger"
  3532. onClick={() => {
  3533. deleteMutation.mutate({ deleteArchives });
  3534. setShowDeleteConfirm(false);
  3535. setDeleteArchives(true);
  3536. }}
  3537. >
  3538. Delete
  3539. </Button>
  3540. </div>
  3541. </CardContent>
  3542. </Card>
  3543. </div>
  3544. )}
  3545. {/* Status — see the equivalent defensive `=== false` check on the
  3546. header pill above for why this is not `!printer.is_active`. */}
  3547. {printer.is_active === false ? (
  3548. // Maintenance mode (#1476) — replaces the cover/progress container
  3549. // so the card keeps the same height. Renders for both compact and
  3550. // expanded view modes so the printer stays visible but plainly
  3551. // out-of-service.
  3552. <>
  3553. {viewMode === 'compact' ? (
  3554. <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">
  3555. <Wrench className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  3556. <span className="text-[length:var(--pc-t11,11px)] text-amber-700 dark:text-amber-400 font-medium truncate">
  3557. {t('printers.maintenance.pillLabel')}
  3558. </span>
  3559. </div>
  3560. ) : (
  3561. <>
  3562. <div className="flex items-center gap-2 mb-2">
  3563. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  3564. {t('printers.status.title', 'Status')}
  3565. </span>
  3566. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3567. </div>
  3568. <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">
  3569. <Wrench className="w-6 h-6 text-amber-600 dark:text-amber-400 shrink-0" />
  3570. <div className="flex-1 min-w-0">
  3571. <p className="text-sm text-amber-700 dark:text-amber-400 font-medium">
  3572. {t('printers.maintenance.title')}
  3573. </p>
  3574. <p className="text-xs text-bambu-gray mt-0.5">
  3575. {t('printers.maintenance.subtitle')}
  3576. </p>
  3577. </div>
  3578. <Button
  3579. variant="secondary"
  3580. size="sm"
  3581. disabled={maintenanceMutation.isPending || !hasPermission('printers:update')}
  3582. onClick={() => maintenanceMutation.mutate(true)}
  3583. title={!hasPermission('printers:update') ? t('printers.permission.noEdit') : undefined}
  3584. >
  3585. {t('printers.maintenance.exitButton')}
  3586. </Button>
  3587. </div>
  3588. </>
  3589. )}
  3590. </>
  3591. ) : status?.connected && (
  3592. <>
  3593. {/* Compact: Simple status bar */}
  3594. {viewMode === 'compact' ? (
  3595. (() => {
  3596. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  3597. const hasProblem = status.state === 'FAILED' || hmsErrors.length > 0;
  3598. const compactProgress = status.state === 'RUNNING' || status.state === 'PAUSE'
  3599. ? Math.max(0, Math.min(100, status.progress || 0))
  3600. : showClearPlateButton
  3601. ? 100
  3602. : hasProblem
  3603. ? 100
  3604. : 0;
  3605. const isActiveCompactPrint = status.state === 'RUNNING' || status.state === 'PAUSE';
  3606. const compactProgressClass = hasProblem
  3607. ? 'bg-status-error'
  3608. : status.state === 'PAUSE'
  3609. ? 'bg-status-warning'
  3610. : 'bg-bambu-green';
  3611. const hasCompactEta = isActiveCompactPrint && status.remaining_time != null && status.remaining_time > 0;
  3612. const hasCompactLayers =
  3613. isActiveCompactPrint &&
  3614. status.layer_num != null &&
  3615. status.total_layers != null &&
  3616. status.total_layers > 0;
  3617. return (
  3618. <>
  3619. <div className="relative mt-2 flex items-center gap-2">
  3620. <div className="h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-bambu-dark-tertiary">
  3621. <div
  3622. className={`${compactProgressClass} h-1.5 rounded-full transition-all`}
  3623. style={{ width: `${compactProgress}%` }}
  3624. />
  3625. </div>
  3626. <span className={`w-9 shrink-0 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActiveCompactPrint ? 'text-white' : 'text-bambu-gray'}`}>
  3627. {isActiveCompactPrint ? `${Math.round(compactProgress)}%` : '---%'}
  3628. </span>
  3629. </div>
  3630. {/* #2674: size S showed only a name, a pip and a progress bar — not
  3631. enough to answer "which printer finishes first", which is what a
  3632. wall-mounted fleet view is for. One line of the metrics the
  3633. expanded card already renders, using the same formatters and the
  3634. same ETA styling so S and M read alike. The row keeps its height
  3635. when idle so cards don't shift as prints start and stop. */}
  3636. <div className="mt-1 flex min-h-[14px] items-center gap-2 overflow-hidden text-[length:var(--pc-t11,11px)] leading-none text-bambu-gray">
  3637. {hasCompactEta && (
  3638. <>
  3639. <span className="flex shrink-0 items-center gap-1">
  3640. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3641. {formatDuration(status.remaining_time! * 60)}
  3642. </span>
  3643. <span
  3644. className="shrink-0 font-medium text-bambu-green"
  3645. title={t('printers.estimatedCompletion')}
  3646. >
  3647. ETA {formatETA(status.remaining_time!, timeFormat, t)}
  3648. </span>
  3649. </>
  3650. )}
  3651. {hasCompactLayers && (
  3652. <span className="flex min-w-0 items-center gap-1 truncate">
  3653. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0" />
  3654. {status.layer_num}/{status.total_layers}
  3655. </span>
  3656. )}
  3657. </div>
  3658. </>
  3659. );
  3660. })()
  3661. ) : (
  3662. /* Expanded: Full status section */
  3663. <>
  3664. <div className="flex items-center gap-2 mb-2">
  3665. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  3666. {t('printers.status.title', 'Status')}
  3667. </span>
  3668. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  3669. </div>
  3670. {/* Current Print or Idle Placeholder */}
  3671. {(() => {
  3672. const isActivePrint = !!(status.current_print && (status.state === 'RUNNING' || status.state === 'PAUSE'));
  3673. const showRetainedPrint = !isActivePrint && needsPlateClear && retainedPrintJob;
  3674. const printName = isActivePrint ? activePrintName : showRetainedPrint ? retainedPrintJob.name : null;
  3675. const coverUrl = isActivePrint ? status.cover_url : showRetainedPrint ? retainedPrintJob.coverUrl : null;
  3676. const progress = isActivePrint ? (status.progress || 0) : showRetainedPrint ? 100 : 0;
  3677. return (
  3678. <div className="p-2 bg-bambu-dark rounded-[10px] relative overflow-hidden">
  3679. <button
  3680. onClick={() => setShowSkipObjectsModal(true)}
  3681. disabled={!isActivePrint || (status.printable_objects_count ?? 0) < 2 || !hasPermission('printers:control')}
  3682. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  3683. isActivePrint && (status.printable_objects_count ?? 0) >= 2 && hasPermission('printers:control')
  3684. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  3685. : 'text-bambu-gray/30 cursor-not-allowed'
  3686. }`}
  3687. title={
  3688. !hasPermission('printers:control')
  3689. ? t('printers.permission.noControl')
  3690. : !isActivePrint
  3691. ? t('printers.skipObjects.onlyWhilePrinting')
  3692. : (status.printable_objects_count ?? 0) >= 2
  3693. ? t('printers.skipObjects.tooltip')
  3694. : t('printers.skipObjects.requiresMultiple')
  3695. }
  3696. >
  3697. <SkipObjectsIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  3698. {objectsData && objectsData.skipped_count > 0 && (
  3699. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[length:var(--pc-t10,10px)] font-bold bg-red-500 text-white rounded-full">
  3700. {objectsData.skipped_count}
  3701. </span>
  3702. )}
  3703. </button>
  3704. <div className="flex items-stretch gap-2">
  3705. <CoverImage
  3706. url={coverUrl}
  3707. printName={printName || undefined}
  3708. className="w-24 h-24 max-[520px]:w-20 max-[520px]:h-20"
  3709. />
  3710. <div className="flex h-24 max-[520px]:h-20 min-w-0 flex-1 flex-col justify-between pt-1">
  3711. <div className="flex min-h-[18px] items-center gap-2 pr-8">
  3712. <p className="min-w-0 truncate text-sm text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  3713. {plateStatusPill}
  3714. </div>
  3715. <p className={`min-h-[18px] truncate pr-8 text-sm ${printName ? 'text-white' : 'text-bambu-gray/70'}`}>
  3716. {printName || t('printers.noActiveJob', 'No active job')}
  3717. </p>
  3718. <div className="flex h-3 items-center gap-2 text-sm">
  3719. <div className="h-1.5 min-w-0 flex-1 rounded-full bg-bambu-dark-tertiary">
  3720. <div
  3721. 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`}
  3722. style={{ width: `${progress}%` }}
  3723. />
  3724. </div>
  3725. <span className={`w-9 shrink-0 pr-1 text-right text-[length:var(--pc-t11,11px)] leading-none ${isActivePrint || showRetainedPrint ? 'text-white' : 'text-bambu-gray'}`}>{isActivePrint || showRetainedPrint ? `${Math.round(progress)}%` : '---%'}</span>
  3726. </div>
  3727. <div className="flex min-h-[16px] items-center gap-2 text-xs text-bambu-gray">
  3728. {isActivePrint ? (
  3729. <>
  3730. {status.remaining_time != null && status.remaining_time > 0 && (
  3731. <>
  3732. <span className="flex items-center gap-1">
  3733. <Clock className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3734. {formatDuration(status.remaining_time * 60)}
  3735. </span>
  3736. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  3737. ETA {formatETA(status.remaining_time, timeFormat, t)}
  3738. </span>
  3739. </>
  3740. )}
  3741. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  3742. <span className="flex items-center gap-1">
  3743. <Layers className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3744. {status.layer_num}/{status.total_layers}
  3745. </span>
  3746. )}
  3747. {currentPrintUser && (
  3748. <span className="flex items-center gap-1" title={`Started by ${currentPrintUser}`}>
  3749. <User className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  3750. {currentPrintUser}
  3751. </span>
  3752. )}
  3753. </>
  3754. ) : lastPrint ? (
  3755. <p className="truncate" title={lastPrint.print_name || lastPrint.filename}>
  3756. Last: {lastPrint.print_name || lastPrint.filename}
  3757. {lastPrint.completed_at && (
  3758. <span className="ml-1 text-bambu-gray/60">
  3759. • {formatDateOnly(lastPrint.completed_at, { month: 'short', day: 'numeric' })}
  3760. </span>
  3761. )}
  3762. </p>
  3763. ) : (
  3764. <span>{t('printers.readyToPrint')}</span>
  3765. )}
  3766. </div>
  3767. </div>
  3768. </div>
  3769. <PrinterQueueWidget
  3770. printerId={printer.id}
  3771. printerModel={printer.model}
  3772. loadedFilamentTypes={loadedFilamentTypes}
  3773. loadedFilaments={loadedFilaments}
  3774. loadedVariants={loadedVariants}
  3775. variant="panelExtension"
  3776. />
  3777. </div>
  3778. );
  3779. })()}
  3780. </>
  3781. )}
  3782. {/* Temperatures */}
  3783. {status.temperatures && viewMode === 'expanded' && (() => {
  3784. // Use actual heater states from MQTT stream
  3785. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  3786. const bedHeating = status.temperatures.bed_heating || false;
  3787. const chamberHeating = status.temperatures.chamber_heating || false;
  3788. const isDualNozzle = printer.nozzle_count === 2 || status.temperatures.nozzle_2 !== undefined;
  3789. const availableHeaterKinds: HeaterSensorKind[] = (() => {
  3790. const kinds: HeaterSensorKind[] = ['nozzle'];
  3791. if (status.temperatures.nozzle_2 !== undefined) kinds.push('nozzle_2');
  3792. kinds.push('bed');
  3793. if (status.temperatures.chamber !== undefined) kinds.push('chamber');
  3794. return kinds;
  3795. })();
  3796. // active_extruder: 0=right, 1=left
  3797. const activeNozzle = status.active_extruder === 1 ? 'L' : 'R';
  3798. // Extended nozzle data from nozzle_rack (H2 series: wear, serial, max_temp, etc.)
  3799. // nozzle_rack id 0 = extruder 0 = RIGHT, id 1 = extruder 1 = LEFT
  3800. const leftNozzleSlot = status.nozzle_rack?.find(s => s.id === 1);
  3801. const rightNozzleSlot = status.nozzle_rack?.find(s => s.id === 0);
  3802. // Single-nozzle models (H2D, H2C): use the primary nozzle (id 0)
  3803. const singleNozzleSlot = rightNozzleSlot || leftNozzleSlot;
  3804. const canUseStatusControls = status.connected && hasPermission('printers:control');
  3805. const statusControlTitle = canUseStatusControls ? undefined : t('printers.permission.noControl');
  3806. 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 ${
  3807. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  3808. }`;
  3809. // Chamber fan only exists on enclosed Bambu models. Open-frame
  3810. // printers (A1, A1 Mini, A2L, P1P) have no chamber fan — showing
  3811. // the widget there is at best dead UI and at worst suggests a
  3812. // control that does nothing. Mirrors the enclosure-door badge
  3813. // gate above.
  3814. const hasChamberFan = MODELS_WITH_CHAMBER_FAN.has(printer.model ?? '');
  3815. // On P2S/X2D the big_fan2 fan is the dedicated chamber EXHAUST fan
  3816. // ("Exhaust" in Bambu's naming) and is an add-on kit, not preinstalled:
  3817. // show it only when the printer actually reports it (airduct part id 3,
  3818. // surfaced as exhaust_fan_present). Other enclosed models (X1/P1S/H2*)
  3819. // have a built-in chamber fan that's always present, so they keep the
  3820. // existing model-list gate and the "Chamber Fan" label.
  3821. const isExhaustModel = MODELS_WITH_EXHAUST_LABEL.has(printer.model ?? '');
  3822. const chamberFanLabel = isExhaustModel
  3823. ? t('printers.fans.exhaust')
  3824. : t('printers.fans.chamber');
  3825. // Composed rather than either/or so both lists stay live for
  3826. // P2S/X2D: the model must have an enclosure fan at all, AND —
  3827. // where that fan is an add-on kit — actually report it. Written
  3828. // as `isExhaustModel ? exhaust_fan_present : hasChamberFan` the
  3829. // P2S/X2D entries in MODELS_WITH_CHAMBER_FAN became unreachable,
  3830. // which reads as if removing them were safe.
  3831. const showChamberFan = hasChamberFan && (!isExhaustModel || status.exhaust_fan_present);
  3832. const fanItems: {
  3833. key: string;
  3834. label: string;
  3835. value: number;
  3836. Icon: typeof Fan;
  3837. activeClass: string;
  3838. }[] = [
  3839. {
  3840. key: 'part',
  3841. label: t('printers.fans.partCooling'),
  3842. value: status.cooling_fan_speed ?? 0,
  3843. Icon: Fan,
  3844. activeClass: 'text-cyan-600 dark:text-cyan-400',
  3845. },
  3846. // Left auxiliary part cooling fan (optional P2S/X2D accessory).
  3847. // Only reported (non-null) when the firmware lists airduct part
  3848. // id 10, i.e. when the fan is physically installed. Placed
  3849. // before the right-hand auxiliary fan so the two aux badges read
  3850. // left-to-right in the same order as the physical hardware.
  3851. ...(status.left_aux_fan_speed != null
  3852. ? [
  3853. {
  3854. key: 'aux2',
  3855. label: t('printers.fans.leftAuxiliary'),
  3856. value: status.left_aux_fan_speed,
  3857. Icon: Wind,
  3858. activeClass: 'text-indigo-600 dark:text-indigo-400',
  3859. },
  3860. ]
  3861. : []),
  3862. {
  3863. key: 'aux',
  3864. label: t('printers.fans.auxiliary'),
  3865. value: status.big_fan1_speed ?? 0,
  3866. Icon: Wind,
  3867. activeClass: 'text-blue-600 dark:text-blue-400',
  3868. },
  3869. ...(showChamberFan
  3870. ? [
  3871. {
  3872. key: 'chamber',
  3873. label: chamberFanLabel,
  3874. value: status.big_fan2_speed ?? 0,
  3875. Icon: AirVent,
  3876. activeClass: 'text-green-600 dark:text-green-400',
  3877. },
  3878. ]
  3879. : []),
  3880. ];
  3881. return (
  3882. <>
  3883. <div className="mt-2 flex items-stretch gap-1.5 flex-wrap">
  3884. {/* Nozzle temp - combined for dual nozzle */}
  3885. <div
  3886. className={statusControlClass}
  3887. title={statusControlTitle}
  3888. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-temp' ? null : 'nozzle-temp')}
  3889. >
  3890. <button
  3891. type="button"
  3892. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3893. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3894. onClick={(e) => {
  3895. e.stopPropagation();
  3896. setHeaterHistoryModal({ initialKind: 'nozzle', availableKinds: availableHeaterKinds });
  3897. }}
  3898. >
  3899. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  3900. </button>
  3901. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-orange-400" isHeating={nozzleHeating} />
  3902. {status.temperatures.nozzle_2 !== undefined ? (
  3903. <>
  3904. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">L / R</p>
  3905. <p className="text-[length:var(--pc-t11,11px)] text-white">
  3906. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  3907. </p>
  3908. </>
  3909. ) : singleNozzleSlot ? (
  3910. <NozzleSlotHoverCard slot={singleNozzleSlot} index={0} activeStatus filamentName={singleNozzleSlot.filament_id ? filamentInfo?.[singleNozzleSlot.filament_id]?.name : undefined}>
  3911. <div className="cursor-default">
  3912. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3913. <p className="text-[length:var(--pc-t11,11px)] text-white">
  3914. {Math.round(status.temperatures.nozzle || 0)}°C
  3915. </p>
  3916. </div>
  3917. </NozzleSlotHoverCard>
  3918. ) : (
  3919. <>
  3920. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  3921. <p className="text-[length:var(--pc-t11,11px)] text-white">
  3922. {Math.round(status.temperatures.nozzle || 0)}°C
  3923. </p>
  3924. </>
  3925. )}
  3926. {statusControlMenu === 'nozzle-temp' && (
  3927. isDualNozzle ? (
  3928. <IndicatorControlPopover
  3929. title="Set Nozzle Temperatures"
  3930. widthClass="w-[300px]"
  3931. popoverWidth={300}
  3932. popoverHeight={260}
  3933. isPending={nozzleTemperatureMutation.isPending}
  3934. onClose={() => setStatusControlMenu(null)}
  3935. >
  3936. <div className="grid grid-cols-2 gap-2 px-3 py-2.5">
  3937. <NozzleTemperatureControlBox
  3938. label="Left Temp"
  3939. current={status.temperatures.nozzle}
  3940. target={status.temperatures.nozzle_target}
  3941. isActive={activeNozzle === 'L'}
  3942. isPending={nozzleTemperatureMutation.isPending}
  3943. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 1 })}
  3944. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3945. />
  3946. <NozzleTemperatureControlBox
  3947. label="Right Temp"
  3948. current={status.temperatures.nozzle_2}
  3949. target={status.temperatures.nozzle_2_target}
  3950. isActive={activeNozzle === 'R'}
  3951. isPending={nozzleTemperatureMutation.isPending}
  3952. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: 0 })}
  3953. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3954. />
  3955. </div>
  3956. </IndicatorControlPopover>
  3957. ) : (
  3958. <IndicatorControlPopover
  3959. title="Set Nozzle Temperature"
  3960. unit="°C"
  3961. customMin={0}
  3962. customMax={320}
  3963. isPending={nozzleTemperatureMutation.isPending}
  3964. options={buildPresetOptions(nozzleTempPresets, 'C')}
  3965. onClose={() => setStatusControlMenu(null)}
  3966. onSubmit={(target) => nozzleTemperatureMutation.mutate({ target, nozzle: status.active_extruder ?? 0 })}
  3967. />
  3968. )
  3969. )}
  3970. </div>
  3971. <div
  3972. className={statusControlClass}
  3973. title={statusControlTitle}
  3974. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'bed-temp' ? null : 'bed-temp')}
  3975. >
  3976. <button
  3977. type="button"
  3978. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  3979. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  3980. onClick={(e) => {
  3981. e.stopPropagation();
  3982. setHeaterHistoryModal({ initialKind: 'bed', availableKinds: availableHeaterKinds });
  3983. }}
  3984. >
  3985. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  3986. </button>
  3987. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-blue-400" isHeating={bedHeating} />
  3988. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.bed')}</p>
  3989. <p className="text-[length:var(--pc-t11,11px)] text-white">
  3990. {Math.round(status.temperatures.bed || 0)}°C
  3991. </p>
  3992. {statusControlMenu === 'bed-temp' && (
  3993. <IndicatorControlPopover
  3994. title="Set Bed Temperature"
  3995. unit="°C"
  3996. customMin={0}
  3997. customMax={140}
  3998. isPending={bedTemperatureMutation.isPending}
  3999. options={buildPresetOptions(bedTempPresets, 'C')}
  4000. onClose={() => setStatusControlMenu(null)}
  4001. onSubmit={(target) => bedTemperatureMutation.mutate(target)}
  4002. />
  4003. )}
  4004. </div>
  4005. {status.temperatures.chamber !== undefined && (() => {
  4006. // Sensor-only models (X1C, X1E, P2S) show the chamber reading
  4007. // but can't act on M141, so we keep the card read-only there.
  4008. const hasChamberHeater = status.supports_chamber_heater === true;
  4009. return (
  4010. <div
  4011. className={hasChamberHeater
  4012. ? statusControlClass
  4013. : 'relative text-center px-2 py-1.5 bg-bambu-dark rounded-lg flex-1 flex flex-col justify-center items-center'}
  4014. title={hasChamberHeater ? statusControlTitle : undefined}
  4015. onClick={hasChamberHeater
  4016. ? () => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'chamber-temp' ? null : 'chamber-temp')
  4017. : undefined}
  4018. >
  4019. <button
  4020. type="button"
  4021. className="absolute top-0.5 right-0.5 p-0.5 rounded text-bambu-gray hover:text-white hover:bg-white/10 transition-colors"
  4022. title={t('printers.heaterHistory.openLabel', 'View heater history')}
  4023. onClick={(e) => {
  4024. e.stopPropagation();
  4025. setHeaterHistoryModal({ initialKind: 'chamber', availableKinds: availableHeaterKinds });
  4026. }}
  4027. >
  4028. <LineChartIcon className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  4029. </button>
  4030. <HeaterThermometer className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5" color="text-green-400" isHeating={chamberHeating} />
  4031. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.chamber')}</p>
  4032. <p className="text-[length:var(--pc-t11,11px)] text-white">
  4033. {Math.round(status.temperatures.chamber || 0)}°C
  4034. </p>
  4035. {hasChamberHeater && statusControlMenu === 'chamber-temp' && (
  4036. <IndicatorControlPopover
  4037. title="Set Chamber Temperature"
  4038. unit="°C"
  4039. customMin={0}
  4040. customMax={MAX_CHAMBER_TEMP_C}
  4041. isPending={chamberTemperatureMutation.isPending}
  4042. options={buildPresetOptions(chamberTempPresets, 'C')}
  4043. onClose={() => setStatusControlMenu(null)}
  4044. onSubmit={(target) => chamberTemperatureMutation.mutate(target)}
  4045. />
  4046. )}
  4047. </div>
  4048. );
  4049. })()}
  4050. {/* Active nozzle indicator for dual-nozzle printers */}
  4051. {isDualNozzle && (
  4052. <DualNozzleHoverCard
  4053. leftSlot={leftNozzleSlot}
  4054. rightSlot={rightNozzleSlot}
  4055. activeNozzle={activeNozzle}
  4056. filamentInfo={filamentInfo}
  4057. >
  4058. <div
  4059. 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 ${
  4060. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4061. }`}
  4062. title={canUseStatusControls ? t('printers.activeNozzle', { nozzle: activeNozzle === 'L' ? t('common.left') : t('common.right') }) : statusControlTitle}
  4063. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === 'nozzle-select' ? null : 'nozzle-select')}
  4064. >
  4065. <NozzleIcon className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] mb-0.5 text-amber-600 dark:text-amber-400" />
  4066. <div className="flex items-center gap-2">
  4067. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'L' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4068. L{leftNozzleSlot?.nozzle_diameter ? ` ${leftNozzleSlot.nozzle_diameter}` : ''}
  4069. </span>
  4070. <span className="text-[length:var(--pc-t9,9px)] text-bambu-gray/40">·</span>
  4071. <span className={`text-[length:var(--pc-t11,11px)] font-bold ${activeNozzle === 'R' ? 'text-amber-700 dark:text-amber-400' : 'text-gray-500'}`}>
  4072. R{rightNozzleSlot?.nozzle_diameter ? ` ${rightNozzleSlot.nozzle_diameter}` : ''}
  4073. </span>
  4074. </div>
  4075. <p className="text-[length:var(--pc-t9,9px)] text-bambu-gray">{t('printers.temperatures.nozzle')}</p>
  4076. {statusControlMenu === 'nozzle-select' && (
  4077. <IndicatorControlPopover
  4078. title="Set Nozzle Selection"
  4079. widthClass="w-[300px]"
  4080. popoverWidth={300}
  4081. popoverHeight={140}
  4082. isPending={selectExtruderMutation.isPending}
  4083. options={[
  4084. { label: 'Left', value: 1 },
  4085. { label: 'Right', value: 0 },
  4086. ]}
  4087. onClose={() => setStatusControlMenu(null)}
  4088. onSubmit={(extruder) => selectExtruderMutation.mutate(extruder)}
  4089. />
  4090. )}
  4091. </div>
  4092. </DualNozzleHoverCard>
  4093. )}
  4094. {/* H2C nozzle rack (tool-changer dock) — only show when rack nozzles exist (IDs >= 2) */}
  4095. {status.nozzle_rack && status.nozzle_rack.some(s => s.id >= 2) && (
  4096. <NozzleRackCard slots={status.nozzle_rack} filamentInfo={filamentInfo} />
  4097. )}
  4098. </div>
  4099. <div className="mt-2 flex items-center gap-1.5">
  4100. {fanItems.map(({ key, label, value, Icon, activeClass }) => {
  4101. const active = value > 0;
  4102. return (
  4103. <div
  4104. key={key}
  4105. 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 ${
  4106. canUseStatusControls ? 'cursor-pointer hover:bg-bambu-dark-tertiary' : 'cursor-default opacity-80'
  4107. }`}
  4108. title={canUseStatusControls ? label : statusControlTitle}
  4109. onClick={() => canUseStatusControls && setStatusControlMenu(statusControlMenu === `fan-${key}` ? null : `fan-${key}`)}
  4110. >
  4111. <Icon className={`w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] shrink-0 ${active ? activeClass : 'text-bambu-gray/50'}`} />
  4112. <span className={`text-[length:var(--pc-t10,10px)] leading-none ${active ? 'text-white' : 'text-bambu-gray/50'}`}>
  4113. {value}%
  4114. </span>
  4115. {statusControlMenu === `fan-${key}` && (
  4116. <IndicatorControlPopover
  4117. title={`Set ${label} Speed`}
  4118. unit="%"
  4119. customMin={0}
  4120. customMax={100}
  4121. isPending={fanSpeedMutation.isPending}
  4122. options={buildPresetOptions(fanSpeedPresets, '%')}
  4123. onClose={() => setStatusControlMenu(null)}
  4124. onSubmit={(speed) => fanSpeedMutation.mutate({ fan: key as 'part' | 'aux' | 'aux2' | 'chamber', speed })}
  4125. />
  4126. )}
  4127. </div>
  4128. );
  4129. })}
  4130. </div>
  4131. </>
  4132. );
  4133. })()}
  4134. {viewMode === 'expanded' && showClearPlateButton && (
  4135. <button
  4136. type="button"
  4137. onClick={() => clearPlateMutation.mutate()}
  4138. disabled={clearPlateMutation.isPending || !hasPermission('printers:clear_plate')}
  4139. 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"
  4140. title={!hasPermission('printers:clear_plate') ? t('printers.permission.noControl') : t('printers.plateStatus.markCleared')}
  4141. >
  4142. {clearPlateMutation.isPending ? (
  4143. <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" />
  4144. ) : (
  4145. <PlateClearedIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4146. )}
  4147. {t('printers.plateStatus.markCleared')}
  4148. </button>
  4149. )}
  4150. {/* Controls */}
  4151. {viewMode === 'expanded' && (() => {
  4152. // Determine print state for control buttons
  4153. const isRunning = status.state === 'RUNNING';
  4154. const isPaused = status.state === 'PAUSE';
  4155. const isPrinting = isRunning || isPaused;
  4156. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  4157. const unavailablePrintActionClass = 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed opacity-50';
  4158. 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';
  4159. const printControlClass = 'flex h-8 w-20 items-center justify-center gap-1 px-2 rounded-lg text-xs font-medium transition-colors';
  4160. return (
  4161. <div className="mt-3">
  4162. {/* Section Header */}
  4163. <div className="flex items-center gap-2 mb-2">
  4164. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4165. {t('printers.controls')}
  4166. </span>
  4167. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4168. </div>
  4169. <div className="flex flex-wrap items-start justify-between gap-x-2 gap-y-2">
  4170. {/* Left: Secondary controls */}
  4171. <div className="flex flex-wrap items-center gap-2 min-w-0">
  4172. <button
  4173. onClick={() => chamberLightMutation.mutate(!status.chamber_light)}
  4174. disabled={!status.connected || chamberLightMutation.isPending || !hasPermission('printers:control')}
  4175. className={`${iconControlClass} ${
  4176. status.chamber_light
  4177. ? 'bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/20'
  4178. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4179. }`}
  4180. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (status.chamber_light ? t('printers.chamberLightOff') : t('printers.chamberLightOn'))}
  4181. >
  4182. <ChamberLight on={status.chamber_light ?? false} className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4183. </button>
  4184. {/* Airduct Mode (P2S / X2D / H2*) */}
  4185. {(['P2S', 'X2D', 'H2D', 'H2C', 'H2S'].includes(printer.model ?? '')) && (() => {
  4186. const isHeating = status.airduct_mode === 1;
  4187. const Icon = isHeating ? Flame : Snowflake;
  4188. const color = isHeating ? 'text-orange-600 dark:text-orange-400' : 'text-sky-600 dark:text-sky-400';
  4189. 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';
  4190. return (
  4191. <div className="relative">
  4192. <button
  4193. onClick={() => setShowAirductMenu(showAirductMenu === printer.id ? null : printer.id)}
  4194. disabled={!hasPermission('printers:control')}
  4195. className={`${iconControlClass} ${bg}`}
  4196. title={`${t('printers.airduct.title')}: ${isHeating ? t('printers.airduct.heating') : t('printers.airduct.cooling')}`}
  4197. >
  4198. <Icon className={`w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] ${color}`} />
  4199. </button>
  4200. {showAirductMenu === printer.id && (
  4201. <>
  4202. <div className="fixed inset-0 z-40" onClick={() => setShowAirductMenu(null)} />
  4203. <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]">
  4204. {([
  4205. { mode: 'cooling', label: t('printers.airduct.cooling'), modeId: 0 },
  4206. { mode: 'heating', label: t('printers.airduct.heating'), modeId: 1 },
  4207. ] as const).map(({ mode, label, modeId }) => (
  4208. <button
  4209. key={mode}
  4210. onClick={() => {
  4211. airductMutation.mutate(mode);
  4212. setShowAirductMenu(null);
  4213. }}
  4214. className={`w-full text-left px-3 py-1.5 text-xs transition-colors flex items-center gap-2 ${
  4215. status.airduct_mode === modeId
  4216. ? 'text-bambu-green bg-bambu-green/10'
  4217. : 'text-white hover:bg-bambu-dark-tertiary'
  4218. }`}
  4219. >
  4220. {mode === 'heating' ? <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Snowflake className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4221. {label}
  4222. </button>
  4223. ))}
  4224. </div>
  4225. </>
  4226. )}
  4227. </div>
  4228. );
  4229. })()}
  4230. {/* Movement — compact badge, popover holds XY, Z, and home controls */}
  4231. {(() => {
  4232. const canControl = hasPermission('printers:control');
  4233. const disabled = isPrinting || !canControl;
  4234. const bambuIsPlateBelow = true; // positive Z moves plate away from nozzle
  4235. 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';
  4236. const requestZJog = (direction: 1 | -1) => {
  4237. const signed = direction * bedJogStep * (bambuIsPlateBelow ? 1 : -1);
  4238. // The jog never disables the soft endstops (#2579), so it's always
  4239. // safe: the firmware clamps the move at the travel limit, or refuses
  4240. // it if the printer isn't homed. No not-homed bypass to gate.
  4241. bedJogMutation.mutate({ distance: signed });
  4242. };
  4243. const requestXyJog = (x: number, y: number) => {
  4244. xyJogMutation.mutate({ x, y });
  4245. };
  4246. const requestExtruderJog = (distance: number) => {
  4247. extruderJogMutation.mutate(distance);
  4248. };
  4249. return (
  4250. <div className="relative">
  4251. <button
  4252. onClick={() => setShowBedJogMenu(showBedJogMenu === printer.id ? null : printer.id)}
  4253. disabled={disabled}
  4254. className={`${iconControlClass} ${
  4255. disabled
  4256. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4257. : 'bg-indigo-50 dark:bg-indigo-500/10 text-indigo-700 dark:text-indigo-400 hover:bg-indigo-500/20'
  4258. }`}
  4259. title={!canControl ? t('printers.permission.noControl') : isPrinting ? t('printers.bedJog.disabledWhilePrinting') : t('printers.bedJog.title')}
  4260. >
  4261. <Move className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4262. </button>
  4263. {showBedJogMenu === printer.id && (
  4264. <>
  4265. <div className="fixed inset-0 z-40" onClick={() => setShowBedJogMenu(null)} />
  4266. <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">
  4267. <div className="shrink-0 px-3 py-2.5 text-center text-sm font-medium text-white">
  4268. {t('printers.bedJog.title')}
  4269. </div>
  4270. <div className="h-px bg-bambu-dark-tertiary" />
  4271. {/* #2579: Bambu firmware does not enforce soft endstops on
  4272. G-code sent over MQTT, so manual moves can drive past the
  4273. travel limits and cause a collision. Not fixable from our
  4274. side — warn prominently. */}
  4275. <div className="flex items-start gap-1.5 bg-yellow-500/10 px-3 py-2 text-[length:var(--pc-t11,11px)] leading-snug text-yellow-700 dark:text-yellow-400">
  4276. <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
  4277. <span>{t('printers.bedJog.limitWarning')}</span>
  4278. </div>
  4279. <div className="h-px bg-bambu-dark-tertiary" />
  4280. <div className="flex justify-center px-3 py-2.5">
  4281. <div className="flex items-center justify-center gap-3">
  4282. <div className="grid grid-cols-3 gap-1">
  4283. <div />
  4284. <button
  4285. onClick={() => requestXyJog(0, bedJogStep)}
  4286. disabled={xyJogMutation.isPending}
  4287. className={jogButtonClass}
  4288. aria-label="Move Y forward"
  4289. >
  4290. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4291. </button>
  4292. <div />
  4293. <button
  4294. onClick={() => requestXyJog(-bedJogStep, 0)}
  4295. disabled={xyJogMutation.isPending}
  4296. className={jogButtonClass}
  4297. aria-label="Move X left"
  4298. >
  4299. <ArrowLeft className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4300. </button>
  4301. <button
  4302. onClick={() => {
  4303. setShowBedJogMenu(null);
  4304. homeAxesMutation.mutate('all');
  4305. }}
  4306. disabled={homeAxesMutation.isPending}
  4307. className={jogButtonClass}
  4308. aria-label={t('printers.bedJog.homeZ')}
  4309. >
  4310. <Home className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4311. </button>
  4312. <button
  4313. onClick={() => requestXyJog(bedJogStep, 0)}
  4314. disabled={xyJogMutation.isPending}
  4315. className={jogButtonClass}
  4316. aria-label="Move X right"
  4317. >
  4318. <ArrowRight className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4319. </button>
  4320. <div />
  4321. <button
  4322. onClick={() => requestXyJog(0, -bedJogStep)}
  4323. disabled={xyJogMutation.isPending}
  4324. className={jogButtonClass}
  4325. aria-label="Move Y back"
  4326. >
  4327. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4328. </button>
  4329. <div />
  4330. </div>
  4331. <div className="flex flex-col items-center gap-1">
  4332. <button
  4333. onClick={() => requestZJog(-1)}
  4334. disabled={bedJogMutation.isPending}
  4335. className={jogButtonClass}
  4336. aria-label={t('printers.bedJog.up')}
  4337. >
  4338. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4339. </button>
  4340. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4341. <Layers className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4342. </div>
  4343. <button
  4344. onClick={() => requestZJog(1)}
  4345. disabled={bedJogMutation.isPending}
  4346. className={jogButtonClass}
  4347. aria-label={t('printers.bedJog.down')}
  4348. >
  4349. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4350. </button>
  4351. </div>
  4352. <div className="flex flex-col items-center gap-1">
  4353. <button
  4354. onClick={() => requestExtruderJog(-bedJogStep)}
  4355. disabled={extruderJogMutation.isPending}
  4356. className={jogButtonClass}
  4357. aria-label="Retract filament"
  4358. >
  4359. <ArrowUp className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4360. </button>
  4361. <div className="flex h-8 w-8 items-center justify-center text-bambu-gray/80">
  4362. <span className="text-sm font-semibold leading-none">E</span>
  4363. </div>
  4364. <button
  4365. onClick={() => requestExtruderJog(bedJogStep)}
  4366. disabled={extruderJogMutation.isPending}
  4367. className={jogButtonClass}
  4368. aria-label="Extrude filament"
  4369. >
  4370. <ArrowDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4371. </button>
  4372. </div>
  4373. </div>
  4374. </div>
  4375. <div className="h-px bg-bambu-dark-tertiary" />
  4376. <div className="px-3 pt-2.5 pb-3">
  4377. <div className="mb-1 text-[length:var(--pc-t9,9px)] uppercase tracking-wider text-bambu-gray/70">
  4378. {t('printers.bedJog.step')}
  4379. </div>
  4380. <div className="flex gap-1">
  4381. {[1, 10, 50].map((step) => (
  4382. <button
  4383. key={step}
  4384. onClick={() => setBedJogStep(step)}
  4385. className={`flex-1 px-1 py-1 rounded text-[length:var(--pc-t10,10px)] transition-colors ${
  4386. bedJogStep === step
  4387. ? 'bg-bambu-green/20 text-bambu-green'
  4388. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  4389. }`}
  4390. >
  4391. {step}
  4392. </button>
  4393. ))}
  4394. </div>
  4395. </div>
  4396. </div>
  4397. </>
  4398. )}
  4399. </div>
  4400. );
  4401. })()}
  4402. <div className={`inline-flex rounded-lg ${printer.plate_detection_enabled ? 'ring-1 ring-green-500' : ''}`}>
  4403. <button
  4404. onClick={handleTogglePlateDetection}
  4405. disabled={!status.connected || plateDetectionMutation.isPending || !hasPermission('printers:update')}
  4406. className={`${iconControlClass} rounded-r-none ${
  4407. printer.plate_detection_enabled
  4408. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4409. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4410. }`}
  4411. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : (printer.plate_detection_enabled ? t('printers.plateDetection.enabledClick') : t('printers.plateDetection.disabledClick'))}
  4412. >
  4413. {plateDetectionMutation.isPending ? (
  4414. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4415. ) : (
  4416. <ScanSearch className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4417. )}
  4418. </button>
  4419. <button
  4420. onClick={handleOpenPlateManagement}
  4421. disabled={!status.connected || isCheckingPlate || !hasPermission('printers:update')}
  4422. 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 ${
  4423. printer.plate_detection_enabled
  4424. ? 'bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 hover:bg-green-500/20'
  4425. : 'bg-bambu-dark text-bambu-gray/50 hover:bg-bambu-dark-tertiary hover:text-white'
  4426. }`}
  4427. title={!hasPermission('printers:update') ? t('printers.plateDetection.noPermission') : t('printers.plateDetection.manageCalibration')}
  4428. >
  4429. {isCheckingPlate ? (
  4430. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] animate-spin" />
  4431. ) : (
  4432. <ChevronDown className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4433. )}
  4434. </button>
  4435. </div>
  4436. {/* Print Speed */}
  4437. {(() => (
  4438. <div className="relative">
  4439. <button
  4440. data-testid="speed-control"
  4441. onClick={() => setShowSpeedMenu(showSpeedMenu === printer.id ? null : printer.id)}
  4442. disabled={!isPrinting || !hasPermission('printers:control')}
  4443. className={`${iconControlClass} ${
  4444. isPrinting
  4445. ? 'bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-400 hover:bg-amber-500/20'
  4446. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4447. }`}
  4448. title={isPrinting ? t('printers.speed.title') : undefined}
  4449. >
  4450. <Gauge className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  4451. </button>
  4452. {showSpeedMenu === printer.id && (
  4453. <>
  4454. <div className="fixed inset-0 z-40" onClick={() => setShowSpeedMenu(null)} />
  4455. <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]">
  4456. {([
  4457. { mode: 1, label: t('printers.speed.silent') },
  4458. { mode: 2, label: t('printers.speed.standard') },
  4459. { mode: 3, label: t('printers.speed.sport') },
  4460. { mode: 4, label: t('printers.speed.ludicrous') },
  4461. ] as const).map(({ mode, label }) => (
  4462. <button
  4463. key={mode}
  4464. onClick={() => {
  4465. printSpeedMutation.mutate(mode);
  4466. setShowSpeedMenu(null);
  4467. }}
  4468. className={`w-full text-left px-3 py-1.5 text-xs transition-colors ${
  4469. status.speed_level === mode
  4470. ? 'text-bambu-green bg-bambu-green/10'
  4471. : 'text-white hover:bg-bambu-dark-tertiary'
  4472. }`}
  4473. >
  4474. {label}
  4475. </button>
  4476. ))}
  4477. </div>
  4478. </>
  4479. )}
  4480. </div>
  4481. ))()}
  4482. </div>
  4483. {/* Right: Print Control Buttons */}
  4484. <div className="ml-auto flex items-center justify-end gap-2 flex-shrink-0">
  4485. {/* Pause/Resume button */}
  4486. {(() => {
  4487. const pauseUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4488. return (
  4489. <button
  4490. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  4491. disabled={pauseUnavailable}
  4492. className={`
  4493. ${printControlClass}
  4494. ${pauseUnavailable
  4495. ? unavailablePrintActionClass
  4496. : isPaused
  4497. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  4498. : 'bg-yellow-100 dark:bg-yellow-500/20 text-yellow-700 dark:text-yellow-400 hover:bg-yellow-500/30'
  4499. }
  4500. `}
  4501. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : (isPaused ? t('printers.resume') : t('printers.pause'))}
  4502. >
  4503. {isPaused ? <Play className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" /> : <Pause className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />}
  4504. {isPaused ? t('printers.resume') : t('printers.pause')}
  4505. </button>
  4506. );
  4507. })()}
  4508. {/* Stop button */}
  4509. {(() => {
  4510. const stopUnavailable = !isPrinting || isControlBusy || !hasPermission('printers:control');
  4511. return (
  4512. <button
  4513. onClick={() => setShowStopConfirm(true)}
  4514. disabled={stopUnavailable}
  4515. className={`
  4516. ${printControlClass}
  4517. ${stopUnavailable
  4518. ? unavailablePrintActionClass
  4519. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400 hover:bg-red-500/30'
  4520. }
  4521. `}
  4522. title={!hasPermission('printers:control') ? t('printers.permission.noControl') : t('printers.stop')}
  4523. >
  4524. <Square className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4525. {t('printers.stop')}
  4526. </button>
  4527. );
  4528. })()}
  4529. </div>
  4530. </div>
  4531. </div>
  4532. );
  4533. })()}
  4534. {/* AMS Units - 2-Column Grid Layout */}
  4535. {(amsData?.length > 0 || status.vt_tray.length > 0) && viewMode === 'expanded' && (() => {
  4536. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  4537. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  4538. const htAms = amsData.filter(ams => ams.tray.length === 1);
  4539. // The external spool can only be hidden while some AMS remains to
  4540. // fill the row (#1782). On an A1 Mini or a bare P1P it is the whole
  4541. // filament section, so the toggle is not offered there and a stored
  4542. // preference from a printer that later lost its AMS cannot blank the
  4543. // row either — both read through canHideExternalSpool.
  4544. const canHideExternalSpool = amsData.length > 0 && status.vt_tray.length > 0;
  4545. const showExternalSpool = !(canHideExternalSpool && externalSpoolHidden);
  4546. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  4547. const bodyScale = CARD_BODY_SCALE[cardSize] ?? 1;
  4548. // Rounded because 11 * 1.2 is 13.200000000000001 in binary
  4549. // floating point, and that lands verbatim in the DOM.
  4550. const scaledRem = (base: number) => `${Math.round(base * bodyScale * 1000) / 1000}rem`;
  4551. // Deliberately NOT scaled with the body (#1848). These AMS cards
  4552. // already grow to fill the row, so the 3.5rem is a floor they sit
  4553. // well above in practice -- raising it just costs a unit its place
  4554. // on the row. Losing one matters: a wrapped AMS-HT is then alone on
  4555. // its line, and flex-grow stretches its single slot across the whole
  4556. // card. The AMS-HT's own width does scale, below, because its
  4557. // readings sit beside the slot rather than under it.
  4558. const slotMinWidth = '3.5rem';
  4559. const filamentSlotStyle: React.CSSProperties = { minWidth: slotMinWidth };
  4560. // The AMS-HT holds a single spool, and its slot is the only thing
  4561. // on that row able to grow -- so it swallowed every spare pixel and
  4562. // shoved the temperature and humidity hard against the card's edge.
  4563. // Capping it at roughly two ordinary slots keeps the readings clear
  4564. // of the edge; the cap scales because the text inside the slot does.
  4565. const htSlotStyle: React.CSSProperties = {
  4566. minWidth: slotMinWidth,
  4567. maxWidth: scaledRem(7.25),
  4568. };
  4569. const slotGridStyle = (columns: number): React.CSSProperties => ({
  4570. gridTemplateColumns: `repeat(${columns}, minmax(${slotMinWidth}, 1fr))`,
  4571. });
  4572. // #1762 (comment 2): while a print is running/paused, overlay a small
  4573. // "P1 / P2 / P3" pill on each slot referenced by the active print's
  4574. // mapping. Catches the reporter's scenario — "any X1C" queue job
  4575. // staged to a printer with mismatched filament: the wrong-slot pill
  4576. // is visible the instant printing starts.
  4577. const isPrintingForMapping = status.state === 'RUNNING' || status.state === 'PAUSE';
  4578. const activeMapping: number[] = isPrintingForMapping && Array.isArray(status.ams_mapping)
  4579. ? status.ams_mapping
  4580. : [];
  4581. const getAmsCardStyle = (slotCount: number): React.CSSProperties => {
  4582. const boundedSlotCount = Math.max(1, slotCount);
  4583. const gapCount = Math.max(0, boundedSlotCount - 1);
  4584. const minWidth = `calc(${boundedSlotCount} * ${slotMinWidth} + ${gapCount} * 0.25rem + 1rem)`;
  4585. return {
  4586. flex: `1 1 ${minWidth}`,
  4587. minWidth,
  4588. };
  4589. };
  4590. return (
  4591. <div className="mt-3">
  4592. {/* Section Header */}
  4593. <div className="flex items-center gap-2 mb-2">
  4594. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  4595. {t('printers.filaments')}
  4596. </span>
  4597. <AmsBackupBadge
  4598. state={status.ams_filament_backup}
  4599. onClick={() => setAmsBackupModalOpen(true)}
  4600. />
  4601. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  4602. {/* Offered only when an AMS is present: on a printer that
  4603. feeds from the external spool alone, hiding it would
  4604. empty the row entirely (#1782). */}
  4605. {canHideExternalSpool && (
  4606. <>
  4607. <ExternalSpoolToggle
  4608. hidden={externalSpoolHidden}
  4609. onClick={toggleExternalSpool}
  4610. />
  4611. <div className="w-3 h-[2px] bg-bambu-dark-tertiary" />
  4612. </>
  4613. )}
  4614. </div>
  4615. {/* AMS Content */}
  4616. <div className="flex flex-wrap gap-2">
  4617. {/* Regular AMS units */}
  4618. {regularAms.map((ams) => {
  4619. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  4620. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  4621. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  4622. const isLeftNozzle = extruderId === 1;
  4623. const isRightNozzle = extruderId === 0;
  4624. return (
  4625. <div key={ams.id} style={getAmsCardStyle(4)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  4626. {/* Header: Label + Stats (no icon) */}
  4627. <div className="flex w-full min-h-7 items-center justify-between gap-2 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  4628. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  4629. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  4630. <AmsNameHoverCard
  4631. ams={ams}
  4632. printerId={printer.id}
  4633. label={getAmsLabel(ams.id, ams.tray.length)}
  4634. amsLabels={amsLabels}
  4635. canEdit={hasPermission('printers:update')}
  4636. onSaved={refetchAmsLabels}
  4637. >
  4638. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  4639. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  4640. </span>
  4641. </AmsNameHoverCard>
  4642. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  4643. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  4644. )}
  4645. </div>
  4646. {(ams.humidity != null || ams.temp != null) && (
  4647. <div className="flex shrink-0 items-center gap-1.5">
  4648. {ams.humidity != null && (
  4649. <HumidityIndicator
  4650. humidity={ams.humidity}
  4651. goodThreshold={amsThresholds?.humidityGood}
  4652. fairThreshold={amsThresholds?.humidityFair}
  4653. onClick={() => setAmsHistoryModal({
  4654. amsId: ams.id,
  4655. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4656. mode: 'humidity',
  4657. })}
  4658. compact
  4659. />
  4660. )}
  4661. {ams.temp != null && (
  4662. <div className="mr-1">
  4663. <TemperatureIndicator
  4664. temp={ams.temp}
  4665. goodThreshold={amsThresholds?.tempGood}
  4666. fairThreshold={amsThresholds?.tempFair}
  4667. onClick={() => setAmsHistoryModal({
  4668. amsId: ams.id,
  4669. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  4670. mode: 'temperature',
  4671. })}
  4672. compact
  4673. />
  4674. </div>
  4675. )}
  4676. {/* Drying button — only for AMS 2 Pro (n3f) and AMS-HT (n3s).
  4677. Screen-only models (P1 series) keep the control but can't
  4678. be commanded: it stays disabled and says why (#2533). */}
  4679. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  4680. <button
  4681. disabled={status.drying_screen_only || !!(ams.dry_sf_reason?.length && ams.dry_time === 0)}
  4682. onClick={(e) => {
  4683. if (ams.dry_time > 0) {
  4684. stopDryingMutation.mutate(ams.id);
  4685. } else if (dryingPopoverAmsId === ams.id) {
  4686. setDryingPopoverAmsId(null);
  4687. } else {
  4688. const firstTray = ams.tray.find(t => t.tray_type);
  4689. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  4690. // Only reachable if a custom preset set dropped PLA itself.
  4691. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  4692. const moduleType = ams.module_type as 'n3f' | 'n3s';
  4693. setDryingFilament(filType);
  4694. setDryingTemp(preset[moduleType] || preset.n3f);
  4695. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  4696. setDryingRotateTray(false);
  4697. setDryingPopoverModuleType(ams.module_type);
  4698. setDryingPopoverAmsId(ams.id);
  4699. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  4700. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  4701. }
  4702. }}
  4703. className={`ml-1 flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  4704. ams.dry_time > 0
  4705. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  4706. : status.drying_screen_only || ams.dry_sf_reason?.length
  4707. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  4708. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  4709. }`}
  4710. 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')}
  4711. >
  4712. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4713. </button>
  4714. )}
  4715. </div>
  4716. )}
  4717. </div>
  4718. {/* Drying status bar */}
  4719. {ams.dry_time > 0 && (
  4720. <div className="flex items-center gap-2 rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  4721. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  4722. <span className="text-amber-700 dark:text-amber-400 font-medium">{t('printers.drying.active')}</span>
  4723. {/* The temperature is only ever known from the target we
  4724. cached when sending the command — the filament can also
  4725. be read off a uniformly loaded unit, so it can outlive
  4726. the temperature (#2759). */}
  4727. {ams.dry_filament && (
  4728. <span className="text-amber-700/80 dark:text-amber-300/70">
  4729. {ams.dry_target_temp != null
  4730. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  4731. : ams.dry_filament}
  4732. </span>
  4733. )}
  4734. <span className="text-amber-700/80 dark:text-amber-300/70">
  4735. {t('printers.drying.timeRemaining', {
  4736. time: ams.dry_time >= 60
  4737. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  4738. : `${ams.dry_time}m`
  4739. })}
  4740. </span>
  4741. {/* A cycle on a screen-only model was started at the printer
  4742. and can only be stopped there (#2533). */}
  4743. {!status.drying_screen_only && (
  4744. <button
  4745. onClick={() => stopDryingMutation.mutate(ams.id)}
  4746. disabled={stopDryingMutation.isPending}
  4747. className="ml-auto text-amber-700 dark:text-amber-400 hover:text-amber-900 dark:hover:text-amber-300 transition-colors disabled:opacity-50"
  4748. title={t('printers.drying.stop')}
  4749. >
  4750. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  4751. </button>
  4752. )}
  4753. </div>
  4754. )}
  4755. {/* Slots grid: 4 columns - always render 4 slots */}
  4756. <div className="grid w-full gap-1" style={slotGridStyle(4)}>
  4757. {[0, 1, 2, 3].map((slotIdx) => {
  4758. // Find tray data for this slot (may be undefined if data incomplete)
  4759. // Use array index if available, as tray.id may not always be set
  4760. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  4761. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  4762. const isEmpty = !tray?.tray_type;
  4763. const emptyKind = getEmptySlotKind(tray);
  4764. // Check if this is the currently loaded tray
  4765. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  4766. const globalTrayId = ams.id * 4 + slotIdx;
  4767. const isActive = effectiveTrayNow === globalTrayId;
  4768. // Runout guidance (#2587): the slot the paused print now
  4769. // expects filament in, and the slot that ran out.
  4770. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  4771. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  4772. // Get cloud preset info if available
  4773. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  4774. // Get saved slot preset mapping (for user-configured slots)
  4775. const slotPreset = slotPresets?.[globalTrayId];
  4776. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  4777. const trayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx))?.toUpperCase();
  4778. const linkedSpool = trayTag ? linkedSpools?.[trayTag] : undefined;
  4779. const spoolmanFill = getSpoolmanFillLevel(linkedSpool);
  4780. // Slot-assigned-only spool fill (no tag link required)
  4781. const slotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  4782. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === slotIdx)
  4783. : undefined;
  4784. const slotSpoolForFill = slotAssignmentForFill
  4785. ? spoolmanSpools?.find(s => s.id === slotAssignmentForFill.spoolman_spool_id)
  4786. : undefined;
  4787. const slotSpoolFill = (slotSpoolForFill && (slotSpoolForFill.label_weight ?? 0) > 0)
  4788. ? Math.round(Math.max(0, (slotSpoolForFill.label_weight ?? 0) - slotSpoolForFill.weight_used) / (slotSpoolForFill.label_weight ?? 1) * 100)
  4789. : null;
  4790. const inventoryAssignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4791. const inventoryFill = (() => {
  4792. const sp = inventoryAssignment?.spool;
  4793. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  4794. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  4795. }
  4796. return null;
  4797. })();
  4798. // If inventory says 0% but AMS reports positive remain, prefer AMS
  4799. // (inventory weight_used may be stale or over-counted — #676)
  4800. const resolvedInventoryFill = (inventoryFill === 0 && hasFillLevel && tray.remain > 0)
  4801. ? null : inventoryFill;
  4802. const effectiveFill = spoolmanFill ?? slotSpoolFill ?? resolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  4803. const fillSource = (spoolmanFill !== null || slotSpoolFill !== null) ? 'spoolman' as const
  4804. : resolvedInventoryFill !== null ? 'inventory' as const
  4805. : hasFillLevel ? 'ams' as const
  4806. : undefined;
  4807. // Build filament data for hover card
  4808. const filamentData = tray?.tray_type ? {
  4809. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  4810. // Spoolman spool name wins over cloud lookup so a slot bound to
  4811. // a Spoolman spool shows that spool's preset name (e.g. "Devil
  4812. // Design PLA") instead of whatever the printer's filament_id
  4813. // resolves to in the cloud catalog (often "Generic PLA" for
  4814. // P-prefix local presets). Spoolman's filament.name is just the
  4815. // material+subtype ("PLA Basic"); prepend the spool's brand so
  4816. // the hover card shows "Devil Design PLA Basic" rather than the
  4817. // vendor-less form. Strip the "@<printer>..." suffix that
  4818. // BambuStudio appends to user-preset names.
  4819. 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,
  4820. colorName: getColorName(tray.tray_color || ''),
  4821. colorHex: tray.tray_color || null,
  4822. kFactor: formatKValue(tray.k),
  4823. fillLevel: effectiveFill,
  4824. trayUuid: tray.tray_uuid || null,
  4825. tagUid: tray.tag_uid || null,
  4826. fillSource,
  4827. } : null;
  4828. // Check if this specific slot is being refreshed
  4829. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  4830. refreshingSlot?.slotId === slotIdx;
  4831. // #1762 (comment 2): which print-slot is mapped to THIS AMS slot.
  4832. const activePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  4833. const activePrintSlotLabel = activePrintSlotIdx >= 0
  4834. ? `P${activePrintSlotIdx + 1}`
  4835. : null;
  4836. // Slot visual content (goes inside hover card)
  4837. const slotVisual = (
  4838. <div
  4839. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  4840. isExpectedSlot
  4841. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  4842. : isRanOutSlot
  4843. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  4844. : isActive
  4845. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  4846. : ''
  4847. }`}
  4848. >
  4849. {isExpectedSlot && (
  4850. <span
  4851. aria-label={t('printers.expectedSlot.ariaLabel', { n: slotIdx + 1 })}
  4852. title={t('printers.expectedSlot.title')}
  4853. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  4854. >
  4855. </span>
  4856. )}
  4857. {activePrintSlotLabel && (
  4858. <span
  4859. aria-label={t('printers.activeJobSlot.ariaLabel', { n: activePrintSlotIdx + 1 })}
  4860. title={t('printers.activeJobSlot.title', { n: activePrintSlotIdx + 1 })}
  4861. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  4862. >
  4863. {activePrintSlotLabel}
  4864. </span>
  4865. )}
  4866. {/* Filament color circle with 1-based slot number centered inside */}
  4867. <FilamentSlotCircle
  4868. trayColor={tray?.tray_color}
  4869. trayType={tray?.tray_type}
  4870. isEmpty={isEmpty}
  4871. emptyKind={emptyKind}
  4872. slotNumber={slotIdx + 1}
  4873. />
  4874. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  4875. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  4876. </div>
  4877. {/* Fill bar */}
  4878. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  4879. {effectiveFill !== null && effectiveFill >= 0 && !isEmpty && tray && (
  4880. <div
  4881. className="h-full rounded-full transition-all"
  4882. style={{
  4883. width: `${effectiveFill}%`,
  4884. backgroundColor: getFillBarColor(effectiveFill),
  4885. }}
  4886. />
  4887. )}
  4888. </div>
  4889. </div>
  4890. );
  4891. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  4892. return (
  4893. <div key={slotIdx} className="relative group w-full" style={filamentSlotStyle}>
  4894. {/* Loading overlay during RFID re-read */}
  4895. {isRefreshing && (
  4896. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  4897. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  4898. </div>
  4899. )}
  4900. {/* Hover card wraps only the visual content */}
  4901. {filamentData ? (
  4902. <FilamentHoverCard
  4903. data={filamentData}
  4904. actions={renderAmsSlotActions({
  4905. amsId: ams.id,
  4906. slotId: slotIdx,
  4907. loadTrayId: ams.id * 4 + slotIdx,
  4908. isRefreshing,
  4909. })}
  4910. spoolman={{
  4911. enabled: spoolmanEnabled,
  4912. // #1457: slot assignment is the user's most explicit action — it must
  4913. // outrank the tag-link, which can be stale when a non-RFID slot's
  4914. // fallback tag is still attached to a previous spool in Spoolman.
  4915. linkedSpoolId: slotAssignmentForFill?.spoolman_spool_id
  4916. ?? (trayTag ? linkedSpools?.[trayTag]?.id : undefined),
  4917. spoolmanUrl,
  4918. syncMode: spoolmanSyncMode,
  4919. // Suppress Link button when slot is already occupied by ANY assignment
  4920. // (Spoolman SlotAssignment OR local SpoolAssignment). Phase 9 only
  4921. // suppressed for Spoolman; the maintainer screenshot shows the badge
  4922. // still appearing on slots with a local Devil Design PLA assigned.
  4923. onLinkSpool: (spoolmanEnabled && !slotAssignmentForFill && !inventoryAssignment) ? () => {
  4924. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, slotIdx)).toUpperCase();
  4925. setLinkSpoolModal({
  4926. tagUid: filamentData.tagUid || linkTag,
  4927. trayUuid: filamentData.trayUuid || '',
  4928. printerId: printer.id,
  4929. amsId: ams.id,
  4930. trayId: slotIdx,
  4931. });
  4932. } : undefined,
  4933. onUnlinkSpool: linkedSpool?.id ? () => unlinkSpoolMutation.mutate(linkedSpool.id) : undefined,
  4934. }}
  4935. inventory={(() => {
  4936. if (spoolmanEnabled) {
  4937. if (spoolmanLoading) return undefined;
  4938. const slotAssignment = slotAssignmentForFill;
  4939. const spoolmanSpool = slotSpoolForFill;
  4940. return {
  4941. assignedSpool: spoolmanSpool ? {
  4942. id: spoolmanSpool.id,
  4943. material: spoolmanSpool.material,
  4944. brand: spoolmanSpool.brand ?? null,
  4945. color_name: spoolmanSpool.color_name ?? null,
  4946. remainingWeightGrams: spoolmanSpool.label_weight
  4947. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  4948. : undefined,
  4949. } : null,
  4950. onAssignSpool: () => setAssignSpoolModal({
  4951. printerId: printer.id,
  4952. amsId: ams.id,
  4953. trayId: slotIdx,
  4954. trayInfo: {
  4955. type: tray?.tray_type || filamentData.profile,
  4956. material: tray?.tray_type ?? undefined,
  4957. profile: filamentData.profile,
  4958. color: filamentData.colorHex || '',
  4959. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4960. },
  4961. }),
  4962. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  4963. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  4964. };
  4965. }
  4966. const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx);
  4967. return {
  4968. assignedSpool: assignment?.spool ? {
  4969. id: assignment.spool.id,
  4970. material: assignment.spool.material,
  4971. brand: assignment.spool.brand,
  4972. color_name: assignment.spool.color_name,
  4973. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  4974. } : null,
  4975. onAssignSpool: () => setAssignSpoolModal({
  4976. printerId: printer.id,
  4977. amsId: ams.id,
  4978. trayId: slotIdx,
  4979. trayInfo: {
  4980. type: tray?.tray_type || filamentData.profile,
  4981. material: tray?.tray_type ?? undefined,
  4982. profile: filamentData.profile,
  4983. color: filamentData.colorHex || '',
  4984. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  4985. },
  4986. }),
  4987. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, slotIdx) : undefined,
  4988. isAssigned: !!assignment || isBambuLabSpool(tray),
  4989. };
  4990. })()}
  4991. configureSlot={{
  4992. enabled: hasPermission('printers:control'),
  4993. onConfigure: () => setConfigureSlotModal({
  4994. amsId: ams.id,
  4995. trayId: slotIdx,
  4996. trayCount: ams.tray.length,
  4997. trayType: tray?.tray_type || undefined,
  4998. trayColor: tray?.tray_color || undefined,
  4999. traySubBrands: tray?.tray_sub_brands || undefined,
  5000. trayInfoIdx: tray?.tray_info_idx || undefined,
  5001. extruderId: mappedExtruderId,
  5002. caliIdx: tray?.cali_idx,
  5003. savedPresetId: slotPreset?.preset_id,
  5004. }),
  5005. }}
  5006. >
  5007. {slotVisual}
  5008. </FilamentHoverCard>
  5009. ) : (
  5010. <EmptySlotHoverCard
  5011. kind={emptyKind ?? undefined}
  5012. actions={renderAmsSlotActions({
  5013. amsId: ams.id,
  5014. slotId: slotIdx,
  5015. loadTrayId: ams.id * 4 + slotIdx,
  5016. isRefreshing,
  5017. })}
  5018. configureSlot={{
  5019. enabled: hasPermission('printers:control'),
  5020. onConfigure: () => setConfigureSlotModal({
  5021. amsId: ams.id,
  5022. trayId: slotIdx,
  5023. trayCount: ams.tray.length,
  5024. extruderId: mappedExtruderId,
  5025. }),
  5026. }}
  5027. onAssignSpool={() => setAssignSpoolModal({
  5028. printerId: printer.id,
  5029. amsId: ams.id,
  5030. trayId: slotIdx,
  5031. trayInfo: {
  5032. type: '',
  5033. material: undefined,
  5034. profile: '',
  5035. color: '',
  5036. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  5037. },
  5038. })}
  5039. >
  5040. {slotVisual}
  5041. </EmptySlotHoverCard>
  5042. )}
  5043. </div>
  5044. );
  5045. })}
  5046. </div>
  5047. </div>
  5048. );
  5049. })}
  5050. {/* HT AMS units */}
  5051. {htAms.map((ams) => {
  5052. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  5053. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  5054. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  5055. const isLeftNozzle = extruderId === 1;
  5056. const isRightNozzle = extruderId === 0;
  5057. const tray = ams.tray[0];
  5058. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  5059. const isEmpty = !tray?.tray_type;
  5060. const emptyKind = getEmptySlotKind(tray);
  5061. // Check if this is the currently loaded tray
  5062. const globalTrayId = getGlobalTrayId(ams.id, tray?.id ?? 0, false);
  5063. const isActive = effectiveTrayNow === globalTrayId;
  5064. // Runout guidance (#2587): expected / ran-out slot on this HT unit.
  5065. const isExpectedSlot = expectedTray !== null && expectedTray === globalTrayId;
  5066. const isRanOutSlot = previousTray !== null && previousTray === globalTrayId;
  5067. // Get cloud preset info if available
  5068. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  5069. // Get saved slot preset mapping (for user-configured slots)
  5070. const slotPreset = slotPresets?.[globalTrayId];
  5071. const htSlotId = tray?.id ?? 0;
  5072. // Fill level fallback chain: Spoolman → Inventory → AMS remain
  5073. const htTrayTag = (tray?.tray_uuid || tray?.tag_uid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId))?.toUpperCase();
  5074. const htLinkedSpool = htTrayTag ? linkedSpools?.[htTrayTag] : undefined;
  5075. const htSpoolmanFill = getSpoolmanFillLevel(htLinkedSpool);
  5076. const htInventoryAssignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5077. const htInventoryFill = (() => {
  5078. const sp = htInventoryAssignment?.spool;
  5079. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5080. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5081. }
  5082. return null;
  5083. })();
  5084. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5085. const htResolvedInventoryFill = (htInventoryFill === 0 && hasFillLevel && tray.remain > 0)
  5086. ? null : htInventoryFill;
  5087. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5088. const htSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5089. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === ams.id && a.tray_id === htSlotId)
  5090. : undefined;
  5091. const htSlotSpoolForFill = htSlotAssignmentForFill
  5092. ? spoolmanSpools?.find(s => s.id === htSlotAssignmentForFill.spoolman_spool_id)
  5093. : undefined;
  5094. const htSlotSpoolFill = (htSlotSpoolForFill && (htSlotSpoolForFill.label_weight ?? 0) > 0)
  5095. ? Math.round(Math.max(0, (htSlotSpoolForFill.label_weight ?? 0) - htSlotSpoolForFill.weight_used) / (htSlotSpoolForFill.label_weight ?? 1) * 100)
  5096. : null;
  5097. const htEffectiveFill = htSpoolmanFill ?? htSlotSpoolFill ?? htResolvedInventoryFill ?? (hasFillLevel ? tray.remain : null);
  5098. const htFillSource = (htSpoolmanFill !== null || htSlotSpoolFill !== null) ? 'spoolman' as const
  5099. : htResolvedInventoryFill !== null ? 'inventory' as const
  5100. : hasFillLevel ? 'ams' as const
  5101. : undefined;
  5102. // Build filament data for hover card
  5103. const filamentData = tray?.tray_type ? {
  5104. vendor: (isBambuLabSpool(tray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5105. 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,
  5106. colorName: getColorName(tray.tray_color || ''),
  5107. colorHex: tray.tray_color || null,
  5108. kFactor: formatKValue(tray.k),
  5109. fillLevel: htEffectiveFill,
  5110. trayUuid: tray.tray_uuid || null,
  5111. tagUid: tray.tag_uid || null,
  5112. fillSource: htFillSource,
  5113. } : null;
  5114. // Check if this specific slot is being refreshed
  5115. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  5116. refreshingSlot?.slotId === htSlotId;
  5117. // #1762 (comment 2): active print-slot index for this HT slot.
  5118. const htActivePrintSlotIdx = activeMapping.indexOf(globalTrayId);
  5119. const htActivePrintSlotLabel = htActivePrintSlotIdx >= 0
  5120. ? `P${htActivePrintSlotIdx + 1}`
  5121. : null;
  5122. // Slot visual content (goes inside hover card)
  5123. const slotVisual = (
  5124. <div
  5125. className={`relative w-full bg-bambu-dark-secondary rounded-lg p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${
  5126. isExpectedSlot
  5127. ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-bambu-dark animate-pulse'
  5128. : isRanOutSlot
  5129. ? 'ring-2 ring-red-500/60 ring-offset-1 ring-offset-bambu-dark'
  5130. : isActive
  5131. ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark'
  5132. : ''
  5133. }`}
  5134. >
  5135. {isExpectedSlot && (
  5136. <span
  5137. aria-label={t('printers.expectedSlot.ariaLabel', { n: 1 })}
  5138. title={t('printers.expectedSlot.title')}
  5139. className="absolute top-0.5 left-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-amber-400 rounded pointer-events-none leading-none"
  5140. >
  5141. </span>
  5142. )}
  5143. {htActivePrintSlotLabel && (
  5144. <span
  5145. aria-label={t('printers.activeJobSlot.ariaLabel', { n: htActivePrintSlotIdx + 1 })}
  5146. title={t('printers.activeJobSlot.title', { n: htActivePrintSlotIdx + 1 })}
  5147. className="absolute top-0.5 right-0.5 px-1 py-px text-[length:var(--pc-t8,8px)] font-bold text-bambu-dark bg-bambu-green rounded pointer-events-none leading-none"
  5148. >
  5149. {htActivePrintSlotLabel}
  5150. </span>
  5151. )}
  5152. {/* Filament color circle with 1-based slot number centered inside */}
  5153. <FilamentSlotCircle
  5154. trayColor={tray?.tray_color}
  5155. trayType={tray?.tray_type}
  5156. isEmpty={isEmpty}
  5157. emptyKind={emptyKind}
  5158. slotNumber={1}
  5159. />
  5160. <div className="text-[length:var(--pc-t9,9px)] text-white font-bold truncate">
  5161. {tray?.tray_type || t(emptyKind === 'reset' ? 'ams.slotUnconfigured' : 'ams.slotEmpty')}
  5162. </div>
  5163. {/* Fill bar */}
  5164. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5165. {htEffectiveFill !== null && htEffectiveFill >= 0 && !isEmpty && (
  5166. <div
  5167. className="h-full rounded-full transition-all"
  5168. style={{
  5169. width: `${htEffectiveFill}%`,
  5170. backgroundColor: getFillBarColor(htEffectiveFill),
  5171. }}
  5172. />
  5173. )}
  5174. </div>
  5175. </div>
  5176. );
  5177. // HT cards lay out slot + stats side-by-side in Row 2 (not stats-in-header
  5178. // like regular AMS), so they need more horizontal room than a 1-slot basis.
  5179. // Without this override, the L view squishes HT into a sliver next to the
  5180. // 4-slot AMS neighbors.
  5181. // 11rem holds one slot plus the temperature/humidity
  5182. // column beside it; both grow with the body scale.
  5183. const htCardWidth = scaledRem(11);
  5184. const htCardStyle: React.CSSProperties = {
  5185. flex: `1 1 ${htCardWidth}`,
  5186. minWidth: htCardWidth,
  5187. // An AMS-HT is never wider than a full AMS. Without a
  5188. // ceiling, a unit that wraps onto a line of its own is
  5189. // the only flex item there and grow stretches its single
  5190. // slot across the entire card, leaving the readings
  5191. // stranded at the far edge.
  5192. maxWidth: `calc(4 * ${slotMinWidth} + 3 * 0.25rem + 1rem)`,
  5193. };
  5194. return (
  5195. <div key={ams.id} style={htCardStyle} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5196. {/* Row 1: Label + Nozzle + Drying */}
  5197. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5198. {/* AMS name — hover to see serial, firmware, and edit friendly name */}
  5199. <div className="flex min-w-0 flex-1 items-center gap-1.5">
  5200. <AmsNameHoverCard
  5201. ams={ams}
  5202. printerId={printer.id}
  5203. label={getAmsLabel(ams.id, ams.tray.length)}
  5204. amsLabels={amsLabels}
  5205. canEdit={hasPermission('printers:update')}
  5206. onSaved={refetchAmsLabels}
  5207. >
  5208. <span className="block truncate text-[length:var(--pc-t10,10px)] text-white font-medium cursor-default select-none">
  5209. {amsLabels?.[ams.id] || getAmsLabel(ams.id, ams.tray.length)}
  5210. </span>
  5211. </AmsNameHoverCard>
  5212. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  5213. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  5214. )}
  5215. </div>
  5216. {/* Drying button for HT AMS */}
  5217. {(status.supports_drying || status.drying_screen_only) && (ams.module_type === 'n3f' || ams.module_type === 'n3s') && hasPermission('printers:control') && (
  5218. <div className="relative ml-auto">
  5219. <button
  5220. disabled={status.drying_screen_only}
  5221. onClick={(e) => {
  5222. if (ams.dry_time > 0) {
  5223. stopDryingMutation.mutate(ams.id);
  5224. } else if (dryingPopoverAmsId === ams.id) {
  5225. setDryingPopoverAmsId(null);
  5226. } else {
  5227. const firstTray = ams.tray.find(t => t.tray_type);
  5228. const filType = resolveDryingPresetKey(firstTray?.tray_type, dryingPresets);
  5229. // Only reachable if a custom preset set dropped PLA itself.
  5230. const preset = dryingPresets[filType] ?? DRYING_PRESETS['PLA'];
  5231. const moduleType = ams.module_type as 'n3f' | 'n3s';
  5232. setDryingFilament(filType);
  5233. setDryingTemp(preset[moduleType] || preset.n3f);
  5234. setDryingDuration(moduleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  5235. setDryingRotateTray(false);
  5236. setDryingPopoverModuleType(ams.module_type);
  5237. setDryingPopoverAmsId(ams.id);
  5238. const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
  5239. setDryingPopoverPos(computePopoverPosition({ triggerRect: rect, popoverWidth: DRYING_POPOVER_WIDTH, estimatedHeight: DRYING_POPOVER_ESTIMATED_HEIGHT, horizontalAlign: 'center' }));
  5240. }
  5241. }}
  5242. className={`flex items-center gap-0.5 px-1 py-0.5 rounded text-[length:var(--pc-t9,9px)] transition-colors ${
  5243. ams.dry_time > 0
  5244. ? 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400'
  5245. : status.drying_screen_only
  5246. ? 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  5247. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark/80'
  5248. }`}
  5249. title={status.drying_screen_only ? t('printers.drying.screenOnly') : ams.dry_time > 0 ? t('printers.drying.stop') : t('printers.drying.start')}
  5250. >
  5251. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5252. </button>
  5253. </div>
  5254. )}
  5255. </div>
  5256. {/* HT AMS drying status bar */}
  5257. {ams.dry_time > 0 && (
  5258. <div className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap rounded-lg bg-amber-50 dark:bg-amber-500/10 px-2 py-1 text-[length:var(--pc-t9,9px)]">
  5259. <Flame className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-amber-600 dark:text-amber-400 shrink-0" />
  5260. {ams.dry_filament && (
  5261. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5262. {ams.dry_target_temp != null
  5263. ? t('printers.drying.targetSummary', { filament: ams.dry_filament, temp: ams.dry_target_temp })
  5264. : ams.dry_filament}
  5265. </span>
  5266. )}
  5267. <span className="text-amber-700/80 dark:text-amber-300/70 text-[length:var(--pc-t8,8px)] truncate">
  5268. {ams.dry_time >= 60
  5269. ? `${Math.floor(ams.dry_time / 60)}h ${ams.dry_time % 60}m`
  5270. : `${ams.dry_time}m`}
  5271. </span>
  5272. {!status.drying_screen_only && (
  5273. <button
  5274. onClick={() => stopDryingMutation.mutate(ams.id)}
  5275. disabled={stopDryingMutation.isPending}
  5276. 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"
  5277. title={t('printers.drying.stop')}
  5278. >
  5279. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)]" />
  5280. </button>
  5281. )}
  5282. </div>
  5283. )}
  5284. {/* Row 2: Slot (left) + Stats (right stacked) */}
  5285. <div className="flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start">
  5286. {/* Slot wrapper with loading overlay */}
  5287. <div className="relative group flex-1" style={htSlotStyle}>
  5288. {/* Loading overlay during RFID re-read */}
  5289. {isHtRefreshing && (
  5290. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  5291. <RefreshCw className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-green animate-spin" />
  5292. </div>
  5293. )}
  5294. {/* Hover card wraps only the visual content */}
  5295. {filamentData ? (
  5296. <FilamentHoverCard
  5297. data={filamentData}
  5298. actions={renderAmsSlotActions({
  5299. amsId: ams.id,
  5300. slotId: htSlotId,
  5301. loadTrayId: ams.id * 4 + htSlotId,
  5302. isRefreshing: isHtRefreshing,
  5303. })}
  5304. spoolman={{
  5305. enabled: spoolmanEnabled,
  5306. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5307. linkedSpoolId: htSlotAssignmentForFill?.spoolman_spool_id
  5308. ?? (htTrayTag ? linkedSpools?.[htTrayTag]?.id : undefined),
  5309. spoolmanUrl,
  5310. syncMode: spoolmanSyncMode,
  5311. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5312. onLinkSpool: (spoolmanEnabled && !htSlotAssignmentForFill && !htInventoryAssignment) ? () => {
  5313. const linkTag = (filamentData.trayUuid || filamentData.tagUid || getFallbackSpoolTag(printer.serial_number, ams.id, htSlotId)).toUpperCase();
  5314. setLinkSpoolModal({
  5315. tagUid: filamentData.tagUid || linkTag,
  5316. trayUuid: filamentData.trayUuid || '',
  5317. printerId: printer.id,
  5318. amsId: ams.id,
  5319. trayId: htSlotId,
  5320. });
  5321. } : undefined,
  5322. onUnlinkSpool: htLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(htLinkedSpool.id) : undefined,
  5323. }}
  5324. inventory={(() => {
  5325. if (spoolmanEnabled) {
  5326. if (spoolmanLoading) return undefined;
  5327. const slotAssignment = htSlotAssignmentForFill;
  5328. const spoolmanSpool = htSlotSpoolForFill;
  5329. return {
  5330. assignedSpool: spoolmanSpool ? {
  5331. id: spoolmanSpool.id,
  5332. material: spoolmanSpool.material,
  5333. brand: spoolmanSpool.brand ?? null,
  5334. color_name: spoolmanSpool.color_name ?? null,
  5335. remainingWeightGrams: spoolmanSpool.label_weight
  5336. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5337. : undefined,
  5338. } : null,
  5339. onAssignSpool: () => setAssignSpoolModal({
  5340. printerId: printer.id,
  5341. amsId: ams.id,
  5342. trayId: htSlotId,
  5343. trayInfo: {
  5344. type: tray?.tray_type || filamentData.profile,
  5345. material: tray?.tray_type ?? undefined,
  5346. profile: filamentData.profile,
  5347. color: filamentData.colorHex || '',
  5348. location: getAmsLabel(ams.id, ams.tray.length),
  5349. },
  5350. }),
  5351. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(tray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5352. isAssigned: !!slotAssignment || isBambuLabSpool(tray),
  5353. };
  5354. }
  5355. const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId);
  5356. return {
  5357. assignedSpool: assignment?.spool ? {
  5358. id: assignment.spool.id,
  5359. material: assignment.spool.material,
  5360. brand: assignment.spool.brand,
  5361. color_name: assignment.spool.color_name,
  5362. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5363. } : null,
  5364. onAssignSpool: () => setAssignSpoolModal({
  5365. printerId: printer.id,
  5366. amsId: ams.id,
  5367. trayId: htSlotId,
  5368. trayInfo: {
  5369. type: tray?.tray_type || filamentData.profile,
  5370. material: tray?.tray_type ?? undefined,
  5371. profile: filamentData.profile,
  5372. color: filamentData.colorHex || '',
  5373. location: getAmsLabel(ams.id, ams.tray.length),
  5374. },
  5375. }),
  5376. onUnassignSpool: (assignment && !isBambuLabSpool(tray)) ? () => onUnassignSpool?.(printer.id, ams.id, htSlotId) : undefined,
  5377. isAssigned: !!assignment || isBambuLabSpool(tray),
  5378. };
  5379. })()}
  5380. configureSlot={{
  5381. enabled: hasPermission('printers:control'),
  5382. onConfigure: () => setConfigureSlotModal({
  5383. amsId: ams.id,
  5384. trayId: htSlotId,
  5385. trayCount: ams.tray.length,
  5386. trayType: tray?.tray_type || undefined,
  5387. trayColor: tray?.tray_color || undefined,
  5388. traySubBrands: tray?.tray_sub_brands || undefined,
  5389. trayInfoIdx: tray?.tray_info_idx || undefined,
  5390. extruderId: mappedExtruderId,
  5391. caliIdx: tray?.cali_idx,
  5392. savedPresetId: slotPreset?.preset_id,
  5393. }),
  5394. }}
  5395. >
  5396. {slotVisual}
  5397. </FilamentHoverCard>
  5398. ) : (
  5399. <EmptySlotHoverCard
  5400. kind={emptyKind ?? undefined}
  5401. actions={renderAmsSlotActions({
  5402. amsId: ams.id,
  5403. slotId: htSlotId,
  5404. loadTrayId: ams.id * 4 + htSlotId,
  5405. isRefreshing: isHtRefreshing,
  5406. })}
  5407. configureSlot={{
  5408. enabled: hasPermission('printers:control'),
  5409. onConfigure: () => setConfigureSlotModal({
  5410. amsId: ams.id,
  5411. trayId: htSlotId,
  5412. trayCount: ams.tray.length,
  5413. extruderId: mappedExtruderId,
  5414. }),
  5415. }}
  5416. onAssignSpool={() => setAssignSpoolModal({
  5417. printerId: printer.id,
  5418. amsId: ams.id,
  5419. trayId: htSlotId,
  5420. trayInfo: {
  5421. type: '',
  5422. material: undefined,
  5423. profile: '',
  5424. color: '',
  5425. location: getAmsLabel(ams.id, ams.tray.length),
  5426. },
  5427. })}
  5428. >
  5429. {slotVisual}
  5430. </EmptySlotHoverCard>
  5431. )}
  5432. </div>
  5433. {/* Stats stacked vertically: Temp on top, Humidity below */}
  5434. {(ams.humidity != null || ams.temp != null) && (
  5435. <div className="flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full">
  5436. {ams.temp != null && (
  5437. <TemperatureIndicator
  5438. temp={ams.temp}
  5439. goodThreshold={amsThresholds?.tempGood}
  5440. fairThreshold={amsThresholds?.tempFair}
  5441. onClick={() => setAmsHistoryModal({
  5442. amsId: ams.id,
  5443. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5444. mode: 'temperature',
  5445. })}
  5446. compact
  5447. />
  5448. )}
  5449. {ams.humidity != null && (
  5450. <HumidityIndicator
  5451. humidity={ams.humidity}
  5452. goodThreshold={amsThresholds?.humidityGood}
  5453. fairThreshold={amsThresholds?.humidityFair}
  5454. onClick={() => setAmsHistoryModal({
  5455. amsId: ams.id,
  5456. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  5457. mode: 'humidity',
  5458. })}
  5459. compact
  5460. />
  5461. )}
  5462. </div>
  5463. )}
  5464. </div>
  5465. </div>
  5466. );
  5467. })}
  5468. {/* External spool(s) - grouped in one card like regular AMS */}
  5469. {status.vt_tray.length > 0 && showExternalSpool && (
  5470. <div style={getAmsCardStyle(status.vt_tray.length)} className="min-w-0 p-2 bg-bambu-dark rounded-[10px] space-y-1">
  5471. <div className="flex w-full min-h-7 items-center gap-1.5 rounded-lg bg-bambu-dark-secondary px-2 py-1">
  5472. <span className="block min-w-0 flex-1 truncate text-[length:var(--pc-t10,10px)] text-white font-medium">{t('printers.external')}</span>
  5473. </div>
  5474. <div className="grid w-full gap-1" style={slotGridStyle(status.vt_tray.length > 1 ? 2 : 1)}>
  5475. {[...status.vt_tray].sort((a, b) => (a.id ?? 254) - (b.id ?? 254)).map((extTray) => {
  5476. const extTrayId = extTray.id ?? 254;
  5477. // On dual-nozzle (H2C/H2D), tray_now=254 means "external spool"
  5478. // generically — use active_extruder to determine L vs R:
  5479. // extruder 1=left → Ext-L (id=254), extruder 0=right → Ext-R (id=255)
  5480. const isExtActive = isDualNozzle && effectiveTrayNow === 254
  5481. ? (extTrayId === 254 && status.active_extruder === 1) ||
  5482. (extTrayId === 255 && status.active_extruder === 0)
  5483. : effectiveTrayNow === extTrayId;
  5484. const slotTrayId = extTrayId - 254; // 0 or 1
  5485. const extLabel = isDualNozzle
  5486. ? (extTrayId === 254 ? t('printers.extL') : t('printers.extR'))
  5487. : '';
  5488. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  5489. const extSlotPreset = slotPresets?.[255 * 4 + slotTrayId];
  5490. const extTrayTag = (extTray.tray_uuid || extTray.tag_uid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId))?.toUpperCase();
  5491. const extLinkedSpool = extTrayTag ? linkedSpools?.[extTrayTag] : undefined;
  5492. const extSpoolmanFill = getSpoolmanFillLevel(extLinkedSpool);
  5493. const extInventoryAssignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5494. const extInventoryFill = (() => {
  5495. const sp = extInventoryAssignment?.spool;
  5496. if (sp && sp.label_weight > 0 && sp.weight_used != null) {
  5497. return Math.round(Math.max(0, sp.label_weight - sp.weight_used) / sp.label_weight * 100);
  5498. }
  5499. return null;
  5500. })();
  5501. const extHasFillLevel = extTray.tray_type && extTray.remain >= 0;
  5502. // If inventory says 0% but AMS reports positive remain, prefer AMS (#676)
  5503. const extResolvedInventoryFill = (extInventoryFill === 0 && extHasFillLevel && extTray.remain > 0)
  5504. ? null : extInventoryFill;
  5505. // Slot-assigned-only fill (when spool has no NFC tag but is slot-assigned)
  5506. const extSlotAssignmentForFill = spoolmanEnabled && !spoolmanLoading
  5507. ? spoolmanSlotAssignments?.find(a => a.printer_id === printer.id && a.ams_id === 255 && a.tray_id === slotTrayId)
  5508. : undefined;
  5509. const extSlotSpoolForFill = extSlotAssignmentForFill
  5510. ? spoolmanSpools?.find(s => s.id === extSlotAssignmentForFill.spoolman_spool_id)
  5511. : undefined;
  5512. const extSlotSpoolFill = (extSlotSpoolForFill && (extSlotSpoolForFill.label_weight ?? 0) > 0)
  5513. ? Math.round(Math.max(0, (extSlotSpoolForFill.label_weight ?? 0) - extSlotSpoolForFill.weight_used) / (extSlotSpoolForFill.label_weight ?? 1) * 100)
  5514. : null;
  5515. const extEffectiveFill = extSpoolmanFill ?? extSlotSpoolFill ?? extResolvedInventoryFill ?? (extHasFillLevel ? extTray.remain : null);
  5516. const extFillSource = (extSpoolmanFill !== null || extSlotSpoolFill !== null) ? 'spoolman' as const
  5517. : extResolvedInventoryFill !== null ? 'inventory' as const
  5518. : extHasFillLevel ? 'ams' as const
  5519. : undefined;
  5520. const extFilamentData = {
  5521. vendor: (isBambuLabSpool(extTray) ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  5522. 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',
  5523. colorName: getColorName(extTray.tray_color || ''),
  5524. colorHex: extTray.tray_color || null,
  5525. kFactor: formatKValue(extTray.k),
  5526. fillLevel: extEffectiveFill,
  5527. trayUuid: extTray.tray_uuid || null,
  5528. tagUid: extTray.tag_uid || null,
  5529. fillSource: extFillSource,
  5530. };
  5531. const isEmpty = !extTray.tray_type;
  5532. const emptyKind = getEmptySlotKind(extTray);
  5533. const extSlotContent = (
  5534. <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' : ''}`}>
  5535. {/* Color circle: L/R inside on dual-nozzle external (replaces
  5536. the separate Ext-L/Ext-R caption that made the row taller than
  5537. regular AMS slots), 1-based slot number on single-nozzle. */}
  5538. <FilamentSlotCircle
  5539. trayColor={extTray.tray_color}
  5540. trayType={extTray.tray_type}
  5541. isEmpty={isEmpty}
  5542. emptyKind={emptyKind}
  5543. slotNumber={isDualNozzle ? (extTrayId === 254 ? 'L' : 'R') : slotTrayId + 1}
  5544. />
  5545. <div className={`text-[length:var(--pc-t9,9px)] font-bold truncate ${isEmpty ? 'text-white/40' : 'text-white'}`}>
  5546. {extTray.tray_type || t('ams.slotEmpty')}
  5547. </div>
  5548. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  5549. {extEffectiveFill !== null && extEffectiveFill >= 0 && !isEmpty && (
  5550. <div
  5551. className="h-full rounded-full transition-all"
  5552. style={{
  5553. width: `${extEffectiveFill}%`,
  5554. backgroundColor: getFillBarColor(extEffectiveFill),
  5555. }}
  5556. />
  5557. )}
  5558. </div>
  5559. </div>
  5560. );
  5561. return (
  5562. <div key={extTrayId} className="relative group w-full" style={filamentSlotStyle}>
  5563. {!isEmpty ? (
  5564. <FilamentHoverCard
  5565. data={extFilamentData}
  5566. actions={renderAmsSlotActions({
  5567. amsId: 255,
  5568. slotId: slotTrayId,
  5569. loadTrayId: extTrayId,
  5570. includeRfid: false,
  5571. })}
  5572. spoolman={{
  5573. enabled: spoolmanEnabled,
  5574. // #1457: slot assignment outranks tag-link (see top-level slot block).
  5575. linkedSpoolId: extSlotAssignmentForFill?.spoolman_spool_id
  5576. ?? (extTrayTag ? linkedSpools?.[extTrayTag]?.id : undefined),
  5577. spoolmanUrl,
  5578. syncMode: spoolmanSyncMode,
  5579. // Suppress Link button when slot is occupied by ANY assignment (Phase 13 P13-6d)
  5580. onLinkSpool: (spoolmanEnabled && !extSlotAssignmentForFill && !extInventoryAssignment) ? () => {
  5581. const linkTag = (extFilamentData.trayUuid || extFilamentData.tagUid || getFallbackSpoolTag(printer.serial_number, 255, slotTrayId)).toUpperCase();
  5582. setLinkSpoolModal({
  5583. tagUid: extFilamentData.tagUid || linkTag,
  5584. trayUuid: extFilamentData.trayUuid || '',
  5585. printerId: printer.id,
  5586. amsId: 255,
  5587. trayId: slotTrayId,
  5588. });
  5589. } : undefined,
  5590. onUnlinkSpool: extLinkedSpool?.id ? () => unlinkSpoolMutation.mutate(extLinkedSpool.id) : undefined,
  5591. }}
  5592. inventory={(() => {
  5593. if (spoolmanEnabled) {
  5594. if (spoolmanLoading) return undefined;
  5595. const slotAssignment = extSlotAssignmentForFill;
  5596. const spoolmanSpool = extSlotSpoolForFill;
  5597. return {
  5598. assignedSpool: spoolmanSpool ? {
  5599. id: spoolmanSpool.id,
  5600. material: spoolmanSpool.material,
  5601. brand: spoolmanSpool.brand ?? null,
  5602. color_name: spoolmanSpool.color_name ?? null,
  5603. remainingWeightGrams: spoolmanSpool.label_weight
  5604. ? Math.max(0, Math.round(spoolmanSpool.label_weight - spoolmanSpool.weight_used))
  5605. : undefined,
  5606. } : null,
  5607. onAssignSpool: () => setAssignSpoolModal({
  5608. printerId: printer.id,
  5609. amsId: 255,
  5610. trayId: slotTrayId,
  5611. trayInfo: {
  5612. type: extTray.tray_type || extFilamentData.profile,
  5613. material: extTray.tray_type ?? undefined,
  5614. profile: extFilamentData.profile,
  5615. color: extFilamentData.colorHex || '',
  5616. location: extLabel || t('printers.external'),
  5617. },
  5618. }),
  5619. onUnassignSpool: (spoolmanSpool && !isBambuLabSpool(extTray)) ? () => onUnassignSpoolmanSpool?.(spoolmanSpool.id) : undefined,
  5620. isAssigned: !!slotAssignment || isBambuLabSpool(extTray),
  5621. };
  5622. }
  5623. const assignment = onGetAssignment?.(printer.id, 255, slotTrayId);
  5624. return {
  5625. assignedSpool: assignment?.spool ? {
  5626. id: assignment.spool.id,
  5627. material: assignment.spool.material,
  5628. brand: assignment.spool.brand,
  5629. color_name: assignment.spool.color_name,
  5630. remainingWeightGrams: Math.max(0, Math.round(assignment.spool.label_weight - assignment.spool.weight_used)),
  5631. } : null,
  5632. onAssignSpool: () => setAssignSpoolModal({
  5633. printerId: printer.id,
  5634. amsId: 255,
  5635. trayId: slotTrayId,
  5636. trayInfo: {
  5637. type: extTray.tray_type || extFilamentData.profile,
  5638. material: extTray.tray_type ?? undefined,
  5639. profile: extFilamentData.profile,
  5640. color: extFilamentData.colorHex || '',
  5641. location: extLabel || t('printers.external'),
  5642. },
  5643. }),
  5644. onUnassignSpool: (assignment && !isBambuLabSpool(extTray)) ? () => onUnassignSpool?.(printer.id, 255, slotTrayId) : undefined,
  5645. isAssigned: !!assignment || isBambuLabSpool(extTray),
  5646. };
  5647. })()}
  5648. configureSlot={{
  5649. enabled: hasPermission('printers:control'),
  5650. onConfigure: () => setConfigureSlotModal({
  5651. amsId: 255,
  5652. trayId: slotTrayId,
  5653. trayCount: 1,
  5654. trayType: extTray.tray_type || undefined,
  5655. trayColor: extTray.tray_color || undefined,
  5656. traySubBrands: extTray.tray_sub_brands || undefined,
  5657. trayInfoIdx: extTray.tray_info_idx || undefined,
  5658. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5659. caliIdx: extTray.cali_idx,
  5660. savedPresetId: extSlotPreset?.preset_id,
  5661. }),
  5662. }}
  5663. >
  5664. {extSlotContent}
  5665. </FilamentHoverCard>
  5666. ) : (
  5667. <EmptySlotHoverCard
  5668. kind={emptyKind ?? undefined}
  5669. actions={renderAmsSlotActions({
  5670. amsId: 255,
  5671. slotId: slotTrayId,
  5672. loadTrayId: extTrayId,
  5673. includeRfid: false,
  5674. })}
  5675. configureSlot={{
  5676. enabled: hasPermission('printers:control'),
  5677. onConfigure: () => setConfigureSlotModal({
  5678. amsId: 255,
  5679. trayId: slotTrayId,
  5680. trayCount: 1,
  5681. extruderId: isDualNozzle ? (extTrayId === 254 ? 1 : 0) : undefined,
  5682. }),
  5683. }}
  5684. onAssignSpool={() => setAssignSpoolModal({
  5685. printerId: printer.id,
  5686. amsId: 255,
  5687. trayId: slotTrayId,
  5688. trayInfo: {
  5689. type: '',
  5690. material: undefined,
  5691. profile: '',
  5692. color: '',
  5693. location: `External Slot ${slotTrayId + 1}`,
  5694. },
  5695. })}
  5696. >
  5697. {extSlotContent}
  5698. </EmptySlotHoverCard>
  5699. )}
  5700. </div>
  5701. );
  5702. })}
  5703. </div>
  5704. </div>
  5705. )}
  5706. </div>
  5707. </div>
  5708. );
  5709. })()}
  5710. </>
  5711. )}
  5712. {/* Bottom block (power row + action bar). Wrapped together so the
  5713. power row hugs the action bar at the card bottom instead of
  5714. floating up when there's less filament content above. */}
  5715. {viewMode === 'expanded' && (
  5716. <div className="mt-auto">
  5717. {smartPlug && (
  5718. <div className="pt-3">
  5719. <div className="flex items-center gap-2 mb-2">
  5720. <span className="text-[length:var(--pc-t10,10px)] uppercase tracking-wider text-bambu-gray font-medium">
  5721. {t('printers.power', 'Power')}
  5722. </span>
  5723. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  5724. </div>
  5725. <div className="flex items-center gap-2 rounded-[10px] bg-bambu-dark p-2">
  5726. {/* Plug name + current power */}
  5727. <div className="flex items-center gap-2 min-w-0 pl-1">
  5728. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] text-bambu-gray flex-shrink-0" />
  5729. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  5730. <span
  5731. className="px-1.5 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray text-[length:var(--pc-t10,10px)] font-medium flex-shrink-0"
  5732. title={t('smartPlugs.power')}
  5733. >
  5734. {plugStatus?.energy?.power !== null && plugStatus?.energy?.power !== undefined ? `${Math.round(plugStatus.energy.power)}W` : '--'}
  5735. </span>
  5736. </div>
  5737. {/* Spacer */}
  5738. <div className="flex-1" />
  5739. <div className="flex items-center gap-2">
  5740. {/* Auto-off */}
  5741. <button
  5742. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  5743. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed || !hasPermission('smart_plugs:control')}
  5744. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (smartPlug.auto_off_executed ? t('printers.autoOffExecuted') : t('printers.autoOffAfterPrint'))}
  5745. 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 ${
  5746. !hasPermission('smart_plugs:control')
  5747. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5748. : smartPlug.auto_off || smartPlug.auto_off_executed
  5749. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5750. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5751. }`}
  5752. >
  5753. <Clock className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  5754. </button>
  5755. <button
  5756. onClick={() => {
  5757. if (plugStatus?.state === 'ON') {
  5758. setShowPowerOffConfirm(true);
  5759. } else {
  5760. setShowPowerOnConfirm(true);
  5761. }
  5762. }}
  5763. disabled={powerControlMutation.isPending || !hasPermission('smart_plugs:control')}
  5764. 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 ${
  5765. !hasPermission('smart_plugs:control')
  5766. ? 'bg-bambu-dark-tertiary/50 text-bambu-gray/50'
  5767. : plugStatus?.state === 'ON'
  5768. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  5769. : 'bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary/80'
  5770. }`}
  5771. title={!hasPermission('smart_plugs:control') ? t('printers.permission.noSmartPlugControl') : (plugStatus?.state === 'ON' ? 'Turn off' : 'Turn on')}
  5772. >
  5773. <Zap className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  5774. </button>
  5775. </div>
  5776. </div>
  5777. {/* HA entity buttons row */}
  5778. {scriptPlugs && scriptPlugs.length > 0 && (
  5779. <div className="flex items-center gap-2 mt-2">
  5780. <Home className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-blue-600 dark:text-blue-400 flex-shrink-0" />
  5781. <span className="text-xs text-bambu-gray">HA:</span>
  5782. <div className="h-[2px] w-5 bg-bambu-dark-tertiary/50" />
  5783. <div className="flex flex-wrap gap-1">
  5784. {scriptPlugs.map(script => {
  5785. const isScript = script.ha_entity_id?.startsWith('script.');
  5786. return (
  5787. <button
  5788. key={script.id}
  5789. onClick={() => {
  5790. if (isScript) {
  5791. runScriptMutation.mutate({ id: script.id, action: 'on' });
  5792. } else {
  5793. setHaToggleConfirm(script);
  5794. }
  5795. }}
  5796. disabled={runScriptMutation.isPending}
  5797. title={`${isScript ? 'Run' : 'Toggle'} ${script.ha_entity_id}`}
  5798. 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"
  5799. >
  5800. <Play className="w-[var(--pc-i25,0.625rem)] h-[var(--pc-i25,0.625rem)]" />
  5801. {script.name}
  5802. </button>
  5803. );
  5804. })}
  5805. </div>
  5806. </div>
  5807. )}
  5808. </div>
  5809. )}
  5810. {/* Home Assistant sensors (#1148). Outside the smartPlug block above:
  5811. a printer can have an enclosure door contact without having a plug,
  5812. and nesting it there would hide the row on exactly those setups. */}
  5813. <PrinterHASensorRow printerId={printer.id} />
  5814. {/* Connection Info & Actions */}
  5815. <div className="pt-4">
  5816. <div className="mb-3 h-[2px] bg-bambu-dark-tertiary" />
  5817. <div className="flex items-center justify-between gap-2">
  5818. {printerActionsMenu}
  5819. <div className="flex items-center justify-end gap-2 flex-wrap">
  5820. {/* Camera Button */}
  5821. <Button
  5822. variant="secondary"
  5823. size="sm"
  5824. onClick={() => {
  5825. if (cameraViewMode === 'embedded' && onOpenEmbeddedCamera) {
  5826. onOpenEmbeddedCamera(printer.id, printer.name);
  5827. } else {
  5828. // Use saved window state or defaults
  5829. const saved = localStorage.getItem('cameraWindowState');
  5830. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  5831. const features = [
  5832. `width=${state.width}`,
  5833. `height=${state.height}`,
  5834. state.left !== undefined ? `left=${state.left}` : '',
  5835. state.top !== undefined ? `top=${state.top}` : '',
  5836. // No `noopener`: same-origin popup needs opener so the browser
  5837. // copies sessionStorage (auth token) into the new window.
  5838. 'menubar=no,toolbar=no,location=no,status=no',
  5839. ].filter(Boolean).join(',');
  5840. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  5841. }
  5842. }}
  5843. disabled={!status?.connected || !hasPermission('camera:view')}
  5844. title={!hasPermission('camera:view') ? t('printers.permission.noCamera') : (cameraViewMode === 'embedded' ? t('printers.openCameraOverlay') : t('printers.openCameraWindow'))}
  5845. className={footerIconButtonClass}
  5846. >
  5847. <Video className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  5848. </Button>
  5849. <Button
  5850. variant="secondary"
  5851. size="sm"
  5852. onClick={() => setShowFileManager(true)}
  5853. disabled={!isConnected || !hasPermission('printers:files')}
  5854. title={!hasPermission('printers:files') ? t('printers.permission.noFiles') : t('printers.browseFiles')}
  5855. className={footerIconButtonClass}
  5856. >
  5857. <HardDrive className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  5858. </Button>
  5859. {isConnected && status?.state !== 'RUNNING' && status?.state !== 'PAUSE' && (
  5860. <Button
  5861. size="sm"
  5862. onClick={() => setShowUploadForPrint(true)}
  5863. disabled={!hasPermission('library:upload') || !hasPermission('queue:create')}
  5864. title={
  5865. !hasPermission('library:upload')
  5866. ? t('fileManager.noPermissionUpload')
  5867. : !hasPermission('queue:create')
  5868. ? t('fileManager.noPermissionAddToQueue')
  5869. : t('common.print')
  5870. }
  5871. className={`${footerActionButtonClass} !bg-bambu-green hover:!bg-bambu-green/80 !text-white`}
  5872. >
  5873. <PrinterIcon className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)]" />
  5874. {t('common.print')}
  5875. </Button>
  5876. )}
  5877. </div>
  5878. </div>
  5879. </div>
  5880. </div>
  5881. )}
  5882. </CardContent>
  5883. {/* File Manager Modal */}
  5884. {showFileManager && (
  5885. <FileManagerModal
  5886. printerId={printer.id}
  5887. printerName={printer.name}
  5888. onClose={() => setShowFileManager(false)}
  5889. />
  5890. )}
  5891. {/* Upload for Print Modal */}
  5892. {showUploadForPrint && (
  5893. <FileUploadModal
  5894. folderId={null}
  5895. onClose={() => setShowUploadForPrint(false)}
  5896. onUploadComplete={() => {}}
  5897. autoUpload
  5898. accept=".gcode,.3mf"
  5899. validateFile={(file) => {
  5900. const lower = file.name.toLowerCase();
  5901. if (!lower.endsWith('.gcode') && !lower.includes('.gcode.')) {
  5902. return t('printers.dropNotPrintable', 'Only .gcode and .gcode.3mf files can be printed');
  5903. }
  5904. }}
  5905. onFileUploaded={(uploadedFile) => {
  5906. // Check printer compatibility if sliced_for_model is available in metadata
  5907. const slicedFor = (uploadedFile.metadata as Record<string, unknown>)?.sliced_for_model as string | undefined;
  5908. const printerModel = mapModelCode(printer.model);
  5909. if (slicedFor && printerModel && slicedFor.toLowerCase() !== printerModel.toLowerCase()) {
  5910. api.deleteLibraryFile(uploadedFile.id).catch(() => {});
  5911. return t('printers.incompatibleFile', 'This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}', { slicedFor, printerModel });
  5912. }
  5913. setPrintAfterUpload({ id: uploadedFile.id, filename: uploadedFile.filename });
  5914. }}
  5915. />
  5916. )}
  5917. {/* Print Modal (after upload) */}
  5918. {printAfterUpload && (
  5919. <PrintModal
  5920. mode="create"
  5921. libraryFileId={printAfterUpload.id}
  5922. archiveName={printAfterUpload.filename}
  5923. initialSelectedPrinterIds={[printer.id]}
  5924. onClose={() => setPrintAfterUpload(null)}
  5925. onSuccess={() => setPrintAfterUpload(null)}
  5926. cleanupLibraryAfterDispatch
  5927. />
  5928. )}
  5929. {/* MQTT Debug Modal */}
  5930. {showMQTTDebug && (
  5931. <MQTTDebugModal
  5932. printerId={printer.id}
  5933. printerName={printer.name}
  5934. onClose={() => setShowMQTTDebug(false)}
  5935. />
  5936. )}
  5937. {showDiagnostic && (
  5938. <ConnectionDiagnosticModal
  5939. printerId={printer.id}
  5940. printerName={printer.name}
  5941. onClose={() => setShowDiagnostic(false)}
  5942. />
  5943. )}
  5944. {showPrinterInfo && (
  5945. <PrinterInfoModal
  5946. printer={printer}
  5947. status={status}
  5948. totalPrintHours={maintenanceInfo?.total_print_hours}
  5949. onClose={closePrinterInfo}
  5950. />
  5951. )}
  5952. {/* Plate Check Result Modal */}
  5953. {plateCheckResult && (
  5954. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4" onClick={() => closePlateCheckModal()}>
  5955. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full" onClick={e => e.stopPropagation()}>
  5956. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  5957. <div className="flex items-center gap-2">
  5958. {plateCheckResult.needs_calibration ? (
  5959. <ScanSearch className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-blue-500" />
  5960. ) : plateCheckResult.is_empty ? (
  5961. <CheckCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-green-500" />
  5962. ) : (
  5963. <XCircle className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)] text-yellow-500" />
  5964. )}
  5965. <h2 className="text-lg font-semibold text-white">
  5966. Build Plate Check
  5967. </h2>
  5968. {plateCheckResult.reference_count !== undefined && plateCheckResult.max_references && (
  5969. <span className="text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded">
  5970. {plateCheckResult.reference_count}/{plateCheckResult.max_references} refs
  5971. </span>
  5972. )}
  5973. </div>
  5974. <button
  5975. onClick={() => closePlateCheckModal()}
  5976. className="p-1 text-bambu-gray hover:text-white rounded transition-colors"
  5977. >
  5978. <X className="w-[var(--pc-i5,1.25rem)] h-[var(--pc-i5,1.25rem)]" />
  5979. </button>
  5980. </div>
  5981. <div className="p-4 space-y-4">
  5982. {plateCheckResult.needs_calibration ? (
  5983. <>
  5984. <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-500/20 border border-blue-300 dark:border-blue-500/50">
  5985. <p className="font-medium text-blue-700 dark:text-blue-400">
  5986. {t('printers.plateDetection.calibrationRequired')}
  5987. </p>
  5988. <p className="text-sm text-bambu-gray mt-1" dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationInstructions') }} />
  5989. </div>
  5990. <div className="text-sm text-bambu-gray space-y-2">
  5991. <p>{t('printers.plateDetection.calibrationDescription')}</p>
  5992. <p dangerouslySetInnerHTML={{ __html: t('printers.plateDetection.calibrationTip') }} />
  5993. </div>
  5994. </>
  5995. ) : (
  5996. <>
  5997. <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'}`}>
  5998. <p className={`font-medium ${plateCheckResult.is_empty ? 'text-green-700 dark:text-green-400' : 'text-yellow-700 dark:text-yellow-400'}`}>
  5999. {plateCheckResult.is_empty ? t('printers.plateDetection.plateEmpty') : t('printers.plateDetection.objectsDetected')}
  6000. </p>
  6001. <p className="text-sm text-bambu-gray mt-1">
  6002. {t('printers.plateDetection.confidence')}: {Math.round(plateCheckResult.confidence * 100)}% | {t('printers.plateDetection.difference')}: {plateCheckResult.difference_percent.toFixed(1)}%
  6003. </p>
  6004. </div>
  6005. {plateCheckResult.debug_image_url && (
  6006. <div>
  6007. <p className="text-sm text-bambu-gray mb-2">{t('printers.plateDetection.analysisPreview')}</p>
  6008. <img
  6009. src={plateCheckResult.debug_image_url}
  6010. alt={t('printers.plateDetection.analysisPreview')}
  6011. className="w-full rounded-lg border border-bambu-dark-tertiary"
  6012. />
  6013. <p className="text-xs text-bambu-gray mt-2">
  6014. {t('printers.plateDetection.analysisLegend')}
  6015. </p>
  6016. </div>
  6017. )}
  6018. <p className="text-xs text-bambu-gray">
  6019. {plateCheckResult.message}
  6020. </p>
  6021. </>
  6022. )}
  6023. {/* Saved References Grid */}
  6024. {plateReferences && plateReferences.references.length > 0 && (
  6025. <div className="mt-4">
  6026. <div className="flex items-center gap-2 mb-2">
  6027. <p className="text-sm font-medium text-white shrink-0">
  6028. {t('printers.plateDetection.savedReferences', { count: plateReferences.references.length, max: plateReferences.max_references })}
  6029. </p>
  6030. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6031. </div>
  6032. <div className="grid grid-cols-5 gap-2">
  6033. {plateReferences.references.map((ref) => (
  6034. <div key={ref.index} className="relative group">
  6035. <img
  6036. src={api.getPlateReferenceThumbnailUrl(printer.id, ref.index)}
  6037. alt={ref.label || `Reference ${ref.index + 1}`}
  6038. className="w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"
  6039. />
  6040. {/* Delete button */}
  6041. <button
  6042. onClick={() => handleDeleteRef(ref.index)}
  6043. className="absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity"
  6044. title={t('printers.plateDetection.deleteReference')}
  6045. >
  6046. <X className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] text-white" />
  6047. </button>
  6048. {/* Label */}
  6049. {editingRefLabel?.index === ref.index ? (
  6050. <input
  6051. type="text"
  6052. value={editingRefLabel.label}
  6053. onChange={(e) => setEditingRefLabel({ ...editingRefLabel, label: e.target.value })}
  6054. onBlur={() => handleUpdateRefLabel(ref.index, editingRefLabel.label)}
  6055. onKeyDown={(e) => {
  6056. if (e.key === 'Enter') handleUpdateRefLabel(ref.index, editingRefLabel.label);
  6057. if (e.key === 'Escape') setEditingRefLabel(null);
  6058. }}
  6059. className="w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white"
  6060. autoFocus
  6061. placeholder={t('printers.plateDetection.labelPlaceholder')}
  6062. />
  6063. ) : (
  6064. <p
  6065. className="text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white"
  6066. onClick={() => setEditingRefLabel({ index: ref.index, label: ref.label })}
  6067. title={ref.label ? t('printers.plateDetection.clickToEdit', { label: ref.label }) : t('printers.plateDetection.clickToAddLabel')}
  6068. >
  6069. {ref.label || <span className="italic opacity-50">{t('printers.noLabel')}</span>}
  6070. </p>
  6071. )}
  6072. {/* Timestamp */}
  6073. <p className="text-[length:var(--pc-t10,10px)] text-bambu-gray/60">
  6074. {ref.timestamp ? parseUTCDate(ref.timestamp)?.toLocaleDateString() ?? '' : ''}
  6075. </p>
  6076. </div>
  6077. ))}
  6078. </div>
  6079. </div>
  6080. )}
  6081. {/* ROI Editor */}
  6082. {!plateCheckResult.needs_calibration && (
  6083. <div className="mt-4">
  6084. <div className="flex items-center justify-between mb-2">
  6085. <div className="flex min-w-0 flex-1 items-center gap-2">
  6086. <p className="text-sm font-medium text-white shrink-0">{t('printers.roi.title')}</p>
  6087. <div className="flex-1 h-[2px] bg-bambu-dark-tertiary" />
  6088. </div>
  6089. {!editingRoi ? (
  6090. <Button
  6091. variant="ghost"
  6092. size="sm"
  6093. onClick={() => setEditingRoi(plateCheckResult.roi || { x: 0.15, y: 0.35, w: 0.70, h: 0.55 })}
  6094. >
  6095. <Pencil className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] mr-1" />
  6096. {t('common.edit')}
  6097. </Button>
  6098. ) : (
  6099. <div className="flex gap-1">
  6100. <Button
  6101. variant="ghost"
  6102. size="sm"
  6103. onClick={() => setEditingRoi(null)}
  6104. disabled={isSavingRoi}
  6105. >
  6106. {t('common.cancel')}
  6107. </Button>
  6108. <Button
  6109. size="sm"
  6110. onClick={handleSaveRoi}
  6111. disabled={isSavingRoi}
  6112. >
  6113. {isSavingRoi ? <Loader2 className="w-[var(--pc-i3,0.75rem)] h-[var(--pc-i3,0.75rem)] animate-spin" /> : t('common.save')}
  6114. </Button>
  6115. </div>
  6116. )}
  6117. </div>
  6118. {editingRoi ? (
  6119. <div className="space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg">
  6120. <div className="grid grid-cols-2 gap-3">
  6121. <div>
  6122. <label className="text-xs text-bambu-gray">{t('printers.roi.xStart')}</label>
  6123. <input
  6124. type="range"
  6125. min="0"
  6126. max="0.9"
  6127. step="0.01"
  6128. value={editingRoi.x}
  6129. onChange={(e) => setEditingRoi({ ...editingRoi, x: parseFloat(e.target.value) })}
  6130. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6131. />
  6132. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.x * 100)}%</span>
  6133. </div>
  6134. <div>
  6135. <label className="text-xs text-bambu-gray">{t('printers.roi.yStart')}</label>
  6136. <input
  6137. type="range"
  6138. min="0"
  6139. max="0.9"
  6140. step="0.01"
  6141. value={editingRoi.y}
  6142. onChange={(e) => setEditingRoi({ ...editingRoi, y: parseFloat(e.target.value) })}
  6143. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6144. />
  6145. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.y * 100)}%</span>
  6146. </div>
  6147. <div>
  6148. <label className="text-xs text-bambu-gray">{t('printers.width')}</label>
  6149. <input
  6150. type="range"
  6151. min="0.1"
  6152. max="1"
  6153. step="0.01"
  6154. value={editingRoi.w}
  6155. onChange={(e) => setEditingRoi({ ...editingRoi, w: parseFloat(e.target.value) })}
  6156. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6157. />
  6158. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.w * 100)}%</span>
  6159. </div>
  6160. <div>
  6161. <label className="text-xs text-bambu-gray">{t('printers.height')}</label>
  6162. <input
  6163. type="range"
  6164. min="0.1"
  6165. max="1"
  6166. step="0.01"
  6167. value={editingRoi.h}
  6168. onChange={(e) => setEditingRoi({ ...editingRoi, h: parseFloat(e.target.value) })}
  6169. className="w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"
  6170. />
  6171. <span className="text-xs text-bambu-gray">{Math.round(editingRoi.h * 100)}%</span>
  6172. </div>
  6173. </div>
  6174. <p className="text-xs text-bambu-gray">
  6175. {t('printers.roi.instruction')}
  6176. </p>
  6177. </div>
  6178. ) : (
  6179. <p className="text-xs text-bambu-gray">
  6180. Current: X={Math.round((plateCheckResult.roi?.x || 0.15) * 100)}%, Y={Math.round((plateCheckResult.roi?.y || 0.35) * 100)}%,
  6181. W={Math.round((plateCheckResult.roi?.w || 0.70) * 100)}%, H={Math.round((plateCheckResult.roi?.h || 0.55) * 100)}%
  6182. </p>
  6183. )}
  6184. </div>
  6185. )}
  6186. </div>
  6187. <div className="flex justify-end gap-2 p-4">
  6188. {plateCheckResult.needs_calibration ? (
  6189. <>
  6190. <Button variant="ghost" onClick={() => closePlateCheckModal()}>
  6191. {t('common.cancel')}
  6192. </Button>
  6193. <Button
  6194. onClick={() => handleCalibratePlate()}
  6195. disabled={isCalibrating}
  6196. >
  6197. {isCalibrating ? (
  6198. <>
  6199. <Loader2 className="w-[var(--pc-i4,1rem)] h-[var(--pc-i4,1rem)] mr-2 animate-spin" />
  6200. Calibrating...
  6201. </>
  6202. ) : (
  6203. 'Calibrate Empty Plate'
  6204. )}
  6205. </Button>
  6206. </>
  6207. ) : (
  6208. <>
  6209. <Button variant="ghost" onClick={() => handleCalibratePlate()} disabled={isCalibrating}>
  6210. {isCalibrating ? 'Adding...' : `Add Reference (${plateReferences?.references.length || 0}/${plateReferences?.max_references || 5})`}
  6211. </Button>
  6212. <Button onClick={() => closePlateCheckModal()}>
  6213. Close
  6214. </Button>
  6215. </>
  6216. )}
  6217. </div>
  6218. </div>
  6219. </div>
  6220. )}
  6221. {/* Power On Confirmation */}
  6222. {showPowerOnConfirm && smartPlug && (
  6223. <ConfirmModal
  6224. title={t('printers.confirm.powerOnTitle')}
  6225. message={t('printers.confirm.powerOnMessage', { name: printer.name })}
  6226. confirmText={t('printers.confirm.powerOnButton')}
  6227. variant="default"
  6228. onConfirm={() => {
  6229. powerControlMutation.mutate('on');
  6230. setShowPowerOnConfirm(false);
  6231. }}
  6232. onCancel={() => setShowPowerOnConfirm(false)}
  6233. />
  6234. )}
  6235. {/* Maintenance Mode mid-print confirmation (#1476) — entering maintenance
  6236. disconnects MQTT, which stops progress tracking + completion
  6237. notifications for the in-flight job. Idle / FINISH / FAILED states
  6238. skip this dialog and toggle directly. */}
  6239. {confirmMaintenanceEnter && (
  6240. <ConfirmModal
  6241. title={t('printers.maintenance.confirmMidPrintTitle')}
  6242. message={t('printers.maintenance.confirmMidPrintMessage', { name: printer.name })}
  6243. confirmText={t('printers.maintenance.menuEnter')}
  6244. variant="danger"
  6245. onConfirm={() => {
  6246. maintenanceMutation.mutate(false);
  6247. setConfirmMaintenanceEnter(false);
  6248. }}
  6249. onCancel={() => setConfirmMaintenanceEnter(false)}
  6250. />
  6251. )}
  6252. {/* Power Off Confirmation */}
  6253. {showPowerOffConfirm && smartPlug && (
  6254. <ConfirmModal
  6255. title={t('printers.confirm.powerOffTitle')}
  6256. message={
  6257. status?.state === 'RUNNING'
  6258. ? t('printers.confirm.powerOffWarning', { name: printer.name })
  6259. : t('printers.confirm.powerOffMessage', { name: printer.name })
  6260. }
  6261. confirmText={t('printers.confirm.powerOffButton')}
  6262. variant="danger"
  6263. onConfirm={() => {
  6264. powerControlMutation.mutate('off');
  6265. setShowPowerOffConfirm(false);
  6266. }}
  6267. onCancel={() => setShowPowerOffConfirm(false)}
  6268. />
  6269. )}
  6270. {/* HA entity toggle confirmation (Show on Printer Card switches) */}
  6271. {haToggleConfirm && (
  6272. <ConfirmModal
  6273. title={t('printers.confirm.haToggleTitle', { name: haToggleConfirm.name })}
  6274. message={
  6275. status?.state === 'RUNNING'
  6276. ? t('printers.confirm.haToggleWarning', { name: printer.name, entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6277. : t('printers.confirm.haToggleMessage', { entity: haToggleConfirm.ha_entity_id || haToggleConfirm.name })
  6278. }
  6279. confirmText={t('printers.confirm.haToggleButton')}
  6280. variant={status?.state === 'RUNNING' ? 'danger' : 'default'}
  6281. onConfirm={() => {
  6282. runScriptMutation.mutate({ id: haToggleConfirm.id, action: 'toggle' });
  6283. setHaToggleConfirm(null);
  6284. }}
  6285. onCancel={() => setHaToggleConfirm(null)}
  6286. />
  6287. )}
  6288. {/* Stop Print Confirmation */}
  6289. {showStopConfirm && (
  6290. <ConfirmModal
  6291. title={t('printers.confirm.stopTitle')}
  6292. message={t('printers.confirm.stopMessage', { name: printer.name })}
  6293. confirmText={t('printers.confirm.stopButton')}
  6294. variant="danger"
  6295. onConfirm={() => {
  6296. stopPrintMutation.mutate();
  6297. setShowStopConfirm(false);
  6298. }}
  6299. onCancel={() => setShowStopConfirm(false)}
  6300. />
  6301. )}
  6302. {/* Pause Print Confirmation */}
  6303. {showPauseConfirm && (
  6304. <ConfirmModal
  6305. title={t('printers.confirm.pauseTitle')}
  6306. message={t('printers.confirm.pauseMessage', { name: printer.name })}
  6307. confirmText={t('printers.confirm.pauseButton')}
  6308. variant="default"
  6309. onConfirm={() => {
  6310. pausePrintMutation.mutate();
  6311. setShowPauseConfirm(false);
  6312. }}
  6313. onCancel={() => setShowPauseConfirm(false)}
  6314. />
  6315. )}
  6316. {/* Resume Print Confirmation */}
  6317. {showResumeConfirm && (
  6318. <ConfirmModal
  6319. title={t('printers.confirm.resumeTitle')}
  6320. message={t('printers.confirm.resumeMessage', { name: printer.name })}
  6321. confirmText={t('printers.confirm.resumeButton')}
  6322. variant="default"
  6323. onConfirm={() => {
  6324. resumePrintMutation.mutate();
  6325. setShowResumeConfirm(false);
  6326. }}
  6327. onCancel={() => setShowResumeConfirm(false)}
  6328. />
  6329. )}
  6330. {/* Skip Objects Modal */}
  6331. <SkipObjectsModal
  6332. printerId={printer.id}
  6333. isOpen={showSkipObjectsModal}
  6334. onClose={() => setShowSkipObjectsModal(false)}
  6335. />
  6336. {/* HMS Error Modal */}
  6337. {showHMSModal && (
  6338. <HMSErrorModal
  6339. printerName={printer.name}
  6340. errors={status?.hms_errors || []}
  6341. onClose={() => setShowHMSModal(false)}
  6342. printerId={printer.id}
  6343. hasPermission={hasPermission}
  6344. runoutGuidance={runoutGuidance}
  6345. />
  6346. )}
  6347. {/* AI failure detection modal (#1546) */}
  6348. {showAiModal && (
  6349. <AiDetectionModal
  6350. printerName={printer.name}
  6351. detection={aiDetection}
  6352. lastError={aiLastError}
  6353. onClose={() => setShowAiModal(false)}
  6354. />
  6355. )}
  6356. {/* AMS Filament Backup status / control modal (#1762) */}
  6357. {amsBackupModalOpen && status && (
  6358. <AmsBackupModal
  6359. isOpen={amsBackupModalOpen}
  6360. state={status.ams_filament_backup}
  6361. amsUnits={status.ams}
  6362. amsExtruderMap={status.ams_extruder_map}
  6363. isDualNozzle={printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined}
  6364. canToggle={hasPermission('printers:control')}
  6365. pending={setAmsBackupMutation.isPending}
  6366. onToggle={(next) => setAmsBackupMutation.mutate(next)}
  6367. onClose={() => setAmsBackupModalOpen(false)}
  6368. />
  6369. )}
  6370. {/* AMS History Modal */}
  6371. {amsHistoryModal && (
  6372. <AMSHistoryModal
  6373. isOpen={!!amsHistoryModal}
  6374. onClose={() => setAmsHistoryModal(null)}
  6375. printerId={printer.id}
  6376. printerName={printer.name}
  6377. amsId={amsHistoryModal.amsId}
  6378. amsLabel={amsHistoryModal.amsLabel}
  6379. initialMode={amsHistoryModal.mode}
  6380. thresholds={amsThresholds}
  6381. />
  6382. )}
  6383. {/* Heater History Modal (nozzle / bed / chamber) */}
  6384. {heaterHistoryModal && (
  6385. <HeaterHistoryModal
  6386. isOpen={!!heaterHistoryModal}
  6387. onClose={() => setHeaterHistoryModal(null)}
  6388. printerId={printer.id}
  6389. printerName={printer.name}
  6390. initialKind={heaterHistoryModal.initialKind}
  6391. availableKinds={heaterHistoryModal.availableKinds}
  6392. />
  6393. )}
  6394. {/* Link Spool Modal */}
  6395. {linkSpoolModal && (
  6396. <LinkSpoolModal
  6397. isOpen={!!linkSpoolModal}
  6398. onClose={() => setLinkSpoolModal(null)}
  6399. tagUid={linkSpoolModal.tagUid}
  6400. trayUuid={linkSpoolModal.trayUuid}
  6401. printerId={linkSpoolModal.printerId}
  6402. amsId={linkSpoolModal.amsId}
  6403. trayId={linkSpoolModal.trayId}
  6404. />
  6405. )}
  6406. {/* Assign Spool Modal */}
  6407. {assignSpoolModal && (
  6408. <AssignSpoolModal
  6409. isOpen={!!assignSpoolModal}
  6410. onClose={() => setAssignSpoolModal(null)}
  6411. printerId={assignSpoolModal.printerId}
  6412. amsId={assignSpoolModal.amsId}
  6413. trayId={assignSpoolModal.trayId}
  6414. trayInfo={assignSpoolModal.trayInfo}
  6415. spoolmanEnabled={!!spoolmanEnabled}
  6416. />
  6417. )}
  6418. {/* Configure AMS Slot Modal */}
  6419. {configureSlotModal && (
  6420. <ConfigureAmsSlotModal
  6421. isOpen={!!configureSlotModal}
  6422. onClose={() => setConfigureSlotModal(null)}
  6423. printerId={printer.id}
  6424. slotInfo={configureSlotModal}
  6425. printerModel={mapModelCode(printer.model) || undefined}
  6426. nozzleDiameter={resolveSlotNozzleDiameter(status, configureSlotModal.amsId)}
  6427. onSuccess={() => {
  6428. // Refresh slot presets to show updated profile name
  6429. queryClient.invalidateQueries({ queryKey: ['slotPresets', printer.id] });
  6430. // Printer status will update automatically via WebSocket when AMS data changes
  6431. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  6432. }}
  6433. />
  6434. )}
  6435. {/* Edit Printer Modal */}
  6436. {showEditModal && (
  6437. <EditPrinterModal
  6438. printer={printer}
  6439. onClose={() => setShowEditModal(false)}
  6440. />
  6441. )}
  6442. {/* Firmware Update Modal */}
  6443. {showFirmwareModal && firmwareInfo && (
  6444. <FirmwareUpdateModal
  6445. printer={printer}
  6446. firmwareInfo={firmwareInfo}
  6447. onClose={() => setShowFirmwareModal(false)}
  6448. />
  6449. )}
  6450. {/* AMS Drying Popover — fixed position to avoid overflow/z-index issues */}
  6451. {dryingPopoverAmsId !== null && dryingPopoverPos && (() => {
  6452. const maxTemp = dryingPopoverModuleType === 'n3s' ? 85 : 65;
  6453. const sliderMin = 35;
  6454. const sliderMax = maxTemp + 10;
  6455. return (
  6456. <>
  6457. {/* Backdrop */}
  6458. <div className="fixed inset-0 z-[100]" onClick={() => setDryingPopoverAmsId(null)} />
  6459. {/* Popover */}
  6460. <div
  6461. className="fixed z-[101] flex flex-col w-[240px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl overflow-hidden"
  6462. style={{
  6463. top: dryingPopoverPos.top,
  6464. left: dryingPopoverPos.left,
  6465. // Cap to the space between the popover's top and the bottom
  6466. // viewport margin (8px, matching computePopoverPosition's
  6467. // margin). When the popover is taller than that space — short
  6468. // viewport, landscape phone, zoomed-in — the body scrolls and
  6469. // the footer stays pinned, so the Start button is always
  6470. // reachable (#1458 / #1447 follow-up). dvh (not vh) so iOS
  6471. // Safari's bottom toolbar overlay doesn't clip the footer
  6472. // (#1669, iPhone 17 Safari).
  6473. maxHeight: `calc(100dvh - ${dryingPopoverPos.top}px - 8px)`,
  6474. }}
  6475. onClick={e => e.stopPropagation()}
  6476. >
  6477. {/* Header */}
  6478. <div className="shrink-0 flex items-center justify-center gap-2 px-3 py-2.5">
  6479. <Flame className="w-[var(--pc-i35,0.875rem)] h-[var(--pc-i35,0.875rem)] text-bambu-green" />
  6480. <span className="text-sm text-white font-medium text-center">{t('printers.drying.start')}</span>
  6481. </div>
  6482. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6483. {/* Body */}
  6484. <div className="px-3 py-2.5 space-y-2.5 overflow-y-auto min-h-0">
  6485. {/* Filament type select */}
  6486. <div>
  6487. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium mb-1 block">{t('printers.filaments')}</label>
  6488. <ToolbarDropdown
  6489. value={dryingFilament}
  6490. options={Object.keys(dryingPresets).map(fil => ({ value: fil, label: fil }))}
  6491. onChange={fil => {
  6492. setDryingFilament(fil);
  6493. const preset = dryingPresets[fil];
  6494. if (preset) {
  6495. const key = dryingPopoverModuleType === 'n3s' ? 'n3s' : 'n3f';
  6496. setDryingTemp(preset[key]);
  6497. setDryingDuration(dryingPopoverModuleType === 'n3s' ? preset.n3s_hours : preset.n3f_hours);
  6498. }
  6499. }}
  6500. fullWidth
  6501. />
  6502. </div>
  6503. {/* Temperature */}
  6504. <div>
  6505. <div className="flex items-center justify-between mb-1">
  6506. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.temperature')}</label>
  6507. <div className="flex items-center gap-1">
  6508. <input
  6509. type="number"
  6510. min={45}
  6511. max={maxTemp}
  6512. value={dryingTemp}
  6513. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value) || 45)))}
  6514. className="w-12 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6515. />
  6516. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">°C</span>
  6517. </div>
  6518. </div>
  6519. <input
  6520. type="range"
  6521. min={sliderMin}
  6522. max={sliderMax}
  6523. value={dryingTemp}
  6524. onChange={e => setDryingTemp(Math.min(maxTemp, Math.max(45, Number(e.target.value))))}
  6525. className="w-full h-1 accent-bambu-green cursor-pointer"
  6526. />
  6527. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6528. <span>45°C</span>
  6529. <span>{maxTemp}°C</span>
  6530. </div>
  6531. </div>
  6532. {/* Duration */}
  6533. <div>
  6534. <div className="flex items-center justify-between mb-1">
  6535. <label className="text-[length:var(--pc-t10,10px)] text-white/70 font-medium">{t('printers.drying.duration')}</label>
  6536. <div className="flex items-center gap-1">
  6537. <input
  6538. type="number"
  6539. min={1}
  6540. max={24}
  6541. value={dryingDuration}
  6542. onChange={e => setDryingDuration(Math.min(24, Math.max(1, Number(e.target.value) || 1)))}
  6543. className="w-10 px-1 py-0.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-[length:var(--pc-t11,11px)] text-center focus:outline-none focus:border-bambu-green [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
  6544. />
  6545. <span className="text-[length:var(--pc-t10,10px)] text-bambu-gray">{t('printers.drying.hours')}</span>
  6546. </div>
  6547. </div>
  6548. <input
  6549. type="range"
  6550. min={1}
  6551. max={24}
  6552. value={dryingDuration}
  6553. onChange={e => setDryingDuration(Number(e.target.value))}
  6554. className="w-full h-1 accent-bambu-green cursor-pointer"
  6555. />
  6556. <div className="flex justify-between text-[length:var(--pc-t9,9px)] text-bambu-gray/50 mt-0.5">
  6557. <span>1h</span>
  6558. <span>24h</span>
  6559. </div>
  6560. </div>
  6561. {/* Rotate tray — disabled when any tray in THIS AMS has its
  6562. filament threaded out into the feed tube. The whole AMS
  6563. rotates as one mechanism (all 4 spools turn together), so a
  6564. single loaded slot locks the entire unit. Bambu per-tray
  6565. `state`: 9 = empty, 10 = spool present but not loaded
  6566. (rotation possible), 11 = loaded into tube (rotation impossible).
  6567. Catches both mid-print (active feed) AND idle-with-threaded-
  6568. filament — the H2D's post-print state leaves filament in the
  6569. tube but tray_now resets to 255, which a tray_now-only check
  6570. would silently miss. */}
  6571. {(() => {
  6572. const targetAms = dryingPopoverAmsId !== null
  6573. ? amsData.find(a => a.id === dryingPopoverAmsId)
  6574. : undefined;
  6575. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6576. tray => tray.state === 11,
  6577. );
  6578. const rotateChecked = dryingRotateTray && !trayLoadedInThisAms;
  6579. return (
  6580. <button
  6581. type="button"
  6582. onClick={() => setDryingRotateTray(enabled => !enabled)}
  6583. aria-pressed={rotateChecked}
  6584. disabled={trayLoadedInThisAms}
  6585. title={trayLoadedInThisAms ? t('printers.drying.rotateUnavailableReason') : undefined}
  6586. className={`h-8 w-full rounded-lg border px-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
  6587. rotateChecked
  6588. ? 'bg-bambu-green border-bambu-green text-white'
  6589. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary disabled:hover:bg-bambu-dark'
  6590. }`}
  6591. >
  6592. {t('printers.drying.rotateTray')}
  6593. </button>
  6594. );
  6595. })()}
  6596. </div>
  6597. <div className="shrink-0 h-px bg-bambu-dark-tertiary" />
  6598. {/* Footer */}
  6599. <div className="shrink-0 px-3 pt-2.5 pb-3">
  6600. <button
  6601. onClick={() => {
  6602. if (dryingPopoverAmsId !== null) {
  6603. // Clamp rotateTray off when any tray in this AMS is loaded into
  6604. // the tube — the rotate UI is disabled there, but the state may
  6605. // linger as `true` from a previous AMS, or a print may have
  6606. // started while the popover was open. Without this clamp the
  6607. // Start payload would carry rotate_tray=true and firmware would
  6608. // reject with dry_sf_reason=[3] (ConsumableAtAmsOutlet).
  6609. const targetAms = amsData.find(a => a.id === dryingPopoverAmsId);
  6610. const trayLoadedInThisAms = (targetAms?.tray ?? []).some(
  6611. tray => tray.state === 11,
  6612. );
  6613. startDryingMutation.mutate({
  6614. amsId: dryingPopoverAmsId,
  6615. temp: dryingTemp,
  6616. duration: dryingDuration,
  6617. filament: dryingFilament,
  6618. rotateTray: dryingRotateTray && !trayLoadedInThisAms,
  6619. });
  6620. }
  6621. }}
  6622. disabled={startDryingMutation.isPending}
  6623. data-testid="drying-start-confirm"
  6624. 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"
  6625. >
  6626. {startDryingMutation.isPending ? t('printers.drying.startingDrying') : t('printers.drying.start')}
  6627. </button>
  6628. </div>
  6629. </div>
  6630. </>
  6631. );
  6632. })()}
  6633. </Card>
  6634. );
  6635. }
  6636. export function AddPrinterModal({
  6637. onClose,
  6638. onAdd,
  6639. existingSerials,
  6640. }: {
  6641. onClose: () => void;
  6642. onAdd: (data: PrinterCreate) => void;
  6643. existingSerials: string[];
  6644. }) {
  6645. const { t } = useTranslation();
  6646. const [form, setForm] = useState<PrinterCreate>({
  6647. name: '',
  6648. serial_number: '',
  6649. ip_address: '',
  6650. access_code: '',
  6651. model: '',
  6652. location: '',
  6653. auto_archive: true,
  6654. });
  6655. // Discovery state
  6656. const [discovering, setDiscovering] = useState(false);
  6657. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  6658. const [discoveryError, setDiscoveryError] = useState('');
  6659. const [hasScanned, setHasScanned] = useState(false);
  6660. const [isDocker, setIsDocker] = useState(false);
  6661. const [detectedSubnets, setDetectedSubnets] = useState<string[]>([]);
  6662. const [subnet, setSubnet] = useState('');
  6663. // Custom subnet — `__custom__` sentinel in the dropdown reveals a CIDR
  6664. // text input so users can scan a subnet Bambuddy isn't directly on
  6665. // (printer behind a router on a different L3 segment — SSDP multicast
  6666. // won't cross that boundary, only an active unicast scan will). #1564
  6667. const [customSubnet, setCustomSubnet] = useState('');
  6668. const [useCustomSubnet, setUseCustomSubnet] = useState(false);
  6669. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  6670. const [showDiagnostic, setShowDiagnostic] = useState(false);
  6671. // Setup-time pre-flight: run the connection diagnostic on save and warn
  6672. // (not block) when checks fail, so the user doesn't add a printer that
  6673. // immediately shows offline. checkingSave = probe in flight; saveWarning =
  6674. // failed result awaiting an explicit "save anyway".
  6675. const [checkingSave, setCheckingSave] = useState(false);
  6676. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  6677. // Fetch discovery info on mount + restore the last custom CIDR the user
  6678. // typed (kept in localStorage so they don't retype `10.1.1.0/24` every
  6679. // time they open this modal).
  6680. useEffect(() => {
  6681. discoveryApi.getInfo().then(info => {
  6682. setIsDocker(info.is_docker);
  6683. if (info.subnets.length > 0) {
  6684. setDetectedSubnets(info.subnets);
  6685. setSubnet(info.subnets[0]);
  6686. }
  6687. }).catch(() => {
  6688. // Ignore errors, assume not Docker
  6689. });
  6690. try {
  6691. const saved = localStorage.getItem('bambuddy.discovery.customSubnet');
  6692. if (saved) setCustomSubnet(saved);
  6693. } catch {
  6694. // localStorage unavailable (private mode, quota); recall is opportunistic
  6695. }
  6696. }, []);
  6697. // Filter out already-added printers
  6698. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  6699. const handleAddSubmit = async (e: React.FormEvent) => {
  6700. e.preventDefault();
  6701. setCheckingSave(true);
  6702. try {
  6703. const result = await api.diagnoseConnection({
  6704. ip_address: form.ip_address.trim(),
  6705. serial_number: form.serial_number.trim() || undefined,
  6706. access_code: form.access_code || undefined,
  6707. });
  6708. if (result.checks.some((c) => c.status === 'fail')) {
  6709. setSaveWarning(result);
  6710. return;
  6711. }
  6712. } catch {
  6713. // Diagnostic infrastructure failed — never block the save on it.
  6714. } finally {
  6715. setCheckingSave(false);
  6716. }
  6717. onAdd(form);
  6718. };
  6719. const startDiscovery = async () => {
  6720. setDiscoveryError('');
  6721. setDiscovered([]);
  6722. setDiscovering(true);
  6723. setHasScanned(false);
  6724. setScanProgress({ scanned: 0, total: 0 });
  6725. // Native installs fall back to subnet scanning when the user picks
  6726. // "Custom" — SSDP can't reach a printer on a different L3 segment
  6727. // (#1564). Docker mode always uses subnet scan (multicast unavailable).
  6728. const scanCidr = useCustomSubnet ? customSubnet.trim() : subnet;
  6729. const wantsSubnetScan = isDocker || useCustomSubnet;
  6730. if (wantsSubnetScan && useCustomSubnet) {
  6731. try {
  6732. localStorage.setItem('bambuddy.discovery.customSubnet', scanCidr);
  6733. } catch {
  6734. // localStorage write best-effort; user just retypes next time
  6735. }
  6736. }
  6737. try {
  6738. if (wantsSubnetScan) {
  6739. await discoveryApi.startSubnetScan(scanCidr);
  6740. // Poll for scan status and results
  6741. const pollInterval = setInterval(async () => {
  6742. try {
  6743. const status = await discoveryApi.getScanStatus();
  6744. setScanProgress({ scanned: status.scanned, total: status.total });
  6745. const printers = await discoveryApi.getDiscoveredPrinters();
  6746. setDiscovered(printers);
  6747. if (!status.running) {
  6748. clearInterval(pollInterval);
  6749. setDiscovering(false);
  6750. setHasScanned(true);
  6751. }
  6752. } catch (e) {
  6753. console.error('Failed to get scan status:', e);
  6754. }
  6755. }, 500);
  6756. } else {
  6757. // Use SSDP discovery for native installs
  6758. await discoveryApi.startDiscovery(10);
  6759. // Poll for discovered printers every second
  6760. const pollInterval = setInterval(async () => {
  6761. try {
  6762. const printers = await discoveryApi.getDiscoveredPrinters();
  6763. setDiscovered(printers);
  6764. } catch (e) {
  6765. console.error('Failed to get discovered printers:', e);
  6766. }
  6767. }, 1000);
  6768. // Stop after 10 seconds
  6769. setTimeout(async () => {
  6770. clearInterval(pollInterval);
  6771. try {
  6772. await discoveryApi.stopDiscovery();
  6773. } catch {
  6774. // Ignore stop errors
  6775. }
  6776. setDiscovering(false);
  6777. setHasScanned(true);
  6778. // Final fetch
  6779. try {
  6780. const printers = await discoveryApi.getDiscoveredPrinters();
  6781. setDiscovered(printers);
  6782. } catch (e) {
  6783. console.error('Failed to get final discovered printers:', e);
  6784. }
  6785. }, 10000);
  6786. }
  6787. } catch (e) {
  6788. console.error('Failed to start discovery:', e);
  6789. setDiscoveryError(e instanceof Error ? e.message : t('printers.discovery.failedToStart'));
  6790. setDiscovering(false);
  6791. setHasScanned(true);
  6792. }
  6793. };
  6794. // Reuse module-level mapModelCode
  6795. const selectPrinter = (printer: DiscoveredPrinter) => {
  6796. // Don't pre-fill serial if it's a placeholder (unknown-*) - user needs to enter actual serial
  6797. const serialNumber = printer.serial.startsWith('unknown-') ? '' : printer.serial;
  6798. setForm({
  6799. ...form,
  6800. name: printer.name || '',
  6801. serial_number: serialNumber,
  6802. ip_address: printer.ip_address,
  6803. model: mapModelCode(printer.model),
  6804. });
  6805. // Clear discovery results after selection
  6806. setDiscovered([]);
  6807. };
  6808. // Cleanup discovery on unmount
  6809. useEffect(() => {
  6810. return () => {
  6811. discoveryApi.stopDiscovery().catch(() => {});
  6812. discoveryApi.stopSubnetScan().catch(() => {});
  6813. };
  6814. }, []);
  6815. // Close on Escape key
  6816. useEffect(() => {
  6817. const handleKeyDown = (e: KeyboardEvent) => {
  6818. if (e.key === 'Escape') onClose();
  6819. };
  6820. window.addEventListener('keydown', handleKeyDown);
  6821. return () => window.removeEventListener('keydown', handleKeyDown);
  6822. }, [onClose]);
  6823. return (
  6824. <>
  6825. <div
  6826. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  6827. onClick={onClose}
  6828. >
  6829. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  6830. <CardContent>
  6831. <h2 className="text-xl font-semibold mb-4">{t('printers.addPrinter')}</h2>
  6832. {/* Discovery Section */}
  6833. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  6834. {/* Subnet picker — always visible. The dropdown lists detected
  6835. interface subnets and a "Custom..." sentinel that reveals
  6836. a CIDR text input for printers on a different L3 segment
  6837. (router, VLAN, etc.). #1564 */}
  6838. <div className="mb-3">
  6839. <label className="block text-sm text-bambu-gray mb-1">
  6840. {t('printers.discovery.subnetToScan')}
  6841. </label>
  6842. {detectedSubnets.length > 0 ? (
  6843. <select
  6844. 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"
  6845. value={useCustomSubnet ? '__custom__' : subnet}
  6846. onChange={(e) => {
  6847. if (e.target.value === '__custom__') {
  6848. setUseCustomSubnet(true);
  6849. } else {
  6850. setUseCustomSubnet(false);
  6851. setSubnet(e.target.value);
  6852. }
  6853. }}
  6854. disabled={discovering}
  6855. >
  6856. {detectedSubnets.map(s => (
  6857. <option key={s} value={s}>{s}</option>
  6858. ))}
  6859. <option value="__custom__">{t('printers.discovery.customSubnetOption')}</option>
  6860. </select>
  6861. ) : (
  6862. <input
  6863. type="text"
  6864. 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"
  6865. value={subnet}
  6866. onChange={(e) => setSubnet(e.target.value)}
  6867. placeholder="192.168.1.0/24"
  6868. disabled={discovering}
  6869. />
  6870. )}
  6871. {useCustomSubnet && (
  6872. <input
  6873. type="text"
  6874. aria-label={t('printers.discovery.customSubnetLabel')}
  6875. 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"
  6876. value={customSubnet}
  6877. onChange={(e) => setCustomSubnet(e.target.value)}
  6878. placeholder="10.1.1.0/24"
  6879. disabled={discovering}
  6880. />
  6881. )}
  6882. <p className="mt-1 text-xs text-bambu-gray">
  6883. {isDocker
  6884. ? t('printers.discovery.dockerNote')
  6885. : t('printers.discovery.customSubnetNote')}
  6886. </p>
  6887. </div>
  6888. <Button
  6889. type="button"
  6890. variant="secondary"
  6891. onClick={startDiscovery}
  6892. disabled={discovering}
  6893. className="w-full"
  6894. >
  6895. {discovering ? (
  6896. <>
  6897. <Loader2 className="w-4 h-4 animate-spin" />
  6898. {(isDocker || useCustomSubnet) && scanProgress.total > 0
  6899. ? t('printers.discovery.scanProgress', { scanned: scanProgress.scanned, total: scanProgress.total })
  6900. : t('printers.discovery.scanning')}
  6901. </>
  6902. ) : (
  6903. <>
  6904. <Search className="w-4 h-4" />
  6905. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanSubnet') : t('printers.discovery.discoverNetwork')}
  6906. </>
  6907. )}
  6908. </Button>
  6909. {discoveryError && (
  6910. <div className="mt-2 text-sm text-red-700 dark:text-red-400">{discoveryError}</div>
  6911. )}
  6912. {newPrinters.length > 0 && (
  6913. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  6914. {newPrinters.map((printer) => (
  6915. <div
  6916. key={printer.serial}
  6917. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  6918. onClick={() => selectPrinter(printer)}
  6919. >
  6920. <div className="min-w-0 flex-1">
  6921. <p className="font-medium text-white text-sm truncate">
  6922. {printer.name || printer.serial}
  6923. </p>
  6924. <p className="text-xs text-bambu-gray truncate">
  6925. {mapModelCode(printer.model) || t('printers.discovery.unknown')} • {printer.ip_address}
  6926. {printer.serial.startsWith('unknown-') && (
  6927. <span className="text-yellow-500"> • {t('printers.discovery.serialRequired')}</span>
  6928. )}
  6929. </p>
  6930. </div>
  6931. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  6932. </div>
  6933. ))}
  6934. </div>
  6935. )}
  6936. {discovering && (
  6937. <p className="mt-2 text-sm text-bambu-gray text-center">
  6938. {(isDocker || useCustomSubnet) ? t('printers.discovery.scanningSubnet') : t('printers.discovery.scanningNetwork')}
  6939. </p>
  6940. )}
  6941. {hasScanned && !discovering && discovered.length === 0 && (
  6942. <p className="mt-2 text-sm text-bambu-gray text-center">
  6943. {(isDocker || useCustomSubnet) ? t('printers.discovery.noPrintersFoundSubnet') : t('printers.discovery.noPrintersFoundNetwork')}
  6944. </p>
  6945. )}
  6946. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  6947. <p className="mt-2 text-sm text-bambu-gray text-center">
  6948. {t('printers.discovery.allConfigured')}
  6949. </p>
  6950. )}
  6951. </div>
  6952. <form onSubmit={handleAddSubmit} className="space-y-4">
  6953. <div>
  6954. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  6955. <input
  6956. type="text"
  6957. required
  6958. 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"
  6959. value={form.name}
  6960. onChange={(e) => setForm({ ...form, name: e.target.value })}
  6961. placeholder={t('printers.modal.myPrinter')}
  6962. />
  6963. </div>
  6964. <div>
  6965. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  6966. <input
  6967. type="text"
  6968. required
  6969. 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])?)*)"
  6970. 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"
  6971. value={form.ip_address}
  6972. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  6973. placeholder="192.168.1.100 or printer.local"
  6974. />
  6975. </div>
  6976. <div>
  6977. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  6978. <input
  6979. type="text"
  6980. required
  6981. 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"
  6982. value={form.serial_number}
  6983. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  6984. placeholder="01P00A000000000"
  6985. />
  6986. </div>
  6987. <div>
  6988. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  6989. <input
  6990. type="password"
  6991. required
  6992. 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"
  6993. value={form.access_code}
  6994. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  6995. placeholder={t('printers.modal.fromPrinterSettings')}
  6996. />
  6997. </div>
  6998. <div>
  6999. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.modelOptional')}</label>
  7000. <select
  7001. 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"
  7002. value={form.model || ''}
  7003. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7004. >
  7005. <option value="">{t('printers.modal.selectModel')}</option>
  7006. <optgroup label="A1 Series">
  7007. <option value="A1">A1</option>
  7008. <option value="A1 Mini">A1 Mini</option>
  7009. </optgroup>
  7010. <optgroup label="A2 Series">
  7011. <option value="A2L">A2L</option>
  7012. </optgroup>
  7013. <optgroup label="H2 Series">
  7014. <option value="H2C">H2C</option>
  7015. <option value="H2D">H2D</option>
  7016. <option value="H2D Pro">H2D Pro</option>
  7017. <option value="H2S">H2S</option>
  7018. </optgroup>
  7019. <optgroup label="P Series">
  7020. <option value="P1P">P1P</option>
  7021. <option value="P1S">P1S</option>
  7022. <option value="P2S">P2S</option>
  7023. </optgroup>
  7024. <optgroup label="X1 Series">
  7025. <option value="X1">X1</option>
  7026. <option value="X1C">X1 Carbon</option>
  7027. <option value="X1E">X1E</option>
  7028. </optgroup>
  7029. <optgroup label="X2 Series">
  7030. <option value="X2D">X2D</option>
  7031. </optgroup>
  7032. </select>
  7033. </div>
  7034. <div>
  7035. <label className="block text-sm text-bambu-gray mb-1">{t('printers.modal.locationGroup')}</label>
  7036. <input
  7037. type="text"
  7038. 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"
  7039. value={form.location || ''}
  7040. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7041. placeholder={t('printers.modal.locationPlaceholder')}
  7042. />
  7043. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7044. </div>
  7045. <div className="flex items-center gap-2">
  7046. <input
  7047. type="checkbox"
  7048. id="auto_archive"
  7049. checked={form.auto_archive}
  7050. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7051. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7052. />
  7053. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  7054. {t('printers.modal.autoArchiveLabel')}
  7055. </label>
  7056. </div>
  7057. <button
  7058. type="button"
  7059. onClick={() => setShowDiagnostic(true)}
  7060. disabled={!form.ip_address.trim()}
  7061. 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"
  7062. >
  7063. <Stethoscope className="w-4 h-4" />
  7064. {t('diagnostic.runButton')}
  7065. </button>
  7066. {saveWarning ? (
  7067. <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">
  7068. <div className="flex items-start gap-2">
  7069. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7070. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7071. </div>
  7072. <DiagnosticChecklist result={saveWarning} />
  7073. <div className="flex gap-3">
  7074. <Button
  7075. type="button"
  7076. variant="secondary"
  7077. onClick={() => setSaveWarning(null)}
  7078. className="flex-1"
  7079. >
  7080. {t('printers.addPreflight.back')}
  7081. </Button>
  7082. <Button type="button" onClick={() => onAdd(form)} className="flex-1">
  7083. {t('printers.addPreflight.saveAnyway')}
  7084. </Button>
  7085. </div>
  7086. </div>
  7087. ) : (
  7088. <div className="flex gap-3 pt-2">
  7089. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7090. {t('common.cancel')}
  7091. </Button>
  7092. <Button type="submit" disabled={checkingSave} className="flex-1">
  7093. {checkingSave ? t('printers.addPreflight.checking') : t('printers.addPrinter')}
  7094. </Button>
  7095. </div>
  7096. )}
  7097. </form>
  7098. </CardContent>
  7099. </Card>
  7100. </div>
  7101. {showDiagnostic && (
  7102. <ConnectionDiagnosticModal
  7103. connection={{
  7104. ip_address: form.ip_address.trim(),
  7105. serial_number: form.serial_number.trim() || undefined,
  7106. access_code: form.access_code || undefined,
  7107. }}
  7108. printerName={form.name || null}
  7109. onClose={() => setShowDiagnostic(false)}
  7110. />
  7111. )}
  7112. </>
  7113. );
  7114. }
  7115. function FirmwareUpdateModal({
  7116. printer,
  7117. firmwareInfo,
  7118. onClose,
  7119. }: {
  7120. printer: Printer;
  7121. firmwareInfo: FirmwareUpdateInfo;
  7122. onClose: () => void;
  7123. }) {
  7124. const { t } = useTranslation();
  7125. const queryClient = useQueryClient();
  7126. const { showToast } = useToast();
  7127. const { hasPermission } = useAuth();
  7128. const canUpdate = hasPermission('firmware:update');
  7129. const [uploadStatus, setUploadStatus] = useState<FirmwareUploadStatus | null>(null);
  7130. const [isUploading, setIsUploading] = useState(false);
  7131. const [pollInterval, setPollInterval] = useState<NodeJS.Timeout | null>(null);
  7132. const [selectedVersion, setSelectedVersion] = useState<string | null>(
  7133. firmwareInfo.update_available ? firmwareInfo.latest_version : null,
  7134. );
  7135. // Prepare check query — runs when a version is selected and user can update
  7136. const { data: prepareInfo, isLoading: isPreparing } = useQuery({
  7137. queryKey: ['firmwarePrepare', printer.id, selectedVersion],
  7138. queryFn: () => firmwareApi.prepareUpload(printer.id, selectedVersion ?? undefined),
  7139. staleTime: 30000,
  7140. enabled: !!selectedVersion && canUpdate && !isUploading,
  7141. });
  7142. // Start upload mutation
  7143. const uploadMutation = useMutation({
  7144. mutationFn: () => firmwareApi.startUpload(printer.id, selectedVersion ?? undefined),
  7145. onSuccess: () => {
  7146. setIsUploading(true);
  7147. // Start polling for status
  7148. const interval = setInterval(async () => {
  7149. try {
  7150. const status = await firmwareApi.getUploadStatus(printer.id);
  7151. setUploadStatus(status);
  7152. if (status.status === 'complete' || status.status === 'error') {
  7153. clearInterval(interval);
  7154. setPollInterval(null);
  7155. setIsUploading(false);
  7156. if (status.status === 'complete') {
  7157. showToast(t('printers.firmwareModal.uploadedToast'), 'success');
  7158. queryClient.invalidateQueries({ queryKey: ['firmwareUpdate', printer.id] });
  7159. }
  7160. }
  7161. } catch {
  7162. // Ignore errors during polling
  7163. }
  7164. }, 2000);
  7165. setPollInterval(interval);
  7166. },
  7167. onError: (error: Error) => {
  7168. showToast(t('printers.firmwareModal.uploadFailed', { error: error.message }), 'error');
  7169. setIsUploading(false);
  7170. },
  7171. });
  7172. // Cleanup on unmount
  7173. useEffect(() => {
  7174. return () => {
  7175. if (pollInterval) clearInterval(pollInterval);
  7176. };
  7177. }, [pollInterval]);
  7178. const handleStartUpload = () => {
  7179. setUploadStatus(null);
  7180. uploadMutation.mutate();
  7181. };
  7182. return (
  7183. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  7184. <Card className="w-full max-w-md mx-4">
  7185. <CardContent>
  7186. <div className="flex items-start gap-3 mb-4">
  7187. <div className={`p-2 rounded-full ${firmwareInfo.update_available ? 'bg-orange-100 dark:bg-orange-500/20' : 'bg-status-ok/20'}`}>
  7188. {firmwareInfo.update_available
  7189. ? <Download className="w-5 h-5 text-orange-600 dark:text-orange-400" />
  7190. : <CheckCircle className="w-5 h-5 text-status-ok" />}
  7191. </div>
  7192. <div className="flex-1">
  7193. <h3 className="text-lg font-semibold text-white">
  7194. {firmwareInfo.update_available ? t('printers.firmwareModal.title') : t('printers.firmwareModal.titleUpToDate')}
  7195. </h3>
  7196. <p className="text-sm text-bambu-gray mt-1">
  7197. {printer.name}
  7198. </p>
  7199. </div>
  7200. </div>
  7201. {/* Version Info */}
  7202. {(() => {
  7203. const selectedEntry = selectedVersion
  7204. ? firmwareInfo.available_versions?.find((v) => v.version === selectedVersion)
  7205. : null;
  7206. const displayVersion = selectedVersion ?? firmwareInfo.latest_version;
  7207. const displayNotes = selectedEntry?.release_notes ?? firmwareInfo.release_notes;
  7208. const showSecondLine = !!displayVersion && displayVersion !== firmwareInfo.current_version;
  7209. return (
  7210. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  7211. <div className="flex justify-between items-center text-sm">
  7212. <span className="text-bambu-gray">{t('printers.firmwareModal.currentVersion')}</span>
  7213. <span className={`font-mono ${showSecondLine ? 'text-white' : 'text-status-ok'}`}>
  7214. {firmwareInfo.current_version || t('common.unknown')}
  7215. </span>
  7216. </div>
  7217. {showSecondLine && (
  7218. <div className="flex justify-between items-center text-sm mt-1">
  7219. <span className="text-bambu-gray">{t('printers.firmwareModal.latestVersion')}</span>
  7220. <span className="text-orange-700 dark:text-orange-400 font-mono">{displayVersion}</span>
  7221. </div>
  7222. )}
  7223. {displayNotes && (
  7224. <details className="mt-3 text-sm" open={!showSecondLine} key={displayVersion ?? 'none'}>
  7225. <summary className={`cursor-pointer hover:underline ${showSecondLine ? 'text-orange-700 dark:text-orange-400' : 'text-status-ok'}`}>
  7226. {t('printers.firmwareModal.releaseNotes')}
  7227. </summary>
  7228. <div className="mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap">
  7229. {displayNotes}
  7230. </div>
  7231. </details>
  7232. )}
  7233. </div>
  7234. );
  7235. })()}
  7236. {/* Available versions list */}
  7237. {firmwareInfo.available_versions && firmwareInfo.available_versions.length > 0 && !isUploading && uploadStatus?.status !== 'complete' && (
  7238. <div className="mb-4">
  7239. <div className="text-xs text-bambu-gray mb-2">{t('printers.firmwareModal.availableVersions')}</div>
  7240. <div className="max-h-56 overflow-y-auto border border-bambu-dark-tertiary rounded-lg divide-y divide-bambu-dark-tertiary">
  7241. {firmwareInfo.available_versions.map((v) => {
  7242. const isCurrent = firmwareInfo.current_version === v.version;
  7243. const isSelected = selectedVersion === v.version;
  7244. const cmp = firmwareInfo.current_version
  7245. ? compareFwVersions(v.version, firmwareInfo.current_version)
  7246. : 0;
  7247. const relLabel = isCurrent
  7248. ? t('printers.firmwareModal.currentBadge')
  7249. : cmp > 0
  7250. ? t('printers.firmwareModal.newerBadge')
  7251. : t('printers.firmwareModal.olderBadge');
  7252. const relClass = isCurrent
  7253. ? 'text-bambu-gray'
  7254. : cmp > 0
  7255. ? 'text-orange-700 dark:text-orange-400'
  7256. : 'text-blue-700 dark:text-blue-400';
  7257. return (
  7258. <button
  7259. key={v.version}
  7260. type="button"
  7261. disabled={!v.file_available || !canUpdate || isCurrent}
  7262. onClick={() => setSelectedVersion(v.version)}
  7263. className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 transition-colors ${
  7264. isSelected ? 'bg-orange-50 dark:bg-orange-500/10' : 'hover:bg-bambu-dark'
  7265. } ${!v.file_available || !canUpdate || isCurrent ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
  7266. >
  7267. <div className="flex items-center gap-2 min-w-0">
  7268. <span className="font-mono text-white">{v.version}</span>
  7269. <span className={`text-xs ${relClass}`}>{relLabel}</span>
  7270. </div>
  7271. <span className={`text-xs px-2 py-0.5 rounded-full ${
  7272. isCurrent
  7273. ? 'bg-blue-50 dark:bg-blue-500/15 text-blue-700 dark:text-blue-400 border border-blue-300 dark:border-blue-500/30'
  7274. : v.file_available
  7275. ? 'bg-bambu-green/15 text-bambu-green border border-bambu-green/30'
  7276. : 'bg-bambu-gray/10 text-bambu-gray border border-bambu-gray/30'
  7277. }`}>
  7278. {isCurrent
  7279. ? t('printers.firmwareModal.installed')
  7280. : v.file_available
  7281. ? t('printers.firmwareModal.usable')
  7282. : t('printers.firmwareModal.unavailable')}
  7283. </span>
  7284. </button>
  7285. );
  7286. })}
  7287. </div>
  7288. </div>
  7289. )}
  7290. {/* Status / Progress (only when a version is selected) */}
  7291. {!selectedVersion ? null : isPreparing ? (
  7292. <div className="flex items-center gap-2 text-bambu-gray text-sm mb-4">
  7293. <Loader2 className="w-4 h-4 animate-spin" />
  7294. {t('printers.firmwareModal.checkingPrereqs')}
  7295. </div>
  7296. ) : prepareInfo && !isUploading && !uploadStatus ? (
  7297. <div className="mb-4">
  7298. {prepareInfo.can_proceed ? (
  7299. <div className="flex items-center gap-2 text-bambu-green text-sm">
  7300. <Box className="w-4 h-4" />
  7301. {t('printers.firmwareModal.sdCardReady')}
  7302. </div>
  7303. ) : (
  7304. <div className="space-y-1">
  7305. {prepareInfo.errors.map((error, i) => (
  7306. <div key={i} className="flex items-center gap-2 text-red-700 dark:text-red-400 text-sm">
  7307. <AlertCircle className="w-4 h-4 flex-shrink-0" />
  7308. {error}
  7309. </div>
  7310. ))}
  7311. </div>
  7312. )}
  7313. </div>
  7314. ) : null}
  7315. {/* Upload Progress */}
  7316. {(isUploading || uploadStatus) && uploadStatus && (
  7317. <div className="mb-4">
  7318. <div className="flex items-center justify-between text-sm mb-1">
  7319. <span className="text-bambu-gray capitalize">{uploadStatus.status}</span>
  7320. <span className="text-white">{uploadStatus.progress}%</span>
  7321. </div>
  7322. <div className="w-full bg-bambu-dark-tertiary rounded-full h-2">
  7323. <div
  7324. className={`h-2 rounded-full transition-all ${
  7325. uploadStatus.status === 'error' ? 'bg-status-error' :
  7326. uploadStatus.status === 'complete' ? 'bg-status-ok' : 'bg-orange-500'
  7327. } ${uploadStatus.status === 'uploading' ? 'animate-pulse' : ''}`}
  7328. style={{ width: `${uploadStatus.progress}%` }}
  7329. />
  7330. </div>
  7331. <p className="text-xs text-bambu-gray mt-1">{uploadStatus.message}</p>
  7332. {uploadStatus.error && (
  7333. <p className="text-xs text-red-700 dark:text-red-400 mt-1">{uploadStatus.error}</p>
  7334. )}
  7335. </div>
  7336. )}
  7337. {/* Success Message */}
  7338. {uploadStatus?.status === 'complete' && (
  7339. <div className="bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4">
  7340. <p className="text-sm text-bambu-green font-medium mb-2">
  7341. {t('printers.firmwareModal.uploadedSuccess')}
  7342. </p>
  7343. <p className="text-xs text-bambu-gray">
  7344. {t('printers.firmwareModal.applyInstructions')}
  7345. </p>
  7346. <ol className="text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1">
  7347. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step1') }} />
  7348. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step2') }} />
  7349. <li dangerouslySetInnerHTML={{ __html: t('printers.firmwareModal.step3') }} />
  7350. <li>{t('printers.firmwareModal.step4')}</li>
  7351. </ol>
  7352. </div>
  7353. )}
  7354. {/* Buttons */}
  7355. <div className="flex gap-2 justify-end">
  7356. <Button variant="secondary" onClick={onClose}>
  7357. {uploadStatus?.status === 'complete' ? t('printers.firmwareModal.done') : t('common.cancel')}
  7358. </Button>
  7359. {prepareInfo?.can_proceed && !isUploading && uploadStatus?.status !== 'complete' && canUpdate && (
  7360. <Button
  7361. onClick={handleStartUpload}
  7362. disabled={uploadMutation.isPending}
  7363. >
  7364. {uploadMutation.isPending ? (
  7365. <>
  7366. <Loader2 className="w-4 h-4 animate-spin mr-2" />
  7367. {t('printers.firmwareModal.starting')}
  7368. </>
  7369. ) : (
  7370. <>
  7371. <Download className="w-4 h-4 mr-2" />
  7372. {t('printers.firmwareModal.uploadFirmware')}
  7373. </>
  7374. )}
  7375. </Button>
  7376. )}
  7377. </div>
  7378. </CardContent>
  7379. </Card>
  7380. </div>
  7381. );
  7382. }
  7383. function EditPrinterModal({
  7384. printer,
  7385. onClose,
  7386. }: {
  7387. printer: Printer;
  7388. onClose: () => void;
  7389. }) {
  7390. const { t } = useTranslation();
  7391. const queryClient = useQueryClient();
  7392. const { showToast } = useToast();
  7393. const [form, setForm] = useState({
  7394. name: printer.name,
  7395. ip_address: printer.ip_address,
  7396. access_code: '',
  7397. model: printer.model || '',
  7398. location: printer.location || '',
  7399. auto_archive: printer.auto_archive,
  7400. is_active: printer.is_active,
  7401. });
  7402. // Setup-time pre-flight — same warn-on-save as the Add-Printer dialog, so an
  7403. // edit that breaks connectivity (e.g. a mistyped IP) is caught before save.
  7404. const [checkingSave, setCheckingSave] = useState(false);
  7405. const [saveWarning, setSaveWarning] = useState<PrinterDiagnosticResult | null>(null);
  7406. const updateMutation = useMutation({
  7407. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  7408. onSuccess: () => {
  7409. queryClient.invalidateQueries({ queryKey: ['printers'] });
  7410. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  7411. onClose();
  7412. },
  7413. onError: (error: Error) => showToast(error.message || t('printers.toast.failedToUpdate'), 'error'),
  7414. });
  7415. // Close on Escape key
  7416. useEffect(() => {
  7417. const handleKeyDown = (e: KeyboardEvent) => {
  7418. if (e.key === 'Escape') onClose();
  7419. };
  7420. window.addEventListener('keydown', handleKeyDown);
  7421. return () => window.removeEventListener('keydown', handleKeyDown);
  7422. }, [onClose]);
  7423. const doSave = () => {
  7424. const data: Partial<PrinterCreate> = {
  7425. name: form.name,
  7426. ip_address: form.ip_address,
  7427. model: form.model || undefined,
  7428. location: form.location || undefined,
  7429. auto_archive: form.auto_archive,
  7430. is_active: form.is_active,
  7431. };
  7432. // Only include access_code if it was changed
  7433. if (form.access_code) {
  7434. data.access_code = form.access_code;
  7435. }
  7436. updateMutation.mutate(data);
  7437. };
  7438. const handleSubmit = async (e: React.FormEvent) => {
  7439. e.preventDefault();
  7440. setCheckingSave(true);
  7441. try {
  7442. const result = await api.diagnoseConnection({
  7443. ip_address: form.ip_address.trim(),
  7444. serial_number: printer.serial_number,
  7445. access_code: form.access_code || undefined,
  7446. });
  7447. if (result.checks.some((c) => c.status === 'fail')) {
  7448. setSaveWarning(result);
  7449. return;
  7450. }
  7451. } catch {
  7452. // Diagnostic infrastructure failed — never block the save on it.
  7453. } finally {
  7454. setCheckingSave(false);
  7455. }
  7456. doSave();
  7457. };
  7458. return (
  7459. <div
  7460. className="fixed inset-0 bg-black/50 flex items-start sm:items-center justify-center z-50 p-4 overflow-y-auto"
  7461. onClick={onClose}
  7462. >
  7463. <Card className="w-full max-w-md my-auto max-h-[calc(100vh-2rem)] overflow-y-auto" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  7464. <CardContent>
  7465. <h2 className="text-xl font-semibold mb-4">{t('printers.editPrinter')}</h2>
  7466. <form onSubmit={handleSubmit} className="space-y-4">
  7467. <div>
  7468. <label className="block text-sm text-bambu-gray mb-1">{t('printers.name')}</label>
  7469. <input
  7470. type="text"
  7471. required
  7472. 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"
  7473. value={form.name}
  7474. onChange={(e) => setForm({ ...form, name: e.target.value })}
  7475. placeholder={t('printers.modal.myPrinter')}
  7476. />
  7477. </div>
  7478. <div>
  7479. <label className="block text-sm text-bambu-gray mb-1">{t('printers.ipAddress')}</label>
  7480. <input
  7481. type="text"
  7482. required
  7483. 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])?)*)"
  7484. 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"
  7485. value={form.ip_address}
  7486. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  7487. placeholder="192.168.1.100 or printer.local"
  7488. />
  7489. </div>
  7490. <div>
  7491. <label className="block text-sm text-bambu-gray mb-1">{t('printers.serialNumber')}</label>
  7492. <input
  7493. type="text"
  7494. disabled
  7495. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  7496. value={printer.serial_number}
  7497. />
  7498. <p className="text-xs text-bambu-gray mt-1">{t('printers.serialCannotBeChanged')}</p>
  7499. </div>
  7500. <div>
  7501. <label className="block text-sm text-bambu-gray mb-1">{t('printers.accessCode')}</label>
  7502. <input
  7503. type="password"
  7504. 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"
  7505. value={form.access_code}
  7506. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  7507. placeholder={t('printers.accessCodePlaceholder')}
  7508. />
  7509. </div>
  7510. <div>
  7511. <label className="block text-sm text-bambu-gray mb-1">{t('printers.model')}</label>
  7512. <select
  7513. 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"
  7514. value={form.model}
  7515. onChange={(e) => setForm({ ...form, model: e.target.value })}
  7516. >
  7517. <option value="">{t('printers.modal.selectModel')}</option>
  7518. <optgroup label="A1 Series">
  7519. <option value="A1">A1</option>
  7520. <option value="A1 Mini">A1 Mini</option>
  7521. </optgroup>
  7522. <optgroup label="A2 Series">
  7523. <option value="A2L">A2L</option>
  7524. </optgroup>
  7525. <optgroup label="H2 Series">
  7526. <option value="H2C">H2C</option>
  7527. <option value="H2D">H2D</option>
  7528. <option value="H2D Pro">H2D Pro</option>
  7529. <option value="H2S">H2S</option>
  7530. </optgroup>
  7531. <optgroup label="P Series">
  7532. <option value="P1P">P1P</option>
  7533. <option value="P1S">P1S</option>
  7534. <option value="P2S">P2S</option>
  7535. </optgroup>
  7536. <optgroup label="X1 Series">
  7537. <option value="X1">X1</option>
  7538. <option value="X1C">X1 Carbon</option>
  7539. <option value="X1E">X1E</option>
  7540. </optgroup>
  7541. <optgroup label="X2 Series">
  7542. <option value="X2D">X2D</option>
  7543. </optgroup>
  7544. </select>
  7545. </div>
  7546. <div>
  7547. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  7548. <input
  7549. type="text"
  7550. 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"
  7551. value={form.location}
  7552. onChange={(e) => setForm({ ...form, location: e.target.value })}
  7553. placeholder={t('printers.modal.locationPlaceholder')}
  7554. />
  7555. <p className="text-xs text-bambu-gray mt-1">{t('printers.locationHelp')}</p>
  7556. </div>
  7557. <div className="flex items-center gap-2">
  7558. <input
  7559. type="checkbox"
  7560. id="edit_auto_archive"
  7561. checked={form.auto_archive}
  7562. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  7563. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  7564. />
  7565. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  7566. {t('printers.modal.autoArchiveLabel')}
  7567. </label>
  7568. </div>
  7569. {/* Maintenance Mode toggle (#1476) — checkbox is the inverse of
  7570. is_active because the user-facing concept is "is this printer
  7571. in maintenance" not "is it active". */}
  7572. <div>
  7573. <div className="flex items-center gap-2">
  7574. <input
  7575. type="checkbox"
  7576. id="edit_maintenance_mode"
  7577. checked={!form.is_active}
  7578. onChange={(e) => setForm({ ...form, is_active: !e.target.checked })}
  7579. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-amber-400 focus:ring-amber-400"
  7580. />
  7581. <label htmlFor="edit_maintenance_mode" className="text-sm text-bambu-gray flex items-center gap-1.5">
  7582. <Wrench className="w-3.5 h-3.5 text-amber-600 dark:text-amber-400" />
  7583. {t('printers.maintenance.editFieldLabel')}
  7584. </label>
  7585. </div>
  7586. <p className="text-xs text-bambu-gray/70 mt-1 ml-6">
  7587. {t('printers.maintenance.editFieldHelp')}
  7588. </p>
  7589. </div>
  7590. {saveWarning ? (
  7591. <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">
  7592. <div className="flex items-start gap-2">
  7593. <AlertTriangle className="w-4 h-4 mt-0.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
  7594. <p className="text-sm text-amber-700 dark:text-amber-300">{t('printers.addPreflight.warning')}</p>
  7595. </div>
  7596. <DiagnosticChecklist result={saveWarning} />
  7597. <div className="flex gap-3">
  7598. <Button
  7599. type="button"
  7600. variant="secondary"
  7601. onClick={() => setSaveWarning(null)}
  7602. className="flex-1"
  7603. >
  7604. {t('printers.addPreflight.back')}
  7605. </Button>
  7606. <Button
  7607. type="button"
  7608. onClick={doSave}
  7609. className="flex-1"
  7610. disabled={updateMutation.isPending}
  7611. >
  7612. {t('printers.addPreflight.saveAnyway')}
  7613. </Button>
  7614. </div>
  7615. </div>
  7616. ) : (
  7617. <div className="flex gap-3 pt-4">
  7618. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  7619. {t('common.cancel')}
  7620. </Button>
  7621. <Button
  7622. type="submit"
  7623. className="flex-1"
  7624. disabled={updateMutation.isPending || checkingSave}
  7625. >
  7626. {checkingSave
  7627. ? t('printers.addPreflight.checking')
  7628. : updateMutation.isPending
  7629. ? t('common.saving')
  7630. : t('printers.modal.saveChanges')}
  7631. </Button>
  7632. </div>
  7633. )}
  7634. </form>
  7635. </CardContent>
  7636. </Card>
  7637. </div>
  7638. );
  7639. }
  7640. // Component to check if a printer is offline (for power dropdown)
  7641. function usePrinterOfflineStatus(printerId: number) {
  7642. const { data: status } = useQuery({
  7643. queryKey: ['printerStatus', printerId],
  7644. queryFn: () => api.getPrinterStatus(printerId),
  7645. refetchInterval: 30000,
  7646. });
  7647. return !status?.connected;
  7648. }
  7649. // Power dropdown item for an offline printer
  7650. function PowerDropdownItem({
  7651. printer,
  7652. plug,
  7653. onPowerOn,
  7654. isPowering,
  7655. }: {
  7656. printer: Printer;
  7657. plug: { id: number; name: string };
  7658. onPowerOn: (plugId: number) => void;
  7659. isPowering: boolean;
  7660. }) {
  7661. const isOffline = usePrinterOfflineStatus(printer.id);
  7662. // Fetch plug status
  7663. const { data: plugStatus } = useQuery({
  7664. queryKey: ['smartPlugStatus', plug.id],
  7665. queryFn: () => api.getSmartPlugStatus(plug.id),
  7666. refetchInterval: 10000,
  7667. });
  7668. // Only show if printer is offline
  7669. if (!isOffline) {
  7670. return null;
  7671. }
  7672. return (
  7673. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  7674. <div className="flex items-center gap-2 min-w-0">
  7675. <span className="text-sm text-white truncate">{printer.name}</span>
  7676. {plugStatus && (
  7677. <span
  7678. className={`text-xs px-1.5 py-0.5 rounded ${
  7679. plugStatus.state === 'ON'
  7680. ? 'bg-bambu-green/20 text-bambu-green'
  7681. : 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400'
  7682. }`}
  7683. >
  7684. {plugStatus.state || '?'}
  7685. </span>
  7686. )}
  7687. </div>
  7688. <button
  7689. onClick={() => onPowerOn(plug.id)}
  7690. disabled={isPowering || plugStatus?.state === 'ON'}
  7691. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  7692. plugStatus?.state === 'ON'
  7693. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  7694. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  7695. }`}
  7696. >
  7697. <Power className="w-3 h-3" />
  7698. {isPowering ? '...' : 'On'}
  7699. </button>
  7700. </div>
  7701. );
  7702. }
  7703. export function PrintersPage() {
  7704. const { t } = useTranslation();
  7705. const { resolvedMode, darkAccent, lightAccent } = useTheme();
  7706. const activeAccent = resolvedMode === 'dark' ? darkAccent : lightAccent;
  7707. const accentButtonClass = {
  7708. green: 'bg-green-500 text-white hover:bg-green-400 border-green-400/60',
  7709. teal: 'bg-teal-500 text-white hover:bg-teal-400 border-teal-400/60',
  7710. blue: 'bg-blue-500 text-white hover:bg-blue-400 border-blue-400/60',
  7711. orange: 'bg-orange-500 text-white hover:bg-orange-400 border-orange-400/60',
  7712. purple: 'bg-purple-500 text-white hover:bg-purple-400 border-purple-400/60',
  7713. red: 'bg-red-500 text-white hover:bg-red-400 border-red-400/60',
  7714. }[activeAccent];
  7715. const [showAddModal, setShowAddModal] = useState(false);
  7716. const [hideDisconnected, setHideDisconnected] = useState(() => {
  7717. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  7718. });
  7719. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  7720. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  7721. const [sortBy, setSortBy] = useState<SortOption>(() => {
  7722. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  7723. });
  7724. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  7725. return localStorage.getItem('printerSortAsc') !== 'false';
  7726. });
  7727. // Card size: 1=small, 2=medium, 3=large, 4=xl
  7728. const [cardSize, setCardSize] = useState<number>(() => {
  7729. const saved = localStorage.getItem('printerCardSize');
  7730. return saved ? parseInt(saved, 10) : 2; // Default to medium
  7731. });
  7732. // Page view: 'cards' = printer cards (default), 'camwall' = grid of live camera tiles
  7733. const [pageView, setPageView] = useState<'cards' | 'camwall'>(() => {
  7734. return localStorage.getItem('printerPageView') === 'camwall' ? 'camwall' : 'cards';
  7735. });
  7736. // Cam-wall settings — per-user, no backend write (a Pi 4 install caps the
  7737. // live count lower than a NUC; default 4 is the documented Pi 4 ceiling).
  7738. const [camWallMaxLive, setCamWallMaxLive] = useState<number>(() => {
  7739. const saved = parseInt(localStorage.getItem('camWallMaxLive') || '', 10);
  7740. return Number.isFinite(saved) && saved > 0 ? saved : 4;
  7741. });
  7742. const [camWallSnapshotSec, setCamWallSnapshotSec] = useState<number>(() => {
  7743. const saved = parseInt(localStorage.getItem('camWallSnapshotSec') || '', 10);
  7744. return Number.isFinite(saved) && saved > 0 ? saved : 8;
  7745. });
  7746. // 'off' hides the printer-state overlay; 'compact' shows only a state chip;
  7747. // 'full' adds progress, layer, and time-left on printing/paused tiles.
  7748. // Defaulting to 'full' because the cards already show this info — users who
  7749. // pick cam-wall view still want to glance the same details without flipping.
  7750. const [camWallStatusMode, setCamWallStatusMode] = useState<'off' | 'compact' | 'full'>(() => {
  7751. const saved = localStorage.getItem('camWallStatusMode');
  7752. return saved === 'off' || saved === 'compact' || saved === 'full' ? saved : 'full';
  7753. });
  7754. // Derive viewMode from cardSize: S=compact, M/L/XL=expanded
  7755. const viewMode: ViewMode = cardSize === 1 ? 'compact' : 'expanded';
  7756. const [compactDrilldownPrinterId, setCompactDrilldownPrinterId] = useState<number | null>(null);
  7757. const scrollPrinterIntoView = useCallback((printerId: number) => {
  7758. requestAnimationFrame(() => {
  7759. requestAnimationFrame(() => {
  7760. const card = document.getElementById(`printer-card-${printerId}`);
  7761. if (!card) return;
  7762. const fixedHeaderHeight = document.querySelector('header')?.getBoundingClientRect().height ?? 56;
  7763. const top = card.getBoundingClientRect().top + window.scrollY - fixedHeaderHeight - 16;
  7764. window.scrollTo({
  7765. top: Math.max(0, top),
  7766. behavior: 'smooth',
  7767. });
  7768. });
  7769. });
  7770. }, []);
  7771. const openCompactCard = useCallback((printerId: number) => {
  7772. setCompactDrilldownPrinterId(printerId);
  7773. setCardSize(2);
  7774. localStorage.setItem('printerCardSize', '2');
  7775. scrollPrinterIntoView(printerId);
  7776. }, [scrollPrinterIntoView]);
  7777. const returnToCompactCards = useCallback(() => {
  7778. const printerId = compactDrilldownPrinterId;
  7779. setCompactDrilldownPrinterId(null);
  7780. setCardSize(1);
  7781. localStorage.setItem('printerCardSize', '1');
  7782. if (printerId != null) {
  7783. scrollPrinterIntoView(printerId);
  7784. }
  7785. }, [compactDrilldownPrinterId, scrollPrinterIntoView]);
  7786. const [search, setSearch] = useState('');
  7787. // Both filters persist like every other preference on this page (#2833).
  7788. // `search` deliberately does not: a box that silently refills itself on
  7789. // return is more surprising than a dropdown that remembers.
  7790. const [statusFilter, setStatusFilter] = useState<string>(() => {
  7791. // Validated on read: a value the dropdown no longer offers would filter
  7792. // every printer out, and nothing would explain why.
  7793. const saved = localStorage.getItem('printerStatusFilter');
  7794. return isKnownStatusFilter(saved) ? (saved as string) : 'all';
  7795. });
  7796. const [locationFilter, setLocationFilter] = useState<string>(
  7797. () => localStorage.getItem('printerLocationFilter') || 'all'
  7798. );
  7799. const [statusCacheVersion, setStatusCacheVersion] = useState(0);
  7800. const [collapsedSections, setCollapsedSections] = useState<Record<string, boolean>>(() => {
  7801. try {
  7802. const saved = localStorage.getItem('printerCollapsedSections');
  7803. return saved ? JSON.parse(saved) : {};
  7804. } catch { return {}; }
  7805. });
  7806. const queryClient = useQueryClient();
  7807. const { showToast } = useToast();
  7808. const { hasPermission } = useAuth();
  7809. // Embedded camera viewer state - supports multiple simultaneous viewers
  7810. // Persisted to localStorage so cameras reopen after navigation
  7811. const [embeddedCameraPrinters, setEmbeddedCameraPrinters] = useState<Map<number, { id: number; name: string }>>(() => {
  7812. // Initialize from localStorage if camera_view_mode is embedded
  7813. const saved = localStorage.getItem('openEmbeddedCameras');
  7814. if (saved) {
  7815. try {
  7816. const cameras = JSON.parse(saved) as Array<{ id: number; name: string }>;
  7817. return new Map(cameras.map(c => [c.id, c]));
  7818. } catch {
  7819. return new Map();
  7820. }
  7821. }
  7822. return new Map();
  7823. });
  7824. // Persist open cameras to localStorage when they change
  7825. useEffect(() => {
  7826. const cameras = Array.from(embeddedCameraPrinters.values());
  7827. if (cameras.length > 0) {
  7828. localStorage.setItem('openEmbeddedCameras', JSON.stringify(cameras));
  7829. } else {
  7830. localStorage.removeItem('openEmbeddedCameras');
  7831. }
  7832. }, [embeddedCameraPrinters]);
  7833. const { data: printers, isLoading } = useQuery({
  7834. queryKey: ['printers'],
  7835. queryFn: api.getPrinters,
  7836. });
  7837. // Fetch the UI-rendering subset of settings. Uses /ui-preferences (not /settings)
  7838. // so users with printers:read but no settings:read still get the values needed
  7839. // to render the clear-plate button, drying presets, AMS thresholds, etc. (#1293).
  7840. const { data: settings } = useQuery({
  7841. queryKey: ['ui-preferences'],
  7842. queryFn: api.getUiPreferences,
  7843. });
  7844. // Parse user-configured temperature/fan presets once, with defensive fallback
  7845. // to built-in defaults on parse failure (validators on the backend already
  7846. // reject malformed writes, so this is just forward-compat).
  7847. const effectiveNozzleTempPresets = useMemo(
  7848. () => parsePresetTriple(settings?.nozzle_temp_presets, NOZZLE_TEMP_DEFAULTS, 0, 320),
  7849. [settings?.nozzle_temp_presets],
  7850. );
  7851. const effectiveBedTempPresets = useMemo(
  7852. () => parsePresetTriple(settings?.bed_temp_presets, BED_TEMP_DEFAULTS, 0, 140),
  7853. [settings?.bed_temp_presets],
  7854. );
  7855. const effectiveChamberTempPresets = useMemo(
  7856. () => parsePresetTriple(settings?.chamber_temp_presets, CHAMBER_TEMP_DEFAULTS, 0, MAX_CHAMBER_TEMP_C),
  7857. [settings?.chamber_temp_presets],
  7858. );
  7859. const effectiveFanSpeedPresets = useMemo(
  7860. () => parsePresetTriple(settings?.fan_speed_presets, FAN_SPEED_DEFAULTS, 0, 100),
  7861. [settings?.fan_speed_presets],
  7862. );
  7863. // Compute drying presets: user-configured (from settings) merged over built-in defaults
  7864. const effectiveDryingPresets = useMemo(() => {
  7865. if (settings?.drying_presets) {
  7866. try {
  7867. const userPresets = JSON.parse(settings.drying_presets);
  7868. if (typeof userPresets === 'object' && userPresets !== null && Object.keys(userPresets).length > 0) {
  7869. return { ...DRYING_PRESETS, ...userPresets };
  7870. }
  7871. } catch { /* ignore parse errors, use defaults */ }
  7872. }
  7873. return DRYING_PRESETS;
  7874. }, [settings?.drying_presets]);
  7875. // Close embedded cameras if mode changes to 'window'
  7876. useEffect(() => {
  7877. if (settings?.camera_view_mode === 'window' && embeddedCameraPrinters.size > 0) {
  7878. setEmbeddedCameraPrinters(new Map());
  7879. }
  7880. }, [settings?.camera_view_mode, embeddedCameraPrinters.size]);
  7881. // Fetch all smart plugs to know which printers have them
  7882. const { data: smartPlugs } = useQuery({
  7883. queryKey: ['smart-plugs'],
  7884. queryFn: api.getSmartPlugs,
  7885. });
  7886. // Fetch maintenance overview for all printers to show badges
  7887. const { data: maintenanceOverview } = useQuery({
  7888. queryKey: ['maintenanceOverview'],
  7889. queryFn: api.getMaintenanceOverview,
  7890. staleTime: 60 * 1000, // 1 minute
  7891. });
  7892. // Live AI failure detection state for the card badges (#1546). Matches the
  7893. // 10s refetch of the Failure Detection settings panel.
  7894. const { data: obicoPrinterStatus } = useQuery({
  7895. queryKey: ['obico-printer-status'],
  7896. queryFn: api.getObicoPrinterStatus,
  7897. refetchInterval: 10000,
  7898. });
  7899. // Badge visibility: detection enabled AND this printer in the monitored set
  7900. // (monitored_printers null = all). Live per-print state is passed separately.
  7901. const isAiMonitored = useCallback(
  7902. (printerId: number) =>
  7903. obicoPrinterStatus?.enabled === true &&
  7904. (obicoPrinterStatus.monitored_printers === null || obicoPrinterStatus.monitored_printers.includes(printerId)),
  7905. [obicoPrinterStatus],
  7906. );
  7907. // Fetch Spoolman status to enable link spool feature
  7908. const { data: spoolmanStatus } = useQuery({
  7909. queryKey: ['spoolman-status'],
  7910. queryFn: api.getSpoolmanStatus,
  7911. staleTime: 60 * 1000, // 1 minute
  7912. });
  7913. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  7914. // Fetch Spoolman settings to get sync mode
  7915. const { data: spoolmanSettings } = useQuery({
  7916. queryKey: ['spoolman-settings'],
  7917. queryFn: api.getSpoolmanSettings,
  7918. enabled: !!spoolmanEnabled,
  7919. staleTime: 60 * 1000, // 1 minute
  7920. });
  7921. const spoolmanSyncMode = spoolmanSettings?.spoolman_sync_mode;
  7922. // Fetch unlinked spools to know if link button should be enabled
  7923. const { data: unlinkedSpools } = useQuery({
  7924. queryKey: ['unlinked-spools'],
  7925. queryFn: api.getUnlinkedSpools,
  7926. enabled: !!spoolmanEnabled,
  7927. staleTime: 30 * 1000, // 30 seconds
  7928. });
  7929. const hasUnlinkedSpools = unlinkedSpools && unlinkedSpools.length > 0;
  7930. // Fetch linked spools map (tag -> spool_id) to know which spools are already in Spoolman
  7931. const { data: linkedSpoolsData } = useQuery({
  7932. queryKey: ['linked-spools'],
  7933. queryFn: api.getLinkedSpools,
  7934. enabled: !!spoolmanEnabled,
  7935. staleTime: 30 * 1000, // 30 seconds
  7936. });
  7937. const linkedSpools = linkedSpoolsData?.linked;
  7938. // Fetch spool assignments for inventory feature
  7939. const { data: spoolAssignments } = useQuery({
  7940. queryKey: ['spool-assignments'],
  7941. queryFn: () => api.getAssignments(),
  7942. enabled: hasPermission('inventory:view_assignments'),
  7943. staleTime: 30 * 1000,
  7944. });
  7945. const unassignMutation = useMutation({
  7946. mutationFn: ({ printerId, amsId, trayId }: { printerId: number; amsId: number; trayId: number }) =>
  7947. api.unassignSpool(printerId, amsId, trayId),
  7948. onSuccess: () => {
  7949. queryClient.invalidateQueries({ queryKey: ['spool-assignments'] });
  7950. },
  7951. });
  7952. const { data: spoolmanSpools, isLoading: spoolmanSpoolsLoading } = useQuery({
  7953. queryKey: ['spoolman-inventory-spools'],
  7954. queryFn: () => api.getSpoolmanInventorySpools(false),
  7955. enabled: !!spoolmanEnabled,
  7956. staleTime: 30 * 1000,
  7957. });
  7958. const { data: spoolmanSlotAssignments, isLoading: spoolmanAssignmentsLoading } = useQuery({
  7959. queryKey: ['spoolman-slot-assignments'],
  7960. queryFn: () => api.getSpoolmanSlotAssignments(),
  7961. enabled: !!spoolmanEnabled,
  7962. staleTime: 30 * 1000,
  7963. });
  7964. const unassignSpoolmanMutation = useMutation({
  7965. mutationFn: (spoolmanSpoolId: number) => api.unassignSpoolmanSlot(spoolmanSpoolId),
  7966. onSuccess: () => {
  7967. queryClient.invalidateQueries({ queryKey: ['spoolman-inventory-spools'] });
  7968. queryClient.invalidateQueries({ queryKey: ['spoolman-slot-assignments'] });
  7969. },
  7970. });
  7971. // Helper to find assignment for a specific slot
  7972. const getAssignment = (printerId: number, amsId: number | string, trayId: number | string): SpoolAssignment | undefined => {
  7973. return spoolAssignments?.find(
  7974. (a) => a.printer_id === printerId && a.ams_id === Number(amsId) && a.tray_id === Number(trayId)
  7975. );
  7976. };
  7977. // Create a map of printer_id -> maintenance info for quick lookup
  7978. const maintenanceByPrinter = maintenanceOverview?.reduce(
  7979. (acc, overview) => {
  7980. acc[overview.printer_id] = {
  7981. due_count: overview.due_count,
  7982. warning_count: overview.warning_count,
  7983. total_print_hours: overview.total_print_hours,
  7984. };
  7985. return acc;
  7986. },
  7987. {} as Record<number, PrinterMaintenanceInfo>
  7988. ) || {};
  7989. // Create a map of printer_id -> smart plug
  7990. const smartPlugByPrinter = smartPlugs?.reduce(
  7991. (acc, plug) => {
  7992. if (plug.printer_id) {
  7993. acc[plug.printer_id] = plug;
  7994. }
  7995. return acc;
  7996. },
  7997. {} as Record<number, typeof smartPlugs[0]>
  7998. ) || {};
  7999. const addMutation = useMutation({
  8000. mutationFn: api.createPrinter,
  8001. onSuccess: () => {
  8002. queryClient.invalidateQueries({ queryKey: ['printers'] });
  8003. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  8004. setShowAddModal(false);
  8005. },
  8006. onError: (error: Error) => {
  8007. // Localized message when the backend returns a stable error code;
  8008. // the raw message is an English fallback for non-UI clients.
  8009. if (error instanceof ApiError && error.code === 'printer_connection_failed') {
  8010. showToast(t('printers.toast.connectionFailedNotAdded'), 'error');
  8011. return;
  8012. }
  8013. showToast(error.message || t('printers.toast.failedToAdd'), 'error');
  8014. },
  8015. });
  8016. const powerOnMutation = useMutation({
  8017. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  8018. onSuccess: () => {
  8019. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  8020. setPoweringOn(null);
  8021. },
  8022. onError: () => {
  8023. setPoweringOn(null);
  8024. },
  8025. });
  8026. // Bulk selection state
  8027. const [selectedPrinterIds, setSelectedPrinterIds] = useState<Set<number>>(new Set());
  8028. const [isSelectionMode, setIsSelectionMode] = useState(false);
  8029. const [bulkConfirmAction, setBulkConfirmAction] = useState<'stop' | 'pause' | 'clearPlate' | null>(null);
  8030. const [bulkActionPending, setBulkActionPending] = useState(false);
  8031. const selectionMode = isSelectionMode || selectedPrinterIds.size > 0;
  8032. const toggleSelect = useCallback((id: number) => {
  8033. setSelectedPrinterIds(prev => {
  8034. const next = new Set(prev);
  8035. if (next.has(id)) next.delete(id);
  8036. else next.add(id);
  8037. return next;
  8038. });
  8039. }, []);
  8040. const clearSelection = useCallback(() => {
  8041. setSelectedPrinterIds(new Set());
  8042. setIsSelectionMode(false);
  8043. }, []);
  8044. // Escape key exits selection mode
  8045. useEffect(() => {
  8046. const handleKeyDown = (e: KeyboardEvent) => {
  8047. if (e.key === 'Escape' && selectionMode) {
  8048. clearSelection();
  8049. }
  8050. };
  8051. window.addEventListener('keydown', handleKeyDown);
  8052. return () => window.removeEventListener('keydown', handleKeyDown);
  8053. }, [selectionMode, clearSelection]);
  8054. const executeBulkAction = useCallback(async (action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8055. setBulkActionPending(true);
  8056. const ids = Array.from(selectedPrinterIds);
  8057. // Filter to only applicable printers based on cached state
  8058. const applicableIds = ids.filter(id => {
  8059. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', id]);
  8060. if (!status?.connected) return false;
  8061. switch (action) {
  8062. case 'stop': return status.state === 'RUNNING' || status.state === 'PAUSE';
  8063. case 'pause': return status.state === 'RUNNING';
  8064. case 'resume': return status.state === 'PAUSE';
  8065. case 'clearPlate': return !!(status as { awaiting_plate_clear?: boolean }).awaiting_plate_clear;
  8066. case 'clearHMS': return status.hms_errors && filterKnownHMSErrors(status.hms_errors).length > 0;
  8067. default: return false;
  8068. }
  8069. });
  8070. if (applicableIds.length === 0) {
  8071. showToast(t('printers.bulk.noneApplicable'), 'error');
  8072. setBulkActionPending(false);
  8073. setBulkConfirmAction(null);
  8074. return;
  8075. }
  8076. const apiCall = {
  8077. stop: api.stopPrint,
  8078. pause: api.pausePrint,
  8079. resume: api.resumePrint,
  8080. clearPlate: api.clearPlate,
  8081. clearHMS: api.clearHMSErrors,
  8082. }[action];
  8083. const results = await Promise.allSettled(
  8084. applicableIds.map(id => apiCall(id))
  8085. );
  8086. const succeeded = results.filter(r => r.status === 'fulfilled').length;
  8087. const failed = results.filter(r => r.status === 'rejected').length;
  8088. if (failed === 0) {
  8089. showToast(t('printers.bulk.success', { action: t(`printers.bulk.actions.${action}`), count: succeeded }));
  8090. } else {
  8091. showToast(t('printers.bulk.partial', { succeeded, failed }), 'error');
  8092. }
  8093. // Invalidate status queries for affected printers
  8094. applicableIds.forEach(id => {
  8095. queryClient.invalidateQueries({ queryKey: ['printerStatus', id] });
  8096. });
  8097. setBulkActionPending(false);
  8098. setBulkConfirmAction(null);
  8099. }, [selectedPrinterIds, queryClient, showToast, t]);
  8100. const handleBulkAction = useCallback((action: 'stop' | 'pause' | 'resume' | 'clearPlate' | 'clearHMS') => {
  8101. // Actions that need confirmation
  8102. if (action === 'stop' || action === 'pause' || action === 'clearPlate') {
  8103. setBulkConfirmAction(action);
  8104. } else {
  8105. executeBulkAction(action);
  8106. }
  8107. }, [executeBulkAction]);
  8108. const toggleHideDisconnected = () => {
  8109. const newValue = !hideDisconnected;
  8110. setHideDisconnected(newValue);
  8111. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  8112. };
  8113. const handleSortChange = (newSort: SortOption) => {
  8114. setSortBy(newSort);
  8115. localStorage.setItem('printerSortBy', newSort);
  8116. };
  8117. const handleStatusFilterChange = (value: string) => {
  8118. setStatusFilter(value);
  8119. localStorage.setItem('printerStatusFilter', value);
  8120. };
  8121. const handleLocationFilterChange = (value: string) => {
  8122. setLocationFilter(value);
  8123. localStorage.setItem('printerLocationFilter', value);
  8124. };
  8125. const toggleSortDirection = () => {
  8126. const newAsc = !sortAsc;
  8127. setSortAsc(newAsc);
  8128. localStorage.setItem('printerSortAsc', String(newAsc));
  8129. };
  8130. // Grid classes based on card size (1=small, 2=medium, 3=large, 4=xl)
  8131. const getGridClasses = () => {
  8132. switch (cardSize) {
  8133. 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
  8134. case 2: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3'; // M: medium cards
  8135. case 3: return 'grid-cols-1 lg:grid-cols-2'; // L: large cards, 2 columns max
  8136. case 4: return 'grid-cols-1'; // XL: single column, full width
  8137. default: return 'grid-cols-1 md:grid-cols-2 xl:grid-cols-3';
  8138. }
  8139. };
  8140. const cardSizeLabels = ['S', 'M', 'L', 'XL'];
  8141. // Increment version counter whenever a printer status cache entry is updated so
  8142. // filteredPrinters re-computes reactively on WebSocket-driven status changes.
  8143. useEffect(() => {
  8144. const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
  8145. if (
  8146. event.type === 'updated' &&
  8147. Array.isArray(event.query.queryKey) &&
  8148. event.query.queryKey[0] === 'printerStatus'
  8149. ) {
  8150. setStatusCacheVersion(v => v + 1);
  8151. }
  8152. });
  8153. return unsubscribe;
  8154. }, [queryClient]);
  8155. // Filter printers by search term, status, and location
  8156. const filteredPrinters = useMemo(() => {
  8157. if (!printers) return [];
  8158. let result = printers;
  8159. // Text search
  8160. if (search.trim()) {
  8161. const q = search.trim().toLowerCase();
  8162. result = result.filter(p =>
  8163. p.name.toLowerCase().includes(q) ||
  8164. (p.model || '').toLowerCase().includes(q) ||
  8165. (p.location || '').toLowerCase().includes(q) ||
  8166. (p.serial_number || '').toLowerCase().includes(q)
  8167. );
  8168. }
  8169. // Location filter
  8170. if (locationFilter !== 'all') {
  8171. result = result.filter(p => (p.location || '') === locationFilter);
  8172. }
  8173. // Status filter
  8174. if (statusFilter !== 'all') {
  8175. result = result.filter(p => {
  8176. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8177. if (!status?.connected) return statusFilter === 'offline';
  8178. const hmsErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  8179. switch (statusFilter) {
  8180. case 'printing': return status.state === 'RUNNING';
  8181. case 'paused': return status.state === 'PAUSE';
  8182. case 'finished': return status.state === 'FINISH';
  8183. case 'error': return status.state === 'FAILED' || hmsErrors.length > 0;
  8184. case 'idle': return status.state !== 'RUNNING' && status.state !== 'PAUSE' && status.state !== 'FINISH' && status.state !== 'FAILED' && hmsErrors.length === 0;
  8185. case 'offline': return false; // Connected printers are never offline
  8186. default: return true;
  8187. }
  8188. });
  8189. }
  8190. return result;
  8191. // eslint-disable-next-line react-hooks/exhaustive-deps -- statusCacheVersion is intentional: it forces recompute when WebSocket updates printer status cache
  8192. }, [printers, search, statusFilter, locationFilter, queryClient, statusCacheVersion]);
  8193. // Derive unique locations for the location filter dropdown
  8194. const availableLocations = useMemo(() => {
  8195. if (!printers) return [];
  8196. return [...new Set(printers.map(p => p.location || '').filter(Boolean))].sort();
  8197. }, [printers]);
  8198. // A saved location can outlive what it matched -- renamed, cleared, or the
  8199. // only printer that had it deleted. The dropdown is rendered only while some
  8200. // printer has a location, so a stale one would hide every printer *and* the
  8201. // control to undo it, leaving an empty page and no way back (#2833).
  8202. // Deliberately waits for `printers`: it is undefined while the query is in
  8203. // flight, and acting on the empty list that produces would throw the saved
  8204. // filter away every time the page loads.
  8205. useEffect(() => {
  8206. if (!printers || locationFilter === 'all' || availableLocations.includes(locationFilter)) return;
  8207. setLocationFilter('all');
  8208. localStorage.setItem('printerLocationFilter', 'all');
  8209. }, [printers, availableLocations, locationFilter]);
  8210. // Sort printers based on selected option
  8211. const sortedPrinters = useMemo(() => {
  8212. const sorted = [...filteredPrinters];
  8213. switch (sortBy) {
  8214. case 'name':
  8215. sorted.sort((a, b) => a.name.localeCompare(b.name));
  8216. break;
  8217. case 'model':
  8218. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  8219. break;
  8220. case 'location':
  8221. // Sort by location, with ungrouped printers last
  8222. sorted.sort((a, b) => {
  8223. const locA = a.location || '';
  8224. const locB = b.location || '';
  8225. if (!locA && locB) return 1;
  8226. if (locA && !locB) return -1;
  8227. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  8228. });
  8229. break;
  8230. case 'status':
  8231. // Sort by status: HMS errors > printing > idle > offline
  8232. sorted.sort((a, b) => {
  8233. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', a.id]);
  8234. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', b.id]);
  8235. const getPriority = (s: typeof statusA) => {
  8236. if (!s?.connected) return 3; // offline
  8237. const hmsErrors = s.hms_errors ? filterKnownHMSErrors(s.hms_errors) : [];
  8238. if (hmsErrors.length > 0) return 0; // HMS errors - top priority
  8239. if (s.state === 'RUNNING') return 1; // printing
  8240. return 2; // idle
  8241. };
  8242. return getPriority(statusA) - getPriority(statusB);
  8243. });
  8244. break;
  8245. case 'eta':
  8246. sorted.sort((a, b) => {
  8247. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', a.id]);
  8248. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null; remaining_time: number | null }>(['printerStatus', b.id]);
  8249. const tier = (s: typeof statusA) => {
  8250. if (!s?.connected) return 3; // offline last
  8251. if (s.state === 'RUNNING' && s.remaining_time != null && s.remaining_time > 0) return 0; // printing with ETA
  8252. if (s.state === 'RUNNING') return 1; // printing without ETA
  8253. return 2; // idle
  8254. };
  8255. const ta = tier(statusA);
  8256. const tb = tier(statusB);
  8257. if (ta !== tb) return ta - tb;
  8258. if (ta === 0) {
  8259. const diff = (statusA!.remaining_time ?? 0) - (statusB!.remaining_time ?? 0);
  8260. if (diff !== 0) return diff;
  8261. }
  8262. return a.name.localeCompare(b.name);
  8263. });
  8264. break;
  8265. }
  8266. // Apply ascending/descending
  8267. if (!sortAsc) {
  8268. sorted.reverse();
  8269. }
  8270. return sorted;
  8271. }, [filteredPrinters, sortBy, sortAsc, queryClient]);
  8272. const selectAll = useCallback(() => {
  8273. setSelectedPrinterIds(new Set(sortedPrinters.map(p => p.id)));
  8274. setIsSelectionMode(true);
  8275. }, [sortedPrinters]);
  8276. const selectByState = useCallback((state: PrinterState) => {
  8277. setSelectedPrinterIds(prev => {
  8278. const next = new Set(prev);
  8279. sortedPrinters.forEach(p => {
  8280. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', p.id]);
  8281. if (classifyPrinterStatus(status) === state) next.add(p.id);
  8282. });
  8283. return next;
  8284. });
  8285. setIsSelectionMode(true);
  8286. }, [sortedPrinters, queryClient]);
  8287. const selectByLocation = useCallback((location: string) => {
  8288. setSelectedPrinterIds(prev => {
  8289. const next = new Set(prev);
  8290. sortedPrinters.filter(p => (p.location || '') === location).forEach(p => next.add(p.id));
  8291. return next;
  8292. });
  8293. setIsSelectionMode(true);
  8294. }, [sortedPrinters]);
  8295. const selectByModel = useCallback((model: string) => {
  8296. setSelectedPrinterIds(prev => {
  8297. const next = new Set(prev);
  8298. sortedPrinters.filter(p => (p.model || 'Unknown') === model).forEach(p => next.add(p.id));
  8299. return next;
  8300. });
  8301. setIsSelectionMode(true);
  8302. }, [sortedPrinters]);
  8303. const toggleSectionCollapse = useCallback((key: string) => {
  8304. setCollapsedSections(prev => {
  8305. const next = { ...prev, [key]: !prev[key] };
  8306. try { localStorage.setItem('printerCollapsedSections', JSON.stringify(next)); } catch { /* quota exceeded / private mode */ }
  8307. return next;
  8308. });
  8309. }, []);
  8310. // Group printers when sorted by location, status, or model
  8311. const groupedPrinters = useMemo(() => {
  8312. if (sortBy === 'name' || sortBy === 'eta') return null;
  8313. const groups: Record<string, typeof sortedPrinters> = {};
  8314. if (sortBy === 'location') {
  8315. sortedPrinters.forEach(printer => {
  8316. const location = printer.location || 'Ungrouped';
  8317. if (!groups[location]) groups[location] = [];
  8318. groups[location].push(printer);
  8319. });
  8320. } else if (sortBy === 'model') {
  8321. sortedPrinters.forEach(printer => {
  8322. const model = printer.model || 'Unknown';
  8323. if (!groups[model]) groups[model] = [];
  8324. groups[model].push(printer);
  8325. });
  8326. } else if (sortBy === 'status') {
  8327. sortedPrinters.forEach(printer => {
  8328. const status = queryClient.getQueryData<{ connected: boolean; state: string | null; hms_errors?: HMSError[] }>(['printerStatus', printer.id]);
  8329. const group = classifyPrinterStatus(status);
  8330. if (!groups[group]) groups[group] = [];
  8331. groups[group].push(printer);
  8332. });
  8333. }
  8334. return groups;
  8335. // 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
  8336. }, [sortBy, sortedPrinters, queryClient, statusCacheVersion]);
  8337. const toolbarRef = useRef<HTMLDivElement>(null);
  8338. const expandedToolbarControlsRef = useRef<HTMLDivElement>(null);
  8339. const expandedToolbarWidthRef = useRef(0);
  8340. const [compactToolbar, setCompactToolbar] = useState(false);
  8341. const measureToolbar = useCallback(() => {
  8342. const toolbar = toolbarRef.current;
  8343. if (!toolbar) return;
  8344. const measuredControlsWidth = expandedToolbarControlsRef.current?.offsetWidth;
  8345. if (measuredControlsWidth) {
  8346. expandedToolbarWidthRef.current = measuredControlsWidth;
  8347. }
  8348. const searchMinimumWidth = 220;
  8349. const gapWidth = 8;
  8350. const shouldCompact = expandedToolbarWidthRef.current > 0 && toolbar.clientWidth < expandedToolbarWidthRef.current + searchMinimumWidth + gapWidth;
  8351. setCompactToolbar(prev => (prev === shouldCompact ? prev : shouldCompact));
  8352. }, []);
  8353. const smartPlugCount = Object.keys(smartPlugByPrinter).length;
  8354. useLayoutEffect(() => {
  8355. measureToolbar();
  8356. const toolbar = toolbarRef.current;
  8357. if (!toolbar) return;
  8358. if (typeof ResizeObserver === 'undefined') {
  8359. window.addEventListener('resize', measureToolbar);
  8360. return () => window.removeEventListener('resize', measureToolbar);
  8361. }
  8362. const resizeObserver = new ResizeObserver(() => measureToolbar());
  8363. resizeObserver.observe(toolbar);
  8364. window.addEventListener('resize', measureToolbar);
  8365. return () => {
  8366. resizeObserver.disconnect();
  8367. window.removeEventListener('resize', measureToolbar);
  8368. };
  8369. }, [
  8370. measureToolbar,
  8371. printers?.length,
  8372. availableLocations.length,
  8373. hideDisconnected,
  8374. smartPlugCount,
  8375. ]);
  8376. const renderFilterControls = (inMenu = false) => (
  8377. <>
  8378. {/* Status filter */}
  8379. {printers && printers.length > 0 && (
  8380. <ToolbarDropdown
  8381. value={statusFilter}
  8382. onChange={handleStatusFilterChange}
  8383. fullWidth={inMenu}
  8384. options={STATUS_FILTER_OPTIONS.map(option => ({ value: option.value, label: t(option.labelKey) }))}
  8385. />
  8386. )}
  8387. {/* Location filter — only shown when at least one printer has a location */}
  8388. {printers && printers.length > 0 && availableLocations.length > 0 && (
  8389. <ToolbarDropdown
  8390. value={locationFilter}
  8391. onChange={handleLocationFilterChange}
  8392. fullWidth={inMenu}
  8393. options={[
  8394. { value: 'all', label: t('printers.filter.allLocations') },
  8395. ...availableLocations.map(loc => ({ value: loc, label: loc })),
  8396. ]}
  8397. />
  8398. )}
  8399. <button
  8400. type="button"
  8401. onClick={toggleHideDisconnected}
  8402. aria-pressed={hideDisconnected}
  8403. className={`h-8 px-2 rounded-lg border text-sm font-medium transition-colors ${inMenu ? 'w-full' : ''} ${
  8404. hideDisconnected
  8405. ? 'bg-bambu-green border-bambu-green text-white'
  8406. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8407. }`}
  8408. >
  8409. {t('printers.hideOffline')}
  8410. </button>
  8411. </>
  8412. );
  8413. const renderViewControls = (inMenu = false) => (
  8414. <>
  8415. {/* Sort dropdown */}
  8416. <div className={`flex items-center gap-1 ${inMenu ? 'w-full' : ''}`}>
  8417. <ToolbarDropdown<SortOption>
  8418. value={sortBy}
  8419. onChange={handleSortChange}
  8420. fullWidth={inMenu}
  8421. options={[
  8422. { value: 'name', label: t('printers.sort.name') },
  8423. { value: 'status', label: t('printers.sort.status') },
  8424. { value: 'model', label: t('printers.sort.model') },
  8425. { value: 'location', label: t('printers.sort.location') },
  8426. { value: 'eta', label: t('printers.sort.eta') },
  8427. ]}
  8428. />
  8429. <button
  8430. onClick={toggleSortDirection}
  8431. 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"
  8432. title={sortAsc ? t('printers.sort.descending') : t('printers.sort.ascending')}
  8433. >
  8434. {sortAsc ? (
  8435. <ArrowUp className="w-4 h-4 text-white" />
  8436. ) : (
  8437. <ArrowDown className="w-4 h-4 text-white" />
  8438. )}
  8439. </button>
  8440. </div>
  8441. {/* Page view toggle: Cards / Cam Wall */}
  8442. <div className={`flex h-8 items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary ${inMenu ? 'w-full' : ''}`}>
  8443. <button
  8444. type="button"
  8445. onClick={() => {
  8446. setPageView('cards');
  8447. localStorage.setItem('printerPageView', 'cards');
  8448. }}
  8449. className={`flex h-full items-center gap-1 rounded-l-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8450. pageView === 'cards' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8451. }`}
  8452. title={t('printers.pageView.cards')}
  8453. aria-pressed={pageView === 'cards'}
  8454. >
  8455. <LayoutGrid className="w-3.5 h-3.5" />
  8456. {inMenu && <span>{t('printers.pageView.cards')}</span>}
  8457. </button>
  8458. <button
  8459. type="button"
  8460. onClick={() => {
  8461. setPageView('camwall');
  8462. localStorage.setItem('printerPageView', 'camwall');
  8463. }}
  8464. className={`flex h-full items-center gap-1 rounded-r-lg px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1 justify-center' : ''} ${
  8465. pageView === 'camwall' ? 'bg-bambu-green text-white' : 'text-white hover:bg-bambu-dark-tertiary'
  8466. }`}
  8467. title={t('printers.pageView.camWall')}
  8468. aria-pressed={pageView === 'camwall'}
  8469. disabled={!hasPermission('camera:view')}
  8470. >
  8471. <MonitorPlay className="w-3.5 h-3.5" />
  8472. {inMenu && <span>{t('printers.pageView.camWall')}</span>}
  8473. </button>
  8474. </div>
  8475. {/* Cam Wall on its own URL (#2531) — the linkable/bookmarkable form of the
  8476. view, and the page a kiosk token points at. Only offered once the wall
  8477. is the active view, so it doesn't compete with the toggle above. */}
  8478. {pageView === 'camwall' && hasPermission('camera:view') && (
  8479. <RouterLink
  8480. to="/camwall"
  8481. 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' : ''}`}
  8482. title={t('printers.pageView.openCamWallPage')}
  8483. >
  8484. <ExternalLink className="w-3.5 h-3.5" />
  8485. {inMenu && <span>{t('printers.pageView.openCamWallPage')}</span>}
  8486. </RouterLink>
  8487. )}
  8488. {/* Card size selector */}
  8489. <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' : ''}`}>
  8490. {cardSizeLabels.map((label, index) => {
  8491. const size = index + 1;
  8492. const isSelected = cardSize === size;
  8493. return (
  8494. <button
  8495. key={label}
  8496. onClick={() => {
  8497. setCompactDrilldownPrinterId(null);
  8498. setCardSize(size);
  8499. localStorage.setItem('printerCardSize', String(size));
  8500. }}
  8501. className={`h-full px-2 text-xs font-medium transition-colors ${inMenu ? 'flex-1' : ''} ${
  8502. index === 0 ? 'rounded-l-lg' : ''
  8503. } ${
  8504. index === cardSizeLabels.length - 1 ? 'rounded-r-lg' : ''
  8505. } ${
  8506. isSelected
  8507. ? 'bg-bambu-green text-white'
  8508. : 'text-white hover:bg-bambu-dark-tertiary'
  8509. }`}
  8510. title={label === 'S' ? t('printers.cardSize.small') : label === 'M' ? t('printers.cardSize.medium') : label === 'L' ? t('printers.cardSize.large') : t('printers.cardSize.extraLarge')}
  8511. >
  8512. {label}
  8513. </button>
  8514. );
  8515. })}
  8516. </div>
  8517. </>
  8518. );
  8519. const renderActionControls = (inMenu = false) => (
  8520. <>
  8521. {/* Bulk select toggle */}
  8522. <button
  8523. onClick={() => {
  8524. if (selectionMode) clearSelection();
  8525. else setIsSelectionMode(true);
  8526. }}
  8527. 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' : ''} ${
  8528. selectionMode
  8529. ? 'bg-bambu-green border-bambu-green text-white'
  8530. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8531. }`}
  8532. title={t('printers.bulk.select')}
  8533. disabled={!hasPermission('printers:control')}
  8534. >
  8535. <CheckSquare className="w-4 h-4" />
  8536. {inMenu && <span>{t('printers.bulk.select')}</span>}
  8537. </button>
  8538. {/* Power dropdown for offline printers with smart plugs */}
  8539. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  8540. <div className={`relative ${inMenu ? 'w-full' : ''}`}>
  8541. <button
  8542. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  8543. className={`h-8 flex items-center gap-1.5 px-2 text-sm rounded-lg border transition-colors ${
  8544. inMenu
  8545. ? 'w-full justify-between bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary hover:text-white'
  8546. : 'bg-bambu-dark border-bambu-dark-tertiary text-white hover:bg-bambu-dark-tertiary'
  8547. }`}
  8548. >
  8549. <span className="flex items-center gap-1.5">
  8550. <Power className="w-4 h-4" />
  8551. {t('printers.powerOn')}
  8552. </span>
  8553. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  8554. </button>
  8555. {showPowerDropdown && (
  8556. <>
  8557. {/* Backdrop to close dropdown */}
  8558. <div
  8559. className="fixed inset-0 z-10"
  8560. onClick={() => setShowPowerDropdown(false)}
  8561. />
  8562. <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">
  8563. <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">
  8564. {t('printers.offlinePrintersWithPlugs')}
  8565. </div>
  8566. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  8567. <PowerDropdownItem
  8568. key={printer.id}
  8569. printer={printer}
  8570. plug={smartPlugByPrinter[printer.id]}
  8571. onPowerOn={(plugId) => {
  8572. setPoweringOn(plugId);
  8573. powerOnMutation.mutate(plugId);
  8574. }}
  8575. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  8576. />
  8577. ))}
  8578. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  8579. <div className="px-3 py-2 text-sm text-bambu-gray">
  8580. No printers with smart plugs
  8581. </div>
  8582. )}
  8583. </div>
  8584. </>
  8585. )}
  8586. </div>
  8587. )}
  8588. <Button
  8589. onClick={() => setShowAddModal(true)}
  8590. disabled={!hasPermission('printers:create')}
  8591. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8592. className={`!h-8 !min-h-8 px-2 py-0 ${inMenu ? 'w-full' : ''}`}
  8593. >
  8594. <Plus className="w-4 h-4" />
  8595. {t('printers.addPrinter')}
  8596. </Button>
  8597. </>
  8598. );
  8599. return (
  8600. <div className="p-4 md:p-8">
  8601. <div className="space-y-3 mb-6">
  8602. <div>
  8603. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  8604. <PrinterIcon className="w-7 h-7 text-bambu-green" />
  8605. {t('printers.title')}
  8606. </h1>
  8607. <StatusSummaryBar printers={printers} />
  8608. </div>
  8609. <div ref={toolbarRef} className="relative flex items-center gap-2">
  8610. {/* Only show search bar when printers exist */}
  8611. {printers && printers.length > 0 && (
  8612. <div className="relative min-w-0 flex-1">
  8613. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50" />
  8614. <input
  8615. type="search"
  8616. name="printer-search"
  8617. autoComplete="off"
  8618. data-1p-ignore
  8619. data-lpignore="true"
  8620. value={search}
  8621. onChange={(e) => setSearch(e.target.value)}
  8622. placeholder={t('printers.search')}
  8623. aria-label={t('printers.search')}
  8624. 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"
  8625. />
  8626. {search && (
  8627. <button
  8628. type="button"
  8629. aria-label={t('common.clear')}
  8630. onClick={() => setSearch('')}
  8631. className="absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white"
  8632. >
  8633. <X className="w-4 h-4" />
  8634. </button>
  8635. )}
  8636. </div>
  8637. )}
  8638. <div
  8639. ref={expandedToolbarControlsRef}
  8640. aria-hidden={compactToolbar}
  8641. inert={compactToolbar}
  8642. 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`}
  8643. >
  8644. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8645. <div className="flex items-center gap-2">{renderFilterControls()}</div>
  8646. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8647. <div className="flex items-center gap-2">{renderViewControls()}</div>
  8648. <div className="h-6 w-px bg-bambu-dark-tertiary" />
  8649. <div className="flex items-center gap-2">{renderActionControls()}</div>
  8650. </div>
  8651. {compactToolbar && (
  8652. <div className="ml-auto flex items-center justify-end gap-1">
  8653. <ToolbarMenu label={t('printers.toolbar.filters', 'Filters')} icon={<Filter className="w-4 h-4" />}>
  8654. <div className="flex w-48 flex-col gap-2">{renderFilterControls(true)}</div>
  8655. </ToolbarMenu>
  8656. <ToolbarMenu label={t('printers.toolbar.view', 'View')} icon={<SlidersHorizontal className="w-4 h-4" />}>
  8657. <div className="flex w-48 flex-col gap-2">{renderViewControls(true)}</div>
  8658. </ToolbarMenu>
  8659. <ToolbarMenu label={t('printers.toolbar.actions', 'Actions')} icon={<MoreHorizontal className="w-4 h-4" />}>
  8660. <div className="flex w-48 flex-col gap-2">{renderActionControls(true)}</div>
  8661. </ToolbarMenu>
  8662. </div>
  8663. )}
  8664. </div>
  8665. </div>
  8666. {isLoading ? (
  8667. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  8668. ) : printers?.length === 0 ? (
  8669. <Card>
  8670. <CardContent className="text-center py-12">
  8671. <p className="text-bambu-gray mb-4">{t('printers.noPrintersConfigured')}</p>
  8672. <Button
  8673. onClick={() => setShowAddModal(true)}
  8674. disabled={!hasPermission('printers:create')}
  8675. title={!hasPermission('printers:create') ? t('printers.permission.noAdd') : undefined}
  8676. >
  8677. <Plus className="w-4 h-4" />
  8678. {t('printers.addPrinter')}
  8679. </Button>
  8680. </CardContent>
  8681. </Card>
  8682. ) : sortedPrinters.length === 0 && (search.trim() || statusFilter !== 'all' || locationFilter !== 'all') ? (
  8683. <Card>
  8684. <CardContent className="text-center py-12">
  8685. <p className="text-bambu-gray">{t('printers.noSearchResults')}</p>
  8686. </CardContent>
  8687. </Card>
  8688. ) : pageView === 'camwall' ? (
  8689. <CameraWall
  8690. printers={sortedPrinters}
  8691. maxLive={camWallMaxLive}
  8692. snapshotIntervalSec={camWallSnapshotSec}
  8693. onTileClick={(id, name) => {
  8694. const cameraMode = settings?.camera_view_mode || 'window';
  8695. if (cameraMode === 'embedded') {
  8696. setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }));
  8697. } else {
  8698. const saved = localStorage.getItem('cameraWindowState');
  8699. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  8700. const features = [
  8701. `width=${state.width}`,
  8702. `height=${state.height}`,
  8703. state.left !== undefined ? `left=${state.left}` : '',
  8704. state.top !== undefined ? `top=${state.top}` : '',
  8705. 'menubar=no,toolbar=no,location=no,status=no',
  8706. ].filter(Boolean).join(',');
  8707. window.open(`/camera/${id}`, `camera-${id}`, features);
  8708. }
  8709. }}
  8710. statusMode={camWallStatusMode}
  8711. onChangeMaxLive={(next) => {
  8712. setCamWallMaxLive(next);
  8713. localStorage.setItem('camWallMaxLive', String(next));
  8714. }}
  8715. onChangeSnapshotIntervalSec={(next) => {
  8716. setCamWallSnapshotSec(next);
  8717. localStorage.setItem('camWallSnapshotSec', String(next));
  8718. }}
  8719. onChangeStatusMode={(next) => {
  8720. setCamWallStatusMode(next);
  8721. localStorage.setItem('camWallStatusMode', next);
  8722. }}
  8723. />
  8724. ) : groupedPrinters ? (
  8725. /* Grouped view (location, status, or model) */
  8726. <div className="space-y-6">
  8727. {(() => {
  8728. const keys = sortBy === 'status'
  8729. ? STATUS_GROUP_ORDER.filter(k => groupedPrinters[k]?.length > 0)
  8730. : Object.keys(groupedPrinters);
  8731. // For status grouping, asc/desc flips the fixed priority order
  8732. // (asc = error→offline, desc = offline→error). This matches the
  8733. // sort-toggle behaviour for other groupings.
  8734. return (sortAsc ? keys : [...keys].reverse());
  8735. })().map((groupKey) => {
  8736. const groupPrinters = groupedPrinters[groupKey];
  8737. const collapseKey = `${sortBy}:${groupKey}`;
  8738. const isOpen = !collapsedSections[collapseKey];
  8739. const dot = sortBy === 'status'
  8740. ? STATUS_GROUP_META[groupKey]?.dot || 'bg-bambu-green'
  8741. : 'bg-bambu-green';
  8742. const label = sortBy === 'status'
  8743. ? t(STATUS_GROUP_META[groupKey]?.labelKey || groupKey)
  8744. : groupKey;
  8745. return (
  8746. <Collapsible
  8747. key={groupKey}
  8748. open={isOpen}
  8749. onToggle={() => toggleSectionCollapse(collapseKey)}
  8750. summaryClassName="py-1"
  8751. summary={
  8752. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  8753. <span className={`w-2 h-2 rounded-full ${dot}`} />
  8754. {label}
  8755. <span className="text-sm font-normal text-bambu-gray">({groupPrinters.length})</span>
  8756. {selectionMode && (
  8757. <button
  8758. onClick={(e) => {
  8759. e.stopPropagation();
  8760. if (sortBy === 'location') selectByLocation(groupKey === 'Ungrouped' ? '' : groupKey);
  8761. else if (sortBy === 'status') selectByState(groupKey as PrinterState);
  8762. else if (sortBy === 'model') selectByModel(groupKey);
  8763. }}
  8764. className="text-xs text-bambu-green hover:text-bambu-green-light transition-colors ml-1"
  8765. >
  8766. {t('printers.bulk.selectAll')}
  8767. </button>
  8768. )}
  8769. </h2>
  8770. }
  8771. >
  8772. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8773. {groupPrinters.map((printer) => (
  8774. <PrinterCard
  8775. key={printer.id}
  8776. printer={printer}
  8777. hideIfDisconnected={hideDisconnected}
  8778. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8779. viewMode={viewMode}
  8780. cardSize={cardSize}
  8781. amsThresholds={settings ? {
  8782. humidityGood: Number(settings.ams_humidity_good) || 40,
  8783. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8784. tempGood: Number(settings.ams_temp_good) || 28,
  8785. tempFair: Number(settings.ams_temp_fair) || 35,
  8786. } : undefined}
  8787. spoolmanEnabled={spoolmanEnabled}
  8788. hasUnlinkedSpools={hasUnlinkedSpools}
  8789. linkedSpools={linkedSpools}
  8790. spoolmanUrl={spoolmanStatus?.url}
  8791. spoolmanSyncMode={spoolmanSyncMode}
  8792. onGetAssignment={getAssignment}
  8793. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8794. spoolmanSpools={spoolmanSpools}
  8795. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8796. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8797. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8798. timeFormat={settings?.time_format || 'system'}
  8799. cameraViewMode={settings?.camera_view_mode || 'window'}
  8800. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8801. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8802. dryingPresets={effectiveDryingPresets}
  8803. nozzleTempPresets={effectiveNozzleTempPresets}
  8804. bedTempPresets={effectiveBedTempPresets}
  8805. chamberTempPresets={effectiveChamberTempPresets}
  8806. fanSpeedPresets={effectiveFanSpeedPresets}
  8807. requirePlateClear={settings?.require_plate_clear === true}
  8808. selectionMode={selectionMode}
  8809. isSelected={selectedPrinterIds.has(printer.id)}
  8810. onToggleSelect={toggleSelect}
  8811. onOpenCompactCard={openCompactCard}
  8812. aiDetectionEnabled={isAiMonitored(printer.id)}
  8813. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8814. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8815. />
  8816. ))}
  8817. </div>
  8818. </Collapsible>
  8819. );
  8820. })}
  8821. </div>
  8822. ) : (
  8823. /* Regular grid view */
  8824. <div className={`grid gap-4 ${cardSize >= 3 ? 'gap-6' : ''} ${getGridClasses()}`}>
  8825. {sortedPrinters.map((printer) => (
  8826. <PrinterCard
  8827. key={printer.id}
  8828. printer={printer}
  8829. hideIfDisconnected={hideDisconnected}
  8830. maintenanceInfo={maintenanceByPrinter[printer.id]}
  8831. viewMode={viewMode}
  8832. cardSize={cardSize}
  8833. spoolmanEnabled={spoolmanEnabled}
  8834. hasUnlinkedSpools={hasUnlinkedSpools}
  8835. linkedSpools={linkedSpools}
  8836. spoolmanUrl={spoolmanStatus?.url}
  8837. spoolmanSyncMode={spoolmanSyncMode}
  8838. onGetAssignment={getAssignment}
  8839. onUnassignSpool={(pid, aid, tid) => unassignMutation.mutate({ printerId: pid, amsId: aid, trayId: tid })}
  8840. spoolmanSpools={spoolmanSpools}
  8841. spoolmanSlotAssignments={spoolmanSlotAssignments}
  8842. spoolmanLoading={spoolmanSpoolsLoading || spoolmanAssignmentsLoading}
  8843. onUnassignSpoolmanSpool={(id) => unassignSpoolmanMutation.mutate(id)}
  8844. amsThresholds={settings ? {
  8845. humidityGood: Number(settings.ams_humidity_good) || 40,
  8846. humidityFair: Number(settings.ams_humidity_fair) || 60,
  8847. tempGood: Number(settings.ams_temp_good) || 28,
  8848. tempFair: Number(settings.ams_temp_fair) || 35,
  8849. } : undefined}
  8850. timeFormat={settings?.time_format || 'system'}
  8851. cameraViewMode={settings?.camera_view_mode || 'window'}
  8852. onOpenEmbeddedCamera={(id, name) => setEmbeddedCameraPrinters(prev => new Map(prev).set(id, { id, name }))}
  8853. checkPrinterFirmware={settings?.check_printer_firmware !== false}
  8854. dryingPresets={effectiveDryingPresets}
  8855. nozzleTempPresets={effectiveNozzleTempPresets}
  8856. bedTempPresets={effectiveBedTempPresets}
  8857. chamberTempPresets={effectiveChamberTempPresets}
  8858. fanSpeedPresets={effectiveFanSpeedPresets}
  8859. requirePlateClear={settings?.require_plate_clear === true}
  8860. selectionMode={selectionMode}
  8861. isSelected={selectedPrinterIds.has(printer.id)}
  8862. onToggleSelect={toggleSelect}
  8863. onOpenCompactCard={openCompactCard}
  8864. aiDetectionEnabled={isAiMonitored(printer.id)}
  8865. aiDetection={obicoPrinterStatus?.enabled ? obicoPrinterStatus.per_printer[String(printer.id)] : undefined}
  8866. aiLastError={obicoPrinterStatus?.last_error ?? null}
  8867. />
  8868. ))}
  8869. </div>
  8870. )}
  8871. {cardSize === 2 && compactDrilldownPrinterId != null && (
  8872. <button
  8873. type="button"
  8874. onClick={returnToCompactCards}
  8875. 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}`}
  8876. title={t('common.back', 'Back')}
  8877. >
  8878. <ArrowLeft className="w-4 h-4" />
  8879. {t('common.back', 'Back')}
  8880. </button>
  8881. )}
  8882. {showAddModal && (
  8883. <AddPrinterModal
  8884. onClose={() => setShowAddModal(false)}
  8885. onAdd={(data) => addMutation.mutate(data)}
  8886. existingSerials={printers?.map(p => p.serial_number) || []}
  8887. />
  8888. )}
  8889. {/* Bulk selection toolbar */}
  8890. {selectionMode && printers && (
  8891. <BulkPrinterToolbar
  8892. selectedIds={selectedPrinterIds}
  8893. printers={printers}
  8894. onClose={clearSelection}
  8895. onSelectAll={selectAll}
  8896. onSelectByLocation={selectByLocation}
  8897. onSelectByState={selectByState}
  8898. onAction={handleBulkAction}
  8899. actionPending={bulkActionPending}
  8900. />
  8901. )}
  8902. {/* Bulk action confirmation modals */}
  8903. {bulkConfirmAction === 'stop' && (
  8904. <ConfirmModal
  8905. title={t('printers.bulk.confirm.stopTitle', { count: selectedPrinterIds.size })}
  8906. message={t('printers.bulk.confirm.stopMessage', { count: selectedPrinterIds.size })}
  8907. confirmText={t('printers.bulk.confirm.stopButton')}
  8908. variant="danger"
  8909. isLoading={bulkActionPending}
  8910. onConfirm={() => executeBulkAction('stop')}
  8911. onCancel={() => setBulkConfirmAction(null)}
  8912. />
  8913. )}
  8914. {bulkConfirmAction === 'pause' && (
  8915. <ConfirmModal
  8916. title={t('printers.bulk.confirm.pauseTitle', { count: selectedPrinterIds.size })}
  8917. message={t('printers.bulk.confirm.pauseMessage', { count: selectedPrinterIds.size })}
  8918. confirmText={t('printers.bulk.confirm.pauseButton')}
  8919. isLoading={bulkActionPending}
  8920. onConfirm={() => executeBulkAction('pause')}
  8921. onCancel={() => setBulkConfirmAction(null)}
  8922. />
  8923. )}
  8924. {bulkConfirmAction === 'clearPlate' && (
  8925. <ConfirmModal
  8926. title={t('printers.bulk.confirm.clearPlateTitle', { count: selectedPrinterIds.size })}
  8927. message={t('printers.bulk.confirm.clearPlateMessage', { count: selectedPrinterIds.size })}
  8928. confirmText={t('printers.bulk.confirm.clearPlateButton')}
  8929. isLoading={bulkActionPending}
  8930. onConfirm={() => executeBulkAction('clearPlate')}
  8931. onCancel={() => setBulkConfirmAction(null)}
  8932. />
  8933. )}
  8934. {/* Embedded Camera Viewers - multiple viewers can be open simultaneously */}
  8935. {Array.from(embeddedCameraPrinters.values()).map((camera, index) => (
  8936. <EmbeddedCameraViewer
  8937. key={camera.id}
  8938. printerId={camera.id}
  8939. printerName={camera.name}
  8940. viewerIndex={index}
  8941. onClose={() => setEmbeddedCameraPrinters(prev => {
  8942. const next = new Map(prev);
  8943. next.delete(camera.id);
  8944. return next;
  8945. })}
  8946. />
  8947. ))}
  8948. </div>
  8949. );
  8950. }