PrintersPage.tsx 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691
  1. import { useState, useEffect, useMemo, useRef } from 'react';
  2. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  3. import { useTheme } from '../contexts/ThemeContext';
  4. import {
  5. Plus,
  6. Link,
  7. Unlink,
  8. Signal,
  9. Clock,
  10. MoreVertical,
  11. Trash2,
  12. RefreshCw,
  13. Box,
  14. HardDrive,
  15. AlertTriangle,
  16. AlertCircle,
  17. Terminal,
  18. Power,
  19. PowerOff,
  20. Zap,
  21. Wrench,
  22. ChevronDown,
  23. Pencil,
  24. ArrowUp,
  25. ArrowDown,
  26. LayoutGrid,
  27. LayoutList,
  28. Layers,
  29. Video,
  30. Search,
  31. Loader2,
  32. Square,
  33. Pause,
  34. Play,
  35. X,
  36. Monitor,
  37. Fan,
  38. Wind,
  39. AirVent,
  40. } from 'lucide-react';
  41. // Custom Skip Objects icon - arrow jumping over boxes
  42. const SkipObjectsIcon = ({ className }: { className?: string }) => (
  43. <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
  44. {/* Three boxes at the bottom */}
  45. <rect x="2" y="15" width="5" height="5" rx="0.5" />
  46. <rect x="9.5" y="15" width="5" height="5" rx="0.5" fill="currentColor" opacity="0.3" />
  47. <rect x="17" y="15" width="5" height="5" rx="0.5" />
  48. {/* Curved arrow jumping over first box */}
  49. <path d="M4 12 C4 6, 14 6, 14 12" />
  50. <polyline points="12,10 14,12 12,14" />
  51. </svg>
  52. );
  53. import { useNavigate } from 'react-router-dom';
  54. import { api, discoveryApi } from '../api/client';
  55. import type { Printer, PrinterCreate, AMSUnit, DiscoveredPrinter } from '../api/client';
  56. import { Card, CardContent } from '../components/Card';
  57. import { Button } from '../components/Button';
  58. import { ConfirmModal } from '../components/ConfirmModal';
  59. import { FileManagerModal } from '../components/FileManagerModal';
  60. import { MQTTDebugModal } from '../components/MQTTDebugModal';
  61. import { HMSErrorModal, filterKnownHMSErrors } from '../components/HMSErrorModal';
  62. import { PrinterQueueWidget } from '../components/PrinterQueueWidget';
  63. import { AMSHistoryModal } from '../components/AMSHistoryModal';
  64. import { FilamentHoverCard, EmptySlotHoverCard } from '../components/FilamentHoverCard';
  65. import { LinkSpoolModal } from '../components/LinkSpoolModal';
  66. import { useToast } from '../contexts/ToastContext';
  67. // Complete Bambu Lab filament color mapping by tray_id_name
  68. // Source: https://github.com/queengooborg/Bambu-Lab-RFID-Library
  69. const BAMBU_FILAMENT_COLORS: Record<string, string> = {
  70. // PLA Basic (A00)
  71. 'A00-W1': 'Jade White',
  72. 'A00-P0': 'Beige',
  73. 'A00-D2': 'Light Gray',
  74. 'A00-Y0': 'Yellow',
  75. 'A00-Y2': 'Sunflower Yellow',
  76. 'A00-A1': 'Pumpkin Orange',
  77. 'A00-A0': 'Orange',
  78. 'A00-Y4': 'Gold',
  79. 'A00-G3': 'Bright Green',
  80. 'A00-G1': 'Bambu Green',
  81. 'A00-G2': 'Mistletoe Green',
  82. 'A00-R3': 'Hot Pink',
  83. 'A00-P6': 'Magenta',
  84. 'A00-R0': 'Red',
  85. 'A00-R2': 'Maroon Red',
  86. 'A00-P5': 'Purple',
  87. 'A00-P2': 'Indigo Purple',
  88. 'A00-B5': 'Turquoise',
  89. 'A00-B8': 'Cyan',
  90. 'A00-B3': 'Cobalt Blue',
  91. 'A00-N0': 'Brown',
  92. 'A00-N1': 'Cocoa Brown',
  93. 'A00-Y3': 'Bronze',
  94. 'A00-D0': 'Gray',
  95. 'A00-D1': 'Silver',
  96. 'A00-B1': 'Blue Grey',
  97. 'A00-D3': 'Dark Gray',
  98. 'A00-K0': 'Black',
  99. // PLA Basic Gradient (A00-M*)
  100. 'A00-M3': 'Pink Citrus',
  101. 'A00-M6': 'Dusk Glare',
  102. 'A00-M0': 'Arctic Whisper',
  103. 'A00-M1': 'Solar Breeze',
  104. 'A00-M5': 'Blueberry Bubblegum',
  105. 'A00-M4': 'Mint Lime',
  106. 'A00-M2': 'Ocean to Meadow',
  107. 'A00-M7': 'Cotton Candy Cloud',
  108. // PLA Lite (A18)
  109. 'A18-K0': 'Black',
  110. 'A18-D0': 'Gray',
  111. 'A18-W0': 'White',
  112. 'A18-R0': 'Red',
  113. 'A18-Y0': 'Yellow',
  114. 'A18-B0': 'Cyan',
  115. 'A18-B1': 'Blue',
  116. 'A18-P0': 'Matte Beige',
  117. // PLA Matte (A01)
  118. 'A01-W2': 'Ivory White',
  119. 'A01-W3': 'Bone White',
  120. 'A01-Y2': 'Lemon Yellow',
  121. 'A01-A2': 'Mandarin Orange',
  122. 'A01-P3': 'Sakura Pink',
  123. 'A01-P4': 'Lilac Purple',
  124. 'A01-R3': 'Plum',
  125. 'A01-R1': 'Scarlet Red',
  126. 'A01-R4': 'Dark Red',
  127. 'A01-G0': 'Apple Green',
  128. 'A01-G1': 'Grass Green',
  129. 'A01-G7': 'Dark Green',
  130. 'A01-B4': 'Ice Blue',
  131. 'A01-B0': 'Sky Blue',
  132. 'A01-B3': 'Marine Blue',
  133. 'A01-B6': 'Dark Blue',
  134. 'A01-Y3': 'Desert Tan',
  135. 'A01-N1': 'Latte Brown',
  136. 'A01-N3': 'Caramel',
  137. 'A01-R2': 'Terracotta',
  138. 'A01-N2': 'Dark Brown',
  139. 'A01-N0': 'Dark Chocolate',
  140. 'A01-D3': 'Ash Gray',
  141. 'A01-D0': 'Nardo Gray',
  142. 'A01-K1': 'Charcoal',
  143. // PLA Glow (A12)
  144. 'A12-G0': 'Green',
  145. 'A12-R0': 'Pink',
  146. 'A12-A0': 'Orange',
  147. 'A12-Y0': 'Yellow',
  148. 'A12-B0': 'Blue',
  149. // PLA Marble (A07)
  150. 'A07-R5': 'Red Granite',
  151. 'A07-D4': 'White Marble',
  152. // PLA Aero (A11)
  153. 'A11-W0': 'White',
  154. 'A11-K0': 'Black',
  155. // PLA Sparkle (A08)
  156. 'A08-G3': 'Alpine Green Sparkle',
  157. 'A08-D5': 'Slate Gray Sparkle',
  158. 'A08-B7': 'Royal Purple Sparkle',
  159. 'A08-R2': 'Crimson Red Sparkle',
  160. 'A08-K2': 'Onyx Black Sparkle',
  161. 'A08-Y1': 'Classic Gold Sparkle',
  162. // PLA Metal (A02)
  163. 'A02-B2': 'Cobalt Blue Metallic',
  164. 'A02-G2': 'Oxide Green Metallic',
  165. 'A02-Y1': 'Iridium Gold Metallic',
  166. 'A02-D2': 'Iron Gray Metallic',
  167. // PLA Translucent (A17)
  168. 'A17-B1': 'Blue',
  169. 'A17-A0': 'Orange',
  170. 'A17-P0': 'Purple',
  171. // PLA Silk+ (A06)
  172. 'A06-Y1': 'Gold',
  173. 'A06-D0': 'Titan Gray',
  174. 'A06-D1': 'Silver',
  175. 'A06-W0': 'White',
  176. 'A06-R0': 'Candy Red',
  177. 'A06-G0': 'Candy Green',
  178. 'A06-G1': 'Mint',
  179. 'A06-B1': 'Blue',
  180. 'A06-B0': 'Baby Blue',
  181. 'A06-P0': 'Purple',
  182. 'A06-R1': 'Rose Gold',
  183. 'A06-R2': 'Pink',
  184. 'A06-Y0': 'Champagne',
  185. // PLA Silk Multi-Color (A05)
  186. 'A05-M8': 'Dawn Radiance',
  187. 'A05-M4': 'Aurora Purple',
  188. 'A05-M1': 'South Beach',
  189. 'A05-T3': 'Neon City',
  190. 'A05-T2': 'Midnight Blaze',
  191. 'A05-T1': 'Gilded Rose',
  192. 'A05-T4': 'Blue Hawaii',
  193. 'A05-T5': 'Velvet Eclipse',
  194. // PLA Galaxy (A15)
  195. 'A15-B0': 'Purple',
  196. 'A15-G0': 'Green',
  197. 'A15-G1': 'Nebulae',
  198. 'A15-R0': 'Brown',
  199. // PLA Wood (A16)
  200. 'A16-K0': 'Black Walnut',
  201. 'A16-R0': 'Rosewood',
  202. 'A16-N0': 'Clay Brown',
  203. 'A16-G0': 'Classic Birch',
  204. 'A16-W0': 'White Oak',
  205. 'A16-Y0': 'Ochre Yellow',
  206. // PLA-CF (A50)
  207. 'A50-D6': 'Lava Gray',
  208. 'A50-K0': 'Black',
  209. 'A50-B6': 'Royal Blue',
  210. // PLA Tough+ (A10)
  211. 'A10-W0': 'White',
  212. 'A10-D0': 'Gray',
  213. // PLA Tough (A09)
  214. 'A09-B5': 'Lavender Blue',
  215. 'A09-B4': 'Light Blue',
  216. 'A09-A0': 'Orange',
  217. 'A09-D1': 'Silver',
  218. 'A09-R3': 'Vermilion Red',
  219. 'A09-Y0': 'Yellow',
  220. // PETG HF (G02)
  221. 'G02-K0': 'Black',
  222. 'G02-W0': 'White',
  223. 'G02-R0': 'Red',
  224. 'G02-D0': 'Gray',
  225. 'G02-D1': 'Dark Gray',
  226. 'G02-Y1': 'Cream',
  227. 'G02-Y0': 'Yellow',
  228. 'G02-A0': 'Orange',
  229. 'G02-N1': 'Peanut Brown',
  230. 'G02-G1': 'Lime Green',
  231. 'G02-G0': 'Green',
  232. 'G02-G2': 'Forest Green',
  233. 'G02-B1': 'Lake Blue',
  234. 'G02-B0': 'Blue',
  235. // PETG Translucent (G01)
  236. 'G01-G1': 'Translucent Teal',
  237. 'G01-B0': 'Translucent Light Blue',
  238. 'G01-C0': 'Clear',
  239. 'G01-D0': 'Translucent Gray',
  240. 'G01-G0': 'Translucent Olive',
  241. 'G01-N0': 'Translucent Brown',
  242. 'G01-A0': 'Translucent Orange',
  243. 'G01-P1': 'Translucent Pink',
  244. 'G01-P0': 'Translucent Purple',
  245. // PETG-CF (G50)
  246. 'G50-P7': 'Violet Purple',
  247. 'G50-K0': 'Black',
  248. // ABS (B00)
  249. 'B00-D1': 'Silver',
  250. 'B00-K0': 'Black',
  251. 'B00-W0': 'White',
  252. 'B00-G6': 'Bambu Green',
  253. 'B00-G7': 'Olive',
  254. 'B00-Y1': 'Tangerine Yellow',
  255. 'B00-A0': 'Orange',
  256. 'B00-R0': 'Red',
  257. 'B00-B4': 'Azure',
  258. 'B00-B0': 'Blue',
  259. 'B00-B6': 'Navy Blue',
  260. // ABS-GF (B50)
  261. 'B50-A0': 'Orange',
  262. 'B50-K0': 'Black',
  263. // ASA (B01)
  264. 'B01-W0': 'White',
  265. 'B01-K0': 'Black',
  266. 'B01-D0': 'Gray',
  267. // ASA Aero (B02)
  268. 'B02-W0': 'White',
  269. // PC (C00)
  270. 'C00-C1': 'Transparent',
  271. 'C00-C0': 'Clear Black',
  272. 'C00-K0': 'Black',
  273. 'C00-W0': 'White',
  274. // PC FR (C01)
  275. 'C01-K0': 'Black',
  276. // TPU for AMS (U02)
  277. 'U02-B0': 'Blue',
  278. 'U02-D0': 'Gray',
  279. 'U02-K0': 'Black',
  280. // PAHT-CF (N04)
  281. 'N04-K0': 'Black',
  282. // PA6-GF (N08)
  283. 'N08-K0': 'Black',
  284. // Support for PLA/PETG (S02, S05)
  285. 'S02-W0': 'Nature',
  286. 'S02-W1': 'White',
  287. 'S05-C0': 'Black',
  288. // Support for ABS (S06)
  289. 'S06-W0': 'White',
  290. // Support for PA/PET (S03)
  291. 'S03-G1': 'Green',
  292. // PVA (S04)
  293. 'S04-Y0': 'Clear',
  294. };
  295. // Fallback color codes for unknown material prefixes
  296. const BAMBU_COLOR_CODE_FALLBACK: Record<string, string> = {
  297. 'W0': 'White', 'W1': 'Jade White', 'W2': 'Ivory White', 'W3': 'Bone White',
  298. 'Y0': 'Yellow', 'Y1': 'Gold', 'Y2': 'Sunflower Yellow', 'Y3': 'Bronze', 'Y4': 'Gold',
  299. 'A0': 'Orange', 'A1': 'Pumpkin Orange', 'A2': 'Mandarin Orange',
  300. 'R0': 'Red', 'R1': 'Scarlet Red', 'R2': 'Maroon Red', 'R3': 'Hot Pink', 'R4': 'Dark Red', 'R5': 'Red Granite',
  301. 'P0': 'Beige', 'P1': 'Pink', 'P2': 'Indigo Purple', 'P3': 'Sakura Pink', 'P4': 'Lilac Purple', 'P5': 'Purple', 'P6': 'Magenta', 'P7': 'Violet Purple',
  302. 'B0': 'Blue', 'B1': 'Blue Grey', 'B2': 'Cobalt Blue', 'B3': 'Cobalt Blue', 'B4': 'Ice Blue', 'B5': 'Turquoise', 'B6': 'Navy Blue', 'B7': 'Royal Purple', 'B8': 'Cyan',
  303. 'G0': 'Green', 'G1': 'Grass Green', 'G2': 'Mistletoe Green', 'G3': 'Bright Green', 'G6': 'Bambu Green', 'G7': 'Dark Green',
  304. 'N0': 'Brown', 'N1': 'Peanut Brown', 'N2': 'Dark Brown', 'N3': 'Caramel',
  305. 'D0': 'Gray', 'D1': 'Silver', 'D2': 'Light Gray', 'D3': 'Dark Gray', 'D4': 'White Marble', 'D5': 'Slate Gray', 'D6': 'Lava Gray',
  306. 'K0': 'Black', 'K1': 'Charcoal', 'K2': 'Onyx Black',
  307. 'C0': 'Clear Black', 'C1': 'Transparent',
  308. 'M0': 'Arctic Whisper', 'M1': 'Solar Breeze', 'M2': 'Ocean to Meadow', 'M3': 'Pink Citrus', 'M4': 'Aurora Purple', 'M5': 'Blueberry Bubblegum', 'M6': 'Dusk Glare', 'M7': 'Cotton Candy Cloud', 'M8': 'Dawn Radiance',
  309. 'T1': 'Gilded Rose', 'T2': 'Midnight Blaze', 'T3': 'Neon City', 'T4': 'Blue Hawaii', 'T5': 'Velvet Eclipse',
  310. };
  311. // Get color name from Bambu Lab tray_id_name (e.g., "A00-Y2" -> "Sunflower Yellow")
  312. function getBambuColorName(trayIdName: string | null | undefined): string | null {
  313. if (!trayIdName) return null;
  314. // First try exact match with full tray_id_name
  315. if (BAMBU_FILAMENT_COLORS[trayIdName]) {
  316. return BAMBU_FILAMENT_COLORS[trayIdName];
  317. }
  318. // Fall back to color code suffix lookup for unknown material prefixes
  319. const parts = trayIdName.split('-');
  320. if (parts.length < 2) return null;
  321. const colorCode = parts[1];
  322. return BAMBU_COLOR_CODE_FALLBACK[colorCode] || null;
  323. }
  324. // Convert hex color to basic color name
  325. function hexToBasicColorName(hex: string | null | undefined): string {
  326. if (!hex || hex.length < 6) return 'Unknown';
  327. // Parse RGB from hex (format: RRGGBBAA or RRGGBB)
  328. const r = parseInt(hex.substring(0, 2), 16);
  329. const g = parseInt(hex.substring(2, 4), 16);
  330. const b = parseInt(hex.substring(4, 6), 16);
  331. // Calculate HSL for better color classification
  332. const max = Math.max(r, g, b) / 255;
  333. const min = Math.min(r, g, b) / 255;
  334. const l = (max + min) / 2;
  335. let h = 0;
  336. let s = 0;
  337. if (max !== min) {
  338. const d = max - min;
  339. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  340. const rNorm = r / 255;
  341. const gNorm = g / 255;
  342. const bNorm = b / 255;
  343. if (max === rNorm) {
  344. h = ((gNorm - bNorm) / d + (gNorm < bNorm ? 6 : 0)) / 6;
  345. } else if (max === gNorm) {
  346. h = ((bNorm - rNorm) / d + 2) / 6;
  347. } else {
  348. h = ((rNorm - gNorm) / d + 4) / 6;
  349. }
  350. }
  351. // Convert to degrees
  352. h = h * 360;
  353. // Classify by lightness first
  354. if (l < 0.15) return 'Black';
  355. if (l > 0.85) return 'White';
  356. // Low saturation = gray
  357. if (s < 0.15) {
  358. if (l < 0.4) return 'Dark Gray';
  359. if (l > 0.6) return 'Light Gray';
  360. return 'Gray';
  361. }
  362. // Classify by hue
  363. if (h < 15 || h >= 345) return 'Red';
  364. if (h < 45) return 'Orange';
  365. if (h < 70) return 'Yellow';
  366. if (h < 150) return 'Green';
  367. if (h < 200) return 'Cyan';
  368. if (h < 260) return 'Blue';
  369. if (h < 290) return 'Purple';
  370. if (h < 345) return 'Pink';
  371. return 'Unknown';
  372. }
  373. // Format K value with 3 decimal places, default to 0.020 if null
  374. function formatKValue(k: number | null | undefined): string {
  375. const value = k ?? 0.020;
  376. return value.toFixed(3);
  377. }
  378. // Nozzle side indicators (Bambu Lab style - square badge with L/R)
  379. function NozzleBadge({ side }: { side: 'L' | 'R' }) {
  380. const { mode } = useTheme();
  381. // Light mode: #e7f5e9 (light green), Dark mode: #1a4d2e (dark green)
  382. const bgColor = mode === 'dark' ? '#1a4d2e' : '#e7f5e9';
  383. return (
  384. <span
  385. className="inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded"
  386. style={{ backgroundColor: bgColor, color: '#00ae42' }}
  387. >
  388. {side}
  389. </span>
  390. );
  391. }
  392. // Water drop SVG - empty outline (Bambu Lab style from bambu-humidity)
  393. function WaterDropEmpty({ className }: { className?: string }) {
  394. return (
  395. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  396. <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"/>
  397. </svg>
  398. );
  399. }
  400. // Water drop SVG - half filled with blue water (Bambu Lab style from bambu-humidity)
  401. function WaterDropHalf({ className }: { className?: string }) {
  402. return (
  403. <svg className={className} viewBox="0 0 35 53" fill="none" xmlns="http://www.w3.org/2000/svg">
  404. <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"/>
  405. <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"/>
  406. </svg>
  407. );
  408. }
  409. // Water drop SVG - fully filled with blue water (Bambu Lab style from bambu-humidity)
  410. function WaterDropFull({ className }: { className?: string }) {
  411. return (
  412. <svg className={className} viewBox="0 0 36 54" fill="none" xmlns="http://www.w3.org/2000/svg">
  413. <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"/>
  414. <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"/>
  415. </svg>
  416. );
  417. }
  418. // Thermometer SVG - empty outline
  419. function ThermometerEmpty({ className }: { className?: string }) {
  420. return (
  421. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  422. <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"/>
  423. <circle cx="6" cy="15" r="2.5" stroke="#C3C2C1" strokeWidth="1" fill="none"/>
  424. </svg>
  425. );
  426. }
  427. // Thermometer SVG - half filled (gold - same as humidity fair)
  428. function ThermometerHalf({ className }: { className?: string }) {
  429. return (
  430. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  431. <rect x="4.5" y="8" width="3" height="4.5" fill="#d4a017" rx="0.5"/>
  432. <circle cx="6" cy="15" r="2" fill="#d4a017"/>
  433. <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"/>
  434. </svg>
  435. );
  436. }
  437. // Thermometer SVG - fully filled (red - same as humidity bad)
  438. function ThermometerFull({ className }: { className?: string }) {
  439. return (
  440. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  441. <rect x="4.5" y="3" width="3" height="9.5" fill="#c62828" rx="0.5"/>
  442. <circle cx="6" cy="15" r="2" fill="#c62828"/>
  443. <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"/>
  444. </svg>
  445. );
  446. }
  447. // Heater thermometer icon - filled when heating, outline when off
  448. interface HeaterThermometerProps {
  449. className?: string;
  450. color: string; // The color class (e.g., "text-orange-400")
  451. isHeating: boolean;
  452. }
  453. function HeaterThermometer({ className, color, isHeating }: HeaterThermometerProps) {
  454. // Extract the actual color from Tailwind class for SVG fill
  455. const colorMap: Record<string, string> = {
  456. 'text-orange-400': '#fb923c',
  457. 'text-blue-400': '#60a5fa',
  458. 'text-green-400': '#4ade80',
  459. };
  460. const fillColor = colorMap[color] || '#888';
  461. // Glow style when heating
  462. const glowStyle = isHeating ? {
  463. filter: `drop-shadow(0 0 4px ${fillColor}) drop-shadow(0 0 8px ${fillColor})`,
  464. } : {};
  465. if (isHeating) {
  466. // Filled thermometer with glow - heater is ON
  467. return (
  468. <svg className={className} style={glowStyle} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  469. <rect x="4.5" y="3" width="3" height="9.5" fill={fillColor} rx="0.5"/>
  470. <circle cx="6" cy="15" r="2" fill={fillColor}/>
  471. <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"/>
  472. </svg>
  473. );
  474. }
  475. // Empty thermometer - heater is OFF
  476. return (
  477. <svg className={className} viewBox="0 0 12 20" fill="none" xmlns="http://www.w3.org/2000/svg">
  478. <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"/>
  479. <circle cx="6" cy="15" r="2.5" stroke={fillColor} strokeWidth="1" fill="none"/>
  480. </svg>
  481. );
  482. }
  483. // Humidity indicator with water drop that fills based on level (Bambu Lab style)
  484. // Reference: https://github.com/theicedmango/bambu-humidity
  485. interface HumidityIndicatorProps {
  486. humidity: number | string;
  487. goodThreshold?: number; // <= this is green
  488. fairThreshold?: number; // <= this is orange, > is red
  489. onClick?: () => void;
  490. compact?: boolean; // Smaller version for grid layout
  491. }
  492. function HumidityIndicator({ humidity, goodThreshold = 40, fairThreshold = 60, onClick, compact }: HumidityIndicatorProps) {
  493. const humidityValue = typeof humidity === 'string' ? parseInt(humidity, 10) : humidity;
  494. const good = typeof goodThreshold === 'number' ? goodThreshold : 40;
  495. const fair = typeof fairThreshold === 'number' ? fairThreshold : 60;
  496. // Status thresholds (configurable via settings)
  497. // Good: ≤goodThreshold (green #22a352), Fair: ≤fairThreshold (gold #d4a017), Bad: >fairThreshold (red #c62828)
  498. let textColor: string;
  499. let statusText: string;
  500. if (isNaN(humidityValue)) {
  501. textColor = '#C3C2C1';
  502. statusText = 'Unknown';
  503. } else if (humidityValue <= good) {
  504. textColor = '#22a352'; // Green - Good
  505. statusText = 'Good';
  506. } else if (humidityValue <= fair) {
  507. textColor = '#d4a017'; // Gold - Fair
  508. statusText = 'Fair';
  509. } else {
  510. textColor = '#c62828'; // Red - Bad
  511. statusText = 'Bad';
  512. }
  513. // Fill level based on status: Good=Empty (dry), Fair=Half, Bad=Full (wet)
  514. let DropComponent: React.FC<{ className?: string }>;
  515. if (isNaN(humidityValue)) {
  516. DropComponent = WaterDropEmpty;
  517. } else if (humidityValue <= good) {
  518. DropComponent = WaterDropEmpty; // Good - empty drop (dry)
  519. } else if (humidityValue <= fair) {
  520. DropComponent = WaterDropHalf; // Fair - half filled
  521. } else {
  522. DropComponent = WaterDropFull; // Bad - full (too humid)
  523. }
  524. return (
  525. <button
  526. type="button"
  527. onClick={onClick}
  528. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  529. title={`Humidity: ${humidityValue}% - ${statusText}${onClick ? ' (click for history)' : ''}`}
  530. >
  531. <DropComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  532. <span className={`font-medium tabular-nums ${compact ? 'text-[10px]' : 'text-xs'}`} style={{ color: textColor }}>{humidityValue}%</span>
  533. </button>
  534. );
  535. }
  536. // Temperature indicator with dynamic icon and coloring
  537. interface TemperatureIndicatorProps {
  538. temp: number;
  539. goodThreshold?: number; // <= this is blue
  540. fairThreshold?: number; // <= this is orange, > is red
  541. onClick?: () => void;
  542. compact?: boolean; // Smaller version for grid layout
  543. }
  544. function TemperatureIndicator({ temp, goodThreshold = 28, fairThreshold = 35, onClick, compact }: TemperatureIndicatorProps) {
  545. // Ensure thresholds are numbers
  546. const good = typeof goodThreshold === 'number' ? goodThreshold : 28;
  547. const fair = typeof fairThreshold === 'number' ? fairThreshold : 35;
  548. let textColor: string;
  549. let statusText: string;
  550. let ThermoComponent: React.FC<{ className?: string }>;
  551. if (temp <= good) {
  552. textColor = '#22a352'; // Green - good (same as humidity)
  553. statusText = 'Good';
  554. ThermoComponent = ThermometerEmpty;
  555. } else if (temp <= fair) {
  556. textColor = '#d4a017'; // Gold - fair (same as humidity)
  557. statusText = 'Fair';
  558. ThermoComponent = ThermometerHalf;
  559. } else {
  560. textColor = '#c62828'; // Red - bad (same as humidity)
  561. statusText = 'Bad';
  562. ThermoComponent = ThermometerFull;
  563. }
  564. return (
  565. <button
  566. type="button"
  567. onClick={onClick}
  568. className={`flex items-center gap-1 ${onClick ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
  569. title={`Temperature: ${temp}°C - ${statusText}${onClick ? ' (click for history)' : ''}`}
  570. >
  571. <ThermoComponent className={compact ? "w-2.5 h-3" : "w-3 h-4"} />
  572. <span className={`tabular-nums text-right ${compact ? 'text-[10px] w-8' : 'w-12'}`} style={{ color: textColor }}>{temp}°C</span>
  573. </button>
  574. );
  575. }
  576. // Get AMS label: AMS-A/B/C/D for regular AMS, HT-A/B for AMS-HT (single spool)
  577. // Always use tray count as the source of truth (1 tray = AMS-HT, 4 trays = regular AMS)
  578. // AMS-HT uses IDs 128+ while regular AMS uses 0-3
  579. function getAmsLabel(amsId: number | string, trayCount: number): string {
  580. // Ensure amsId is a number (backend might send string)
  581. const id = typeof amsId === 'string' ? parseInt(amsId, 10) : amsId;
  582. const safeId = isNaN(id) ? 0 : id;
  583. const isHt = trayCount === 1;
  584. // AMS-HT uses IDs starting at 128, regular AMS uses 0-3
  585. const normalizedId = safeId >= 128 ? safeId - 128 : safeId;
  586. const letter = String.fromCharCode(65 + normalizedId); // 0=A, 1=B, 2=C, 3=D
  587. return isHt ? `HT-${letter}` : `AMS-${letter}`;
  588. }
  589. // Get fill bar color based on spool fill level
  590. function getFillBarColor(fillLevel: number): string {
  591. if (fillLevel > 50) return '#00ae42'; // Green - good
  592. if (fillLevel >= 15) return '#f59e0b'; // Amber - warning (<= 50%)
  593. return '#ef4444'; // Red - critical (< 15%)
  594. }
  595. function formatTime(seconds: number): string {
  596. const hours = Math.floor(seconds / 3600);
  597. const minutes = Math.floor((seconds % 3600) / 60);
  598. return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
  599. }
  600. function formatETA(remainingMinutes: number): string {
  601. const now = new Date();
  602. const eta = new Date(now.getTime() + remainingMinutes * 60 * 1000);
  603. const today = new Date();
  604. today.setHours(0, 0, 0, 0);
  605. const etaDay = new Date(eta);
  606. etaDay.setHours(0, 0, 0, 0);
  607. const timeStr = eta.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  608. // Check if it's tomorrow or later
  609. const dayDiff = Math.floor((etaDay.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  610. if (dayDiff === 0) {
  611. return timeStr;
  612. } else if (dayDiff === 1) {
  613. return `Tomorrow ${timeStr}`;
  614. } else {
  615. return eta.toLocaleDateString([], { weekday: 'short' }) + ' ' + timeStr;
  616. }
  617. }
  618. function getPrinterImage(model: string | null | undefined): string {
  619. if (!model) return '/img/printers/default.png';
  620. const modelLower = model.toLowerCase().replace(/\s+/g, '');
  621. // Map model names to image files
  622. if (modelLower.includes('x1e')) return '/img/printers/x1e.png';
  623. if (modelLower.includes('x1c') || modelLower.includes('x1carbon')) return '/img/printers/x1c.png';
  624. if (modelLower.includes('x1')) return '/img/printers/x1c.png';
  625. if (modelLower.includes('h2d')) return '/img/printers/h2d.png';
  626. if (modelLower.includes('h2c') || modelLower.includes('h2s')) return '/img/printers/h2d.png';
  627. if (modelLower.includes('p2s')) return '/img/printers/p1s.png';
  628. if (modelLower.includes('p1s')) return '/img/printers/p1s.png';
  629. if (modelLower.includes('p1p')) return '/img/printers/p1p.png';
  630. if (modelLower.includes('a1mini')) return '/img/printers/a1mini.png';
  631. if (modelLower.includes('a1')) return '/img/printers/a1.png';
  632. return '/img/printers/default.png';
  633. }
  634. function getWifiStrength(rssi: number | null | undefined): { label: string; color: string; bars: number } {
  635. if (rssi == null) return { label: '', color: 'text-bambu-gray', bars: 0 };
  636. if (rssi >= -50) return { label: 'Excellent', color: 'text-bambu-green', bars: 4 };
  637. if (rssi >= -60) return { label: 'Good', color: 'text-bambu-green', bars: 3 };
  638. if (rssi >= -70) return { label: 'Fair', color: 'text-yellow-400', bars: 2 };
  639. if (rssi >= -80) return { label: 'Weak', color: 'text-orange-400', bars: 1 };
  640. return { label: 'Very weak', color: 'text-red-400', bars: 1 };
  641. }
  642. function CoverImage({ url, printName }: { url: string | null; printName?: string }) {
  643. const [loaded, setLoaded] = useState(false);
  644. const [error, setError] = useState(false);
  645. const [showOverlay, setShowOverlay] = useState(false);
  646. return (
  647. <>
  648. <div
  649. className={`w-20 h-20 flex-shrink-0 rounded-lg overflow-hidden bg-bambu-dark-tertiary flex items-center justify-center ${url && loaded ? 'cursor-pointer' : ''}`}
  650. onClick={() => url && loaded && setShowOverlay(true)}
  651. >
  652. {url && !error ? (
  653. <>
  654. <img
  655. src={url}
  656. alt="Print preview"
  657. className={`w-full h-full object-cover ${loaded ? 'block' : 'hidden'}`}
  658. onLoad={() => setLoaded(true)}
  659. onError={() => setError(true)}
  660. />
  661. {!loaded && <Box className="w-8 h-8 text-bambu-gray" />}
  662. </>
  663. ) : (
  664. <Box className="w-8 h-8 text-bambu-gray" />
  665. )}
  666. </div>
  667. {/* Cover Image Overlay */}
  668. {showOverlay && url && (
  669. <div
  670. className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-8"
  671. onClick={() => setShowOverlay(false)}
  672. >
  673. <div className="relative max-w-2xl max-h-full">
  674. <img
  675. src={url}
  676. alt="Print preview"
  677. className="max-w-full max-h-[80vh] rounded-lg shadow-2xl"
  678. />
  679. {printName && (
  680. <p className="text-white text-center mt-4 text-lg">{printName}</p>
  681. )}
  682. </div>
  683. </div>
  684. )}
  685. </>
  686. );
  687. }
  688. interface PrinterMaintenanceInfo {
  689. due_count: number;
  690. warning_count: number;
  691. total_print_hours: number;
  692. }
  693. // Status summary bar component - uses queryClient to read cached statuses
  694. function StatusSummaryBar({ printers }: { printers: Printer[] | undefined }) {
  695. const queryClient = useQueryClient();
  696. const counts = useMemo(() => {
  697. let printing = 0;
  698. let idle = 0;
  699. let offline = 0;
  700. let loading = 0;
  701. printers?.forEach((printer) => {
  702. const status = queryClient.getQueryData<{ connected: boolean; state: string | null }>(['printerStatus', printer.id]);
  703. if (status === undefined) {
  704. // Status not yet loaded - don't count as offline yet
  705. loading++;
  706. } else if (!status.connected) {
  707. offline++;
  708. } else if (status.state === 'RUNNING') {
  709. printing++;
  710. } else {
  711. idle++;
  712. }
  713. });
  714. return { printing, idle, offline, loading, total: (printers?.length || 0) };
  715. }, [printers, queryClient]);
  716. // Subscribe to query cache changes to re-render when status updates
  717. // Throttled to prevent rapid re-renders from causing tab crashes
  718. const [, setTick] = useState(0);
  719. useEffect(() => {
  720. let pending = false;
  721. const unsubscribe = queryClient.getQueryCache().subscribe(() => {
  722. if (!pending) {
  723. pending = true;
  724. requestAnimationFrame(() => {
  725. setTick(t => t + 1);
  726. pending = false;
  727. });
  728. }
  729. });
  730. return () => unsubscribe();
  731. }, [queryClient]);
  732. if (!printers?.length) return null;
  733. return (
  734. <div className="flex items-center gap-4 text-sm">
  735. {counts.printing > 0 && (
  736. <div className="flex items-center gap-1.5">
  737. <div className="w-2 h-2 rounded-full bg-bambu-green animate-pulse" />
  738. <span className="text-bambu-gray">
  739. <span className="text-white font-medium">{counts.printing}</span> printing
  740. </span>
  741. </div>
  742. )}
  743. {counts.idle > 0 && (
  744. <div className="flex items-center gap-1.5">
  745. <div className="w-2 h-2 rounded-full bg-blue-400" />
  746. <span className="text-bambu-gray">
  747. <span className="text-white font-medium">{counts.idle}</span> idle
  748. </span>
  749. </div>
  750. )}
  751. {counts.offline > 0 && (
  752. <div className="flex items-center gap-1.5">
  753. <div className="w-2 h-2 rounded-full bg-gray-400" />
  754. <span className="text-bambu-gray">
  755. <span className="text-white font-medium">{counts.offline}</span> offline
  756. </span>
  757. </div>
  758. )}
  759. </div>
  760. );
  761. }
  762. type SortOption = 'name' | 'status' | 'model' | 'location';
  763. type ViewMode = 'expanded' | 'compact';
  764. /**
  765. * Get human-readable status display text for a printer.
  766. * Uses stg_cur_name for detailed calibration/preparation stages,
  767. * otherwise formats the gcode_state nicely.
  768. */
  769. function getStatusDisplay(state: string | null | undefined, stg_cur_name: string | null | undefined): string {
  770. // If we have a specific stage name (calibration, heating, etc.), use it
  771. if (stg_cur_name) {
  772. return stg_cur_name;
  773. }
  774. // Format the gcode_state nicely
  775. switch (state) {
  776. case 'RUNNING':
  777. return 'Printing';
  778. case 'PAUSE':
  779. return 'Paused';
  780. case 'FINISH':
  781. return 'Finished';
  782. case 'FAILED':
  783. return 'Failed';
  784. case 'IDLE':
  785. return 'Idle';
  786. default:
  787. return state ? state.charAt(0) + state.slice(1).toLowerCase() : 'Idle';
  788. }
  789. }
  790. function PrinterCard({
  791. printer,
  792. hideIfDisconnected,
  793. maintenanceInfo,
  794. viewMode = 'expanded',
  795. amsThresholds,
  796. spoolmanEnabled = false,
  797. }: {
  798. printer: Printer;
  799. hideIfDisconnected?: boolean;
  800. maintenanceInfo?: PrinterMaintenanceInfo;
  801. viewMode?: ViewMode;
  802. amsThresholds?: {
  803. humidityGood: number;
  804. humidityFair: number;
  805. tempGood: number;
  806. tempFair: number;
  807. };
  808. spoolmanEnabled?: boolean;
  809. }) {
  810. const queryClient = useQueryClient();
  811. const navigate = useNavigate();
  812. const { showToast } = useToast();
  813. const [showMenu, setShowMenu] = useState(false);
  814. const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  815. const [deleteArchives, setDeleteArchives] = useState(true);
  816. const [showEditModal, setShowEditModal] = useState(false);
  817. const [showFileManager, setShowFileManager] = useState(false);
  818. const [showMQTTDebug, setShowMQTTDebug] = useState(false);
  819. const [showPowerOnConfirm, setShowPowerOnConfirm] = useState(false);
  820. const [showPowerOffConfirm, setShowPowerOffConfirm] = useState(false);
  821. const [showHMSModal, setShowHMSModal] = useState(false);
  822. const [showStopConfirm, setShowStopConfirm] = useState(false);
  823. const [showPauseConfirm, setShowPauseConfirm] = useState(false);
  824. const [showResumeConfirm, setShowResumeConfirm] = useState(false);
  825. const [showSkipObjectsModal, setShowSkipObjectsModal] = useState(false);
  826. const [amsHistoryModal, setAmsHistoryModal] = useState<{
  827. amsId: number;
  828. amsLabel: string;
  829. mode: 'humidity' | 'temperature';
  830. } | null>(null);
  831. const [linkSpoolModal, setLinkSpoolModal] = useState<{
  832. trayUuid: string;
  833. trayInfo: { type: string; color: string; location: string };
  834. } | null>(null);
  835. const { data: status } = useQuery({
  836. queryKey: ['printerStatus', printer.id],
  837. queryFn: () => api.getPrinterStatus(printer.id),
  838. refetchInterval: 30000, // Fallback polling, WebSocket handles real-time
  839. });
  840. // Collect unique tray_info_idx values for cloud filament info lookup
  841. const trayInfoIds = useMemo(() => {
  842. const ids = new Set<string>();
  843. if (status?.ams) {
  844. for (const ams of status.ams) {
  845. for (const tray of ams.tray || []) {
  846. if (tray.tray_info_idx) {
  847. ids.add(tray.tray_info_idx);
  848. }
  849. }
  850. }
  851. }
  852. if (status?.vt_tray?.tray_info_idx) {
  853. ids.add(status.vt_tray.tray_info_idx);
  854. }
  855. return Array.from(ids);
  856. }, [status?.ams, status?.vt_tray]);
  857. // Fetch cloud filament info for tooltips (name includes color, also has K value)
  858. const { data: filamentInfo } = useQuery({
  859. queryKey: ['filamentInfo', trayInfoIds],
  860. queryFn: () => api.getFilamentInfo(trayInfoIds),
  861. enabled: trayInfoIds.length > 0,
  862. staleTime: 5 * 60 * 1000, // 5 minutes
  863. });
  864. // Cache WiFi signal to prevent it disappearing on updates
  865. const [cachedWifiSignal, setCachedWifiSignal] = useState<number | null>(null);
  866. useEffect(() => {
  867. if (status?.wifi_signal != null) {
  868. setCachedWifiSignal(status.wifi_signal);
  869. }
  870. }, [status?.wifi_signal]);
  871. const wifiSignal = status?.wifi_signal ?? cachedWifiSignal;
  872. // Cache connected state to prevent flicker when status briefly becomes undefined
  873. const cachedConnected = useRef<boolean | undefined>(undefined);
  874. useEffect(() => {
  875. if (status?.connected !== undefined) {
  876. cachedConnected.current = status.connected;
  877. }
  878. }, [status?.connected]);
  879. const isConnected = status?.connected ?? cachedConnected.current;
  880. // Cache ams_extruder_map to prevent L/R indicators bouncing on updates
  881. const cachedAmsExtruderMap = useRef<Record<string, number>>({});
  882. useEffect(() => {
  883. if (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0) {
  884. cachedAmsExtruderMap.current = status.ams_extruder_map;
  885. }
  886. }, [status?.ams_extruder_map]);
  887. const amsExtruderMap = (status?.ams_extruder_map && Object.keys(status.ams_extruder_map).length > 0)
  888. ? status.ams_extruder_map
  889. : cachedAmsExtruderMap.current;
  890. // Cache AMS data to prevent it disappearing on idle/offline printers
  891. const cachedAmsData = useRef<AMSUnit[]>([]);
  892. useEffect(() => {
  893. if (status?.ams && status.ams.length > 0) {
  894. cachedAmsData.current = status.ams;
  895. }
  896. }, [status?.ams]);
  897. const amsData = (status?.ams && status.ams.length > 0) ? status.ams : cachedAmsData.current;
  898. // Cache tray_now to prevent flickering when 255 (unloaded) or undefined values come in
  899. // Only update cache when we get a valid tray ID (0-253 or 254 for external)
  900. const cachedTrayNow = useRef<number>(255);
  901. const currentTrayNow = status?.tray_now;
  902. // Update cache synchronously during render if we have a valid value
  903. if (currentTrayNow !== undefined && currentTrayNow !== 255) {
  904. cachedTrayNow.current = currentTrayNow;
  905. }
  906. // Use cached value if current is 255/undefined but we had a valid value before
  907. const effectiveTrayNow = (currentTrayNow === undefined || currentTrayNow === 255)
  908. ? cachedTrayNow.current
  909. : currentTrayNow;
  910. // Fetch smart plug for this printer
  911. const { data: smartPlug } = useQuery({
  912. queryKey: ['smartPlugByPrinter', printer.id],
  913. queryFn: () => api.getSmartPlugByPrinter(printer.id),
  914. });
  915. // Fetch smart plug status if plug exists (faster refresh for energy monitoring)
  916. const { data: plugStatus } = useQuery({
  917. queryKey: ['smartPlugStatus', smartPlug?.id],
  918. queryFn: () => smartPlug ? api.getSmartPlugStatus(smartPlug.id) : null,
  919. enabled: !!smartPlug,
  920. refetchInterval: 10000, // 10 seconds for real-time power display
  921. });
  922. // Fetch queue count for this printer
  923. const { data: queueItems } = useQuery({
  924. queryKey: ['queue', printer.id, 'pending'],
  925. queryFn: () => api.getQueue(printer.id, 'pending'),
  926. });
  927. const queueCount = queueItems?.length || 0;
  928. // Fetch last completed print for this printer
  929. const { data: lastPrints } = useQuery({
  930. queryKey: ['archives', printer.id, 'last'],
  931. queryFn: () => api.getArchives(printer.id, 1, 0),
  932. enabled: status?.connected && status?.state !== 'RUNNING',
  933. });
  934. const lastPrint = lastPrints?.[0];
  935. // Determine if this card should be hidden (use cached connected state to prevent flicker)
  936. const shouldHide = hideIfDisconnected && isConnected === false;
  937. const deleteMutation = useMutation({
  938. mutationFn: (options: { deleteArchives: boolean }) =>
  939. api.deletePrinter(printer.id, options.deleteArchives),
  940. onSuccess: () => {
  941. queryClient.invalidateQueries({ queryKey: ['printers'] });
  942. queryClient.invalidateQueries({ queryKey: ['archives'] });
  943. },
  944. });
  945. const connectMutation = useMutation({
  946. mutationFn: () => api.connectPrinter(printer.id),
  947. onSuccess: () => {
  948. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  949. },
  950. });
  951. // Smart plug control mutations
  952. const powerControlMutation = useMutation({
  953. mutationFn: (action: 'on' | 'off') =>
  954. smartPlug ? api.controlSmartPlug(smartPlug.id, action) : Promise.reject('No plug'),
  955. onSuccess: () => {
  956. queryClient.invalidateQueries({ queryKey: ['smartPlugStatus', smartPlug?.id] });
  957. },
  958. });
  959. const toggleAutoOffMutation = useMutation({
  960. mutationFn: (enabled: boolean) =>
  961. smartPlug ? api.updateSmartPlug(smartPlug.id, { auto_off: enabled }) : Promise.reject('No plug'),
  962. onSuccess: () => {
  963. queryClient.invalidateQueries({ queryKey: ['smartPlugByPrinter', printer.id] });
  964. // Also invalidate the smart-plugs list to keep Settings page in sync
  965. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  966. },
  967. });
  968. // Print control mutations
  969. const stopPrintMutation = useMutation({
  970. mutationFn: () => api.stopPrint(printer.id),
  971. onSuccess: () => {
  972. showToast('Print stopped');
  973. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  974. },
  975. onError: (error: Error) => showToast(error.message || 'Failed to stop print', 'error'),
  976. });
  977. const pausePrintMutation = useMutation({
  978. mutationFn: () => api.pausePrint(printer.id),
  979. onSuccess: () => {
  980. showToast('Print paused');
  981. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  982. },
  983. onError: (error: Error) => showToast(error.message || 'Failed to pause print', 'error'),
  984. });
  985. const resumePrintMutation = useMutation({
  986. mutationFn: () => api.resumePrint(printer.id),
  987. onSuccess: () => {
  988. showToast('Print resumed');
  989. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  990. },
  991. onError: (error: Error) => showToast(error.message || 'Failed to resume print', 'error'),
  992. });
  993. // Query for printable objects (for skip functionality)
  994. // Fetch when printing with 2+ objects OR when modal is open
  995. const isPrintingWithObjects = (status?.state === 'RUNNING' || status?.state === 'PAUSE' || status?.state === 'PAUSED') && (status?.printable_objects_count ?? 0) >= 2;
  996. const { data: objectsData, refetch: refetchObjects } = useQuery({
  997. queryKey: ['printableObjects', printer.id],
  998. queryFn: () => api.getPrintableObjects(printer.id),
  999. enabled: showSkipObjectsModal || isPrintingWithObjects,
  1000. refetchInterval: showSkipObjectsModal ? 5000 : (isPrintingWithObjects ? 30000 : false), // 5s when modal open, 30s otherwise
  1001. });
  1002. // Skip objects mutation
  1003. const skipObjectsMutation = useMutation({
  1004. mutationFn: (objectIds: number[]) => api.skipObjects(printer.id, objectIds),
  1005. onSuccess: (data) => {
  1006. showToast(data.message || 'Objects skipped');
  1007. refetchObjects();
  1008. },
  1009. onError: (error: Error) => showToast(error.message || 'Failed to skip objects', 'error'),
  1010. });
  1011. // State for tracking which AMS slot is being refreshed
  1012. const [refreshingSlot, setRefreshingSlot] = useState<{ amsId: number; slotId: number } | null>(null);
  1013. // Track if we've seen the printer enter "busy" state (ams_status_main !== 0)
  1014. const seenBusyStateRef = useRef<boolean>(false);
  1015. // Fallback timeout ref
  1016. const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1017. // Minimum display time passed
  1018. const minTimePassedRef = useRef<boolean>(false);
  1019. // AMS slot refresh mutation
  1020. const refreshAmsSlotMutation = useMutation({
  1021. mutationFn: ({ amsId, slotId }: { amsId: number; slotId: number }) =>
  1022. api.refreshAmsSlot(printer.id, amsId, slotId),
  1023. onMutate: ({ amsId, slotId }) => {
  1024. // Clear any existing timeout
  1025. if (refreshTimeoutRef.current) {
  1026. clearTimeout(refreshTimeoutRef.current);
  1027. }
  1028. // Reset state
  1029. seenBusyStateRef.current = false;
  1030. minTimePassedRef.current = false;
  1031. setRefreshingSlot({ amsId, slotId });
  1032. // Minimum display time (2 seconds)
  1033. setTimeout(() => {
  1034. minTimePassedRef.current = true;
  1035. }, 2000);
  1036. // Fallback timeout (30 seconds max)
  1037. refreshTimeoutRef.current = setTimeout(() => {
  1038. setRefreshingSlot(null);
  1039. }, 30000);
  1040. },
  1041. onSuccess: (data) => {
  1042. showToast(data.message || 'RFID re-read initiated');
  1043. },
  1044. onError: (error: Error) => {
  1045. showToast(error.message || 'Failed to re-read RFID', 'error');
  1046. if (refreshTimeoutRef.current) {
  1047. clearTimeout(refreshTimeoutRef.current);
  1048. }
  1049. setRefreshingSlot(null);
  1050. },
  1051. });
  1052. // Watch ams_status_main to detect when RFID read completes
  1053. // ams_status_main: 0=idle, 2=rfid_identifying
  1054. const deferredClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  1055. useEffect(() => {
  1056. if (!refreshingSlot) return;
  1057. const amsStatus = status?.ams_status_main ?? 0;
  1058. // Track when we see non-idle state (printer is working)
  1059. if (amsStatus !== 0) {
  1060. seenBusyStateRef.current = true;
  1061. // Cancel any deferred clear since we're back to busy
  1062. if (deferredClearRef.current) {
  1063. clearTimeout(deferredClearRef.current);
  1064. deferredClearRef.current = null;
  1065. }
  1066. }
  1067. // When we've seen busy and now idle, clear (with min time check)
  1068. if (seenBusyStateRef.current && amsStatus === 0) {
  1069. if (minTimePassedRef.current) {
  1070. // Min time passed - clear now
  1071. if (refreshTimeoutRef.current) {
  1072. clearTimeout(refreshTimeoutRef.current);
  1073. }
  1074. setRefreshingSlot(null);
  1075. } else {
  1076. // Schedule clear after min time (2 seconds from start)
  1077. if (!deferredClearRef.current) {
  1078. deferredClearRef.current = setTimeout(() => {
  1079. if (refreshTimeoutRef.current) {
  1080. clearTimeout(refreshTimeoutRef.current);
  1081. }
  1082. setRefreshingSlot(null);
  1083. }, 2000);
  1084. }
  1085. }
  1086. }
  1087. return () => {
  1088. if (deferredClearRef.current) {
  1089. clearTimeout(deferredClearRef.current);
  1090. }
  1091. };
  1092. }, [status?.ams_status_main, refreshingSlot]);
  1093. // State for AMS slot menu
  1094. const [amsSlotMenu, setAmsSlotMenu] = useState<{ amsId: number; slotId: number } | null>(null);
  1095. if (shouldHide) {
  1096. return null;
  1097. }
  1098. return (
  1099. <Card className="relative">
  1100. <CardContent>
  1101. {/* Header */}
  1102. <div className={viewMode === 'compact' ? 'mb-2' : 'mb-4'}>
  1103. {/* Top row: Image, Name, Menu */}
  1104. <div className="flex items-start justify-between gap-2">
  1105. <div className="flex items-center gap-3 min-w-0 flex-1">
  1106. {/* Printer Model Image */}
  1107. <img
  1108. src={getPrinterImage(printer.model)}
  1109. alt={printer.model || 'Printer'}
  1110. className={`object-contain rounded-lg bg-bambu-dark flex-shrink-0 ${viewMode === 'compact' ? 'w-10 h-10' : 'w-14 h-14'}`}
  1111. />
  1112. <div className="min-w-0 flex-1">
  1113. <div className="flex items-center gap-2">
  1114. <h3 className={`font-semibold text-white ${viewMode === 'compact' ? 'text-base truncate' : 'text-lg'}`}>{printer.name}</h3>
  1115. {/* Connection indicator dot for compact mode */}
  1116. {viewMode === 'compact' && (
  1117. <div
  1118. className={`w-2 h-2 rounded-full flex-shrink-0 ${
  1119. status?.connected ? 'bg-bambu-green' : 'bg-red-500'
  1120. }`}
  1121. title={status?.connected ? 'Connected' : 'Offline'}
  1122. />
  1123. )}
  1124. </div>
  1125. <p className="text-sm text-bambu-gray">
  1126. {printer.model || 'Unknown Model'}
  1127. {/* Nozzle Info - only in expanded */}
  1128. {viewMode === 'expanded' && status?.nozzles && status.nozzles[0]?.nozzle_diameter && (
  1129. <span className="ml-1.5 text-bambu-gray" title={status.nozzles[0].nozzle_type || 'Nozzle'}>
  1130. • {status.nozzles[0].nozzle_diameter}mm
  1131. </span>
  1132. )}
  1133. {viewMode === 'expanded' && maintenanceInfo && maintenanceInfo.total_print_hours > 0 && (
  1134. <span className="ml-2 text-bambu-gray">
  1135. <Clock className="w-3 h-3 inline-block mr-1" />
  1136. {Math.round(maintenanceInfo.total_print_hours)}h
  1137. </span>
  1138. )}
  1139. </p>
  1140. </div>
  1141. </div>
  1142. {/* Menu button */}
  1143. <div className="relative flex-shrink-0">
  1144. <Button
  1145. variant="ghost"
  1146. size="sm"
  1147. onClick={() => setShowMenu(!showMenu)}
  1148. >
  1149. <MoreVertical className="w-4 h-4" />
  1150. </Button>
  1151. {showMenu && (
  1152. <div className="absolute right-0 mt-2 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10">
  1153. <button
  1154. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1155. onClick={() => {
  1156. setShowEditModal(true);
  1157. setShowMenu(false);
  1158. }}
  1159. >
  1160. <Pencil className="w-4 h-4" />
  1161. Edit
  1162. </button>
  1163. <button
  1164. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1165. onClick={() => {
  1166. connectMutation.mutate();
  1167. setShowMenu(false);
  1168. }}
  1169. >
  1170. <RefreshCw className="w-4 h-4" />
  1171. Reconnect
  1172. </button>
  1173. <button
  1174. className="w-full px-4 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1175. onClick={() => {
  1176. setShowMQTTDebug(true);
  1177. setShowMenu(false);
  1178. }}
  1179. >
  1180. <Terminal className="w-4 h-4" />
  1181. MQTT Debug
  1182. </button>
  1183. <button
  1184. className="w-full px-4 py-2 text-left text-sm text-red-400 hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1185. onClick={() => {
  1186. setShowDeleteConfirm(true);
  1187. setShowMenu(false);
  1188. }}
  1189. >
  1190. <Trash2 className="w-4 h-4" />
  1191. Delete
  1192. </button>
  1193. </div>
  1194. )}
  1195. </div>
  1196. </div>
  1197. {/* Badges row - only in expanded mode */}
  1198. {viewMode === 'expanded' && (
  1199. <div className="flex flex-wrap items-center gap-2 mt-2">
  1200. {/* Connection status badge */}
  1201. <span
  1202. className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs ${
  1203. status?.connected
  1204. ? 'bg-bambu-green/20 text-bambu-green'
  1205. : 'bg-red-500/20 text-red-400'
  1206. }`}
  1207. >
  1208. {status?.connected ? (
  1209. <Link className="w-3 h-3" />
  1210. ) : (
  1211. <Unlink className="w-3 h-3" />
  1212. )}
  1213. {status?.connected ? 'Connected' : 'Offline'}
  1214. </span>
  1215. {/* WiFi signal strength indicator */}
  1216. {status?.connected && wifiSignal != null && (
  1217. <span
  1218. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs ${
  1219. wifiSignal >= -50
  1220. ? 'bg-bambu-green/20 text-bambu-green'
  1221. : wifiSignal >= -60
  1222. ? 'bg-bambu-green/20 text-bambu-green'
  1223. : wifiSignal >= -70
  1224. ? 'bg-amber-500/20 text-amber-600'
  1225. : wifiSignal >= -80
  1226. ? 'bg-orange-500/20 text-orange-600'
  1227. : 'bg-red-500/20 text-red-600'
  1228. }`}
  1229. title={`WiFi: ${wifiSignal} dBm - ${getWifiStrength(wifiSignal).label}`}
  1230. >
  1231. <Signal className="w-3 h-3" />
  1232. {wifiSignal}dBm
  1233. </span>
  1234. )}
  1235. {/* HMS Status Indicator */}
  1236. {status?.connected && (() => {
  1237. const knownErrors = status.hms_errors ? filterKnownHMSErrors(status.hms_errors) : [];
  1238. return (
  1239. <button
  1240. onClick={() => setShowHMSModal(true)}
  1241. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  1242. knownErrors.length > 0
  1243. ? knownErrors.some(e => e.severity <= 2)
  1244. ? 'bg-red-500/20 text-red-400'
  1245. : 'bg-orange-500/20 text-orange-400'
  1246. : 'bg-bambu-green/20 text-bambu-green'
  1247. }`}
  1248. title="Click to view HMS errors"
  1249. >
  1250. <AlertTriangle className="w-3 h-3" />
  1251. {knownErrors.length > 0 ? knownErrors.length : 'OK'}
  1252. </button>
  1253. );
  1254. })()}
  1255. {/* Maintenance Status Indicator */}
  1256. {maintenanceInfo && (
  1257. <button
  1258. onClick={() => navigate('/maintenance')}
  1259. className={`flex items-center gap-1 px-2 py-1 rounded-full text-xs cursor-pointer hover:opacity-80 transition-opacity ${
  1260. maintenanceInfo.due_count > 0
  1261. ? 'bg-red-500/20 text-red-400'
  1262. : maintenanceInfo.warning_count > 0
  1263. ? 'bg-orange-500/20 text-orange-400'
  1264. : 'bg-bambu-green/20 text-bambu-green'
  1265. }`}
  1266. title={
  1267. maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  1268. ? `${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`
  1269. : 'All maintenance up to date - Click to view'
  1270. }
  1271. >
  1272. <Wrench className="w-3 h-3" />
  1273. {maintenanceInfo.due_count > 0 || maintenanceInfo.warning_count > 0
  1274. ? maintenanceInfo.due_count + maintenanceInfo.warning_count
  1275. : 'OK'}
  1276. </button>
  1277. )}
  1278. {/* Queue Count Badge */}
  1279. {queueCount > 0 && (
  1280. <button
  1281. onClick={() => navigate('/queue')}
  1282. className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-purple-500/20 text-purple-400 hover:opacity-80 transition-opacity"
  1283. title={`${queueCount} print${queueCount > 1 ? 's' : ''} in queue`}
  1284. >
  1285. <Layers className="w-3 h-3" />
  1286. {queueCount}
  1287. </button>
  1288. )}
  1289. </div>
  1290. )}
  1291. </div>
  1292. {/* Delete Confirmation */}
  1293. {showDeleteConfirm && (
  1294. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
  1295. <Card className="w-full max-w-md mx-4">
  1296. <CardContent>
  1297. <div className="flex items-start gap-3 mb-4">
  1298. <div className="p-2 rounded-full bg-red-500/20">
  1299. <AlertTriangle className="w-5 h-5 text-red-400" />
  1300. </div>
  1301. <div>
  1302. <h3 className="text-lg font-semibold text-white">Delete Printer</h3>
  1303. <p className="text-sm text-bambu-gray mt-1">
  1304. Are you sure you want to delete "{printer.name}"? This will remove all connection settings.
  1305. </p>
  1306. </div>
  1307. </div>
  1308. <div className="bg-bambu-dark rounded-lg p-3 mb-4">
  1309. <label className="flex items-start gap-3 cursor-pointer">
  1310. <input
  1311. type="checkbox"
  1312. checked={deleteArchives}
  1313. onChange={(e) => setDeleteArchives(e.target.checked)}
  1314. className="mt-0.5 w-4 h-4 rounded border-bambu-gray bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"
  1315. />
  1316. <div>
  1317. <span className="text-sm text-white">Delete print archives</span>
  1318. <p className="text-xs text-bambu-gray mt-0.5">
  1319. {deleteArchives
  1320. ? 'All print history for this printer will be permanently deleted.'
  1321. : 'Print history will be kept but no longer associated with this printer.'}
  1322. </p>
  1323. </div>
  1324. </label>
  1325. </div>
  1326. <div className="flex justify-end gap-2">
  1327. <Button
  1328. variant="secondary"
  1329. onClick={() => {
  1330. setShowDeleteConfirm(false);
  1331. setDeleteArchives(true);
  1332. }}
  1333. >
  1334. Cancel
  1335. </Button>
  1336. <Button
  1337. variant="danger"
  1338. onClick={() => {
  1339. deleteMutation.mutate({ deleteArchives });
  1340. setShowDeleteConfirm(false);
  1341. setDeleteArchives(true);
  1342. }}
  1343. >
  1344. Delete
  1345. </Button>
  1346. </div>
  1347. </CardContent>
  1348. </Card>
  1349. </div>
  1350. )}
  1351. {/* Status */}
  1352. {status?.connected && (
  1353. <>
  1354. {/* Compact: Simple status bar */}
  1355. {viewMode === 'compact' ? (
  1356. <div className="mt-2">
  1357. {status.state === 'RUNNING' ? (
  1358. <div className="flex items-center gap-2">
  1359. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-1.5">
  1360. <div
  1361. className="bg-bambu-green h-1.5 rounded-full transition-all"
  1362. style={{ width: `${status.progress || 0}%` }}
  1363. />
  1364. </div>
  1365. <span className="text-xs text-white">{Math.round(status.progress || 0)}%</span>
  1366. </div>
  1367. ) : (
  1368. <p className="text-xs text-bambu-gray">{getStatusDisplay(status.state, status.stg_cur_name)}</p>
  1369. )}
  1370. </div>
  1371. ) : (
  1372. /* Expanded: Full status section */
  1373. <>
  1374. {/* Current Print or Idle Placeholder */}
  1375. <div className="mb-4 p-3 bg-bambu-dark rounded-lg relative">
  1376. {/* Skip Objects button - top right corner, always visible */}
  1377. <button
  1378. onClick={() => setShowSkipObjectsModal(true)}
  1379. disabled={!(status.state === 'RUNNING' || status.state === 'PAUSE' || status.state === 'PAUSED') || (status.printable_objects_count ?? 0) < 2}
  1380. className={`absolute top-2 right-2 p-1.5 rounded transition-colors z-10 ${
  1381. (status.state === 'RUNNING' || status.state === 'PAUSE' || status.state === 'PAUSED') && (status.printable_objects_count ?? 0) >= 2
  1382. ? 'text-bambu-gray hover:text-white hover:bg-white/10'
  1383. : 'text-bambu-gray/30 cursor-not-allowed'
  1384. }`}
  1385. title={
  1386. !(status.state === 'RUNNING' || status.state === 'PAUSE' || status.state === 'PAUSED')
  1387. ? "Skip objects (only while printing)"
  1388. : (status.printable_objects_count ?? 0) >= 2
  1389. ? "Skip objects"
  1390. : "Skip objects (requires 2+ objects)"
  1391. }
  1392. >
  1393. <SkipObjectsIcon className="w-4 h-4" />
  1394. {/* Badge showing skipped count */}
  1395. {objectsData && objectsData.skipped_count > 0 && (
  1396. <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 flex items-center justify-center text-[10px] font-bold bg-red-500 text-white rounded-full">
  1397. {objectsData.skipped_count}
  1398. </span>
  1399. )}
  1400. </button>
  1401. <div className="flex gap-3">
  1402. {/* Cover Image */}
  1403. <CoverImage
  1404. url={status.state === 'RUNNING' ? status.cover_url : null}
  1405. printName={status.state === 'RUNNING' ? (status.subtask_name || status.current_print || undefined) : undefined}
  1406. />
  1407. {/* Print Info */}
  1408. <div className="flex-1 min-w-0">
  1409. {status.current_print && status.state === 'RUNNING' ? (
  1410. <>
  1411. <p className="text-sm text-bambu-gray mb-1">{status.stg_cur_name || 'Printing'}</p>
  1412. <p className="text-white text-sm mb-2 truncate">
  1413. {status.subtask_name || status.current_print}
  1414. </p>
  1415. <div className="flex items-center justify-between text-sm">
  1416. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3">
  1417. <div
  1418. className="bg-bambu-green h-2 rounded-full transition-all"
  1419. style={{ width: `${status.progress || 0}%` }}
  1420. />
  1421. </div>
  1422. <span className="text-white">{Math.round(status.progress || 0)}%</span>
  1423. </div>
  1424. <div className="flex items-center gap-3 mt-2 text-xs text-bambu-gray">
  1425. {status.remaining_time != null && status.remaining_time > 0 && (
  1426. <>
  1427. <span className="flex items-center gap-1">
  1428. <Clock className="w-3 h-3" />
  1429. {formatTime(status.remaining_time * 60)}
  1430. </span>
  1431. <span className="text-bambu-green font-medium" title="Estimated completion time">
  1432. ETA {formatETA(status.remaining_time)}
  1433. </span>
  1434. </>
  1435. )}
  1436. {status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  1437. <span className="flex items-center gap-1">
  1438. <Layers className="w-3 h-3" />
  1439. {status.layer_num}/{status.total_layers}
  1440. </span>
  1441. )}
  1442. </div>
  1443. </>
  1444. ) : (
  1445. <>
  1446. <p className="text-sm text-bambu-gray mb-1">Status</p>
  1447. <p className="text-white text-sm mb-2">
  1448. {getStatusDisplay(status.state, status.stg_cur_name)}
  1449. </p>
  1450. <div className="flex items-center justify-between text-sm">
  1451. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-2 mr-3">
  1452. <div className="bg-bambu-dark-tertiary h-2 rounded-full" />
  1453. </div>
  1454. <span className="text-bambu-gray">—</span>
  1455. </div>
  1456. {lastPrint ? (
  1457. <p className="text-xs text-bambu-gray mt-2 truncate" title={lastPrint.print_name || lastPrint.filename}>
  1458. Last: {lastPrint.print_name || lastPrint.filename}
  1459. {lastPrint.completed_at && (
  1460. <span className="ml-1 text-bambu-gray/60">
  1461. • {new Date(lastPrint.completed_at).toLocaleDateString([], { month: 'short', day: 'numeric' })}
  1462. </span>
  1463. )}
  1464. </p>
  1465. ) : (
  1466. <p className="text-xs text-bambu-gray mt-2">Ready to print</p>
  1467. )}
  1468. </>
  1469. )}
  1470. </div>
  1471. </div>
  1472. </div>
  1473. {/* Queue Widget - shows next scheduled print */}
  1474. {status.state !== 'RUNNING' && (
  1475. <PrinterQueueWidget printerId={printer.id} />
  1476. )}
  1477. </>
  1478. )}
  1479. {/* Temperatures */}
  1480. {status.temperatures && viewMode === 'expanded' && (() => {
  1481. // Use actual heater states from MQTT stream
  1482. const nozzleHeating = status.temperatures.nozzle_heating || status.temperatures.nozzle_2_heating || false;
  1483. const bedHeating = status.temperatures.bed_heating || false;
  1484. const chamberHeating = status.temperatures.chamber_heating || false;
  1485. return (
  1486. <div className="grid grid-cols-3 gap-2">
  1487. {/* Nozzle temp - combined for dual nozzle */}
  1488. <div className="text-center p-2 bg-bambu-dark rounded-lg">
  1489. <HeaterThermometer className="w-4 h-4 mx-auto mb-1" color="text-orange-400" isHeating={nozzleHeating} />
  1490. {status.temperatures.nozzle_2 !== undefined ? (
  1491. <>
  1492. <p className="text-[10px] text-bambu-gray">L / R</p>
  1493. <p className="text-xs text-white">
  1494. {Math.round(status.temperatures.nozzle || 0)}° / {Math.round(status.temperatures.nozzle_2 || 0)}°
  1495. </p>
  1496. </>
  1497. ) : (
  1498. <>
  1499. <p className="text-[10px] text-bambu-gray">Nozzle</p>
  1500. <p className="text-xs text-white">
  1501. {Math.round(status.temperatures.nozzle || 0)}°C
  1502. </p>
  1503. </>
  1504. )}
  1505. </div>
  1506. <div className="text-center p-2 bg-bambu-dark rounded-lg">
  1507. <HeaterThermometer className="w-4 h-4 mx-auto mb-1" color="text-blue-400" isHeating={bedHeating} />
  1508. <p className="text-[10px] text-bambu-gray">Bed</p>
  1509. <p className="text-xs text-white">
  1510. {Math.round(status.temperatures.bed || 0)}°C
  1511. </p>
  1512. </div>
  1513. {status.temperatures.chamber !== undefined ? (
  1514. <div className="text-center p-2 bg-bambu-dark rounded-lg">
  1515. <HeaterThermometer className="w-4 h-4 mx-auto mb-1" color="text-green-400" isHeating={chamberHeating} />
  1516. <p className="text-[10px] text-bambu-gray">Chamber</p>
  1517. <p className="text-xs text-white">
  1518. {Math.round(status.temperatures.chamber || 0)}°C
  1519. </p>
  1520. </div>
  1521. ) : (
  1522. <div /> /* Empty placeholder to maintain grid */
  1523. )}
  1524. </div>
  1525. );
  1526. })()}
  1527. {/* Controls - Fans + Print Buttons */}
  1528. {viewMode === 'expanded' && (() => {
  1529. // Determine print state for control buttons
  1530. const isRunning = status.state === 'RUNNING';
  1531. const isPaused = status.state === 'PAUSED' || status.state === 'PAUSE';
  1532. const isPrinting = isRunning || isPaused;
  1533. const isControlBusy = stopPrintMutation.isPending || pausePrintMutation.isPending || resumePrintMutation.isPending;
  1534. // Fan data
  1535. const partFan = status.cooling_fan_speed;
  1536. const auxFan = status.big_fan1_speed;
  1537. const chamberFan = status.big_fan2_speed;
  1538. return (
  1539. <div className="mt-3">
  1540. {/* Section Header */}
  1541. <div className="flex items-center gap-2 mb-2">
  1542. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  1543. Controls
  1544. </span>
  1545. <div className="flex-1 h-px bg-bambu-dark-tertiary/30" />
  1546. </div>
  1547. <div className="flex items-center justify-between gap-2">
  1548. {/* Left: Fan Status - always visible, dynamic coloring */}
  1549. <div className="flex items-center gap-2">
  1550. {/* Part Cooling Fan */}
  1551. <div
  1552. className={`flex items-center gap-1 px-1.5 py-1 rounded ${partFan && partFan > 0 ? 'bg-cyan-500/10' : 'bg-bambu-dark'}`}
  1553. title="Part Cooling Fan"
  1554. >
  1555. <Fan className={`w-3.5 h-3.5 ${partFan && partFan > 0 ? 'text-cyan-400' : 'text-bambu-gray/50'}`} />
  1556. <span className={`text-[10px] ${partFan && partFan > 0 ? 'text-cyan-400' : 'text-bambu-gray/50'}`}>
  1557. {partFan ?? 0}%
  1558. </span>
  1559. </div>
  1560. {/* Auxiliary Fan */}
  1561. <div
  1562. className={`flex items-center gap-1 px-1.5 py-1 rounded ${auxFan && auxFan > 0 ? 'bg-blue-500/10' : 'bg-bambu-dark'}`}
  1563. title="Auxiliary Fan"
  1564. >
  1565. <Wind className={`w-3.5 h-3.5 ${auxFan && auxFan > 0 ? 'text-blue-400' : 'text-bambu-gray/50'}`} />
  1566. <span className={`text-[10px] ${auxFan && auxFan > 0 ? 'text-blue-400' : 'text-bambu-gray/50'}`}>
  1567. {auxFan ?? 0}%
  1568. </span>
  1569. </div>
  1570. {/* Chamber Fan */}
  1571. <div
  1572. className={`flex items-center gap-1 px-1.5 py-1 rounded ${chamberFan && chamberFan > 0 ? 'bg-green-500/10' : 'bg-bambu-dark'}`}
  1573. title="Chamber Fan"
  1574. >
  1575. <AirVent className={`w-3.5 h-3.5 ${chamberFan && chamberFan > 0 ? 'text-green-400' : 'text-bambu-gray/50'}`} />
  1576. <span className={`text-[10px] ${chamberFan && chamberFan > 0 ? 'text-green-400' : 'text-bambu-gray/50'}`}>
  1577. {chamberFan ?? 0}%
  1578. </span>
  1579. </div>
  1580. </div>
  1581. {/* Right: Print Control Buttons */}
  1582. <div className="flex items-center gap-2">
  1583. {/* Stop button */}
  1584. <button
  1585. onClick={() => setShowStopConfirm(true)}
  1586. disabled={!isPrinting || isControlBusy}
  1587. className={`
  1588. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  1589. transition-colors
  1590. ${isPrinting
  1591. ? 'bg-red-500/20 text-red-400 hover:bg-red-500/30'
  1592. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  1593. }
  1594. `}
  1595. title="Stop print"
  1596. >
  1597. <Square className="w-3 h-3" />
  1598. Stop
  1599. </button>
  1600. {/* Pause/Resume button */}
  1601. <button
  1602. onClick={() => isPaused ? setShowResumeConfirm(true) : setShowPauseConfirm(true)}
  1603. disabled={!isPrinting || isControlBusy}
  1604. className={`
  1605. flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium
  1606. transition-colors
  1607. ${isPrinting
  1608. ? isPaused
  1609. ? 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30'
  1610. : 'bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30'
  1611. : 'bg-bambu-dark text-bambu-gray/50 cursor-not-allowed'
  1612. }
  1613. `}
  1614. title={isPaused ? 'Resume print' : 'Pause print'}
  1615. >
  1616. {isPaused ? <Play className="w-3 h-3" /> : <Pause className="w-3 h-3" />}
  1617. {isPaused ? 'Resume' : 'Pause'}
  1618. </button>
  1619. </div>
  1620. </div>
  1621. </div>
  1622. );
  1623. })()}
  1624. {/* AMS Units - 2-Column Grid Layout */}
  1625. {amsData && amsData.length > 0 && viewMode === 'expanded' && (() => {
  1626. // Separate regular AMS (4-tray) from HT AMS (1-tray)
  1627. const regularAms = amsData.filter(ams => ams.tray.length > 1);
  1628. const htAms = amsData.filter(ams => ams.tray.length === 1);
  1629. const isDualNozzle = printer.nozzle_count === 2 || status?.temperatures?.nozzle_2 !== undefined;
  1630. return (
  1631. <div className="mt-3">
  1632. {/* Section Header */}
  1633. <div className="flex items-center gap-2 mb-2">
  1634. <span className="text-[10px] uppercase tracking-wider text-bambu-gray font-medium">
  1635. Filaments
  1636. </span>
  1637. <div className="flex-1 h-px bg-bambu-dark-tertiary/30" />
  1638. </div>
  1639. {/* AMS Content */}
  1640. <div className="space-y-3">
  1641. {/* Row 1-2: Regular AMS (4-tray) in 2-column grid */}
  1642. {regularAms.length > 0 && (
  1643. <div className="grid grid-cols-2 gap-3">
  1644. {regularAms.map((ams) => {
  1645. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  1646. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  1647. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  1648. const isLeftNozzle = extruderId === 1;
  1649. const isRightNozzle = extruderId === 0;
  1650. return (
  1651. <div key={ams.id} className="p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30">
  1652. {/* Header: Label + Stats (no icon) */}
  1653. <div className="flex items-center justify-between mb-2">
  1654. <div className="flex items-center gap-1.5">
  1655. <span className="text-[10px] text-white font-medium">
  1656. {getAmsLabel(ams.id, ams.tray.length)}
  1657. </span>
  1658. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  1659. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  1660. )}
  1661. </div>
  1662. {(ams.humidity != null || ams.temp != null) && (
  1663. <div className="flex items-center gap-1.5">
  1664. {ams.humidity != null && (
  1665. <HumidityIndicator
  1666. humidity={ams.humidity}
  1667. goodThreshold={amsThresholds?.humidityGood}
  1668. fairThreshold={amsThresholds?.humidityFair}
  1669. onClick={() => setAmsHistoryModal({
  1670. amsId: ams.id,
  1671. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  1672. mode: 'humidity',
  1673. })}
  1674. compact
  1675. />
  1676. )}
  1677. {ams.temp != null && (
  1678. <TemperatureIndicator
  1679. temp={ams.temp}
  1680. goodThreshold={amsThresholds?.tempGood}
  1681. fairThreshold={amsThresholds?.tempFair}
  1682. onClick={() => setAmsHistoryModal({
  1683. amsId: ams.id,
  1684. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  1685. mode: 'temperature',
  1686. })}
  1687. compact
  1688. />
  1689. )}
  1690. </div>
  1691. )}
  1692. </div>
  1693. {/* Slots grid: 4 columns - always render 4 slots */}
  1694. <div className="grid grid-cols-4 gap-1.5">
  1695. {[0, 1, 2, 3].map((slotIdx) => {
  1696. // Find tray data for this slot (may be undefined if data incomplete)
  1697. // Use array index if available, as tray.id may not always be set
  1698. const tray = ams.tray[slotIdx] || ams.tray.find(t => t.id === slotIdx);
  1699. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  1700. const isEmpty = !tray?.tray_type;
  1701. // Check if this is the currently loaded tray
  1702. // Global tray ID = ams.id * 4 + slot index (for standard AMS)
  1703. const globalTrayId = ams.id * 4 + slotIdx;
  1704. const isActive = effectiveTrayNow === globalTrayId;
  1705. // Get cloud preset info if available
  1706. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  1707. // Build filament data for hover card
  1708. const filamentData = tray?.tray_type ? {
  1709. vendor: (tray.tray_uuid ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  1710. profile: cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  1711. colorName: getBambuColorName(tray.tray_id_name) || hexToBasicColorName(tray.tray_color),
  1712. colorHex: tray.tray_color || null,
  1713. kFactor: formatKValue(tray.k),
  1714. fillLevel: hasFillLevel ? tray.remain : null,
  1715. trayUuid: tray.tray_uuid || null,
  1716. } : null;
  1717. // Check if this specific slot is being refreshed
  1718. const isRefreshing = refreshingSlot?.amsId === ams.id &&
  1719. refreshingSlot?.slotId === slotIdx;
  1720. // Slot visual content (goes inside hover card)
  1721. const slotVisual = (
  1722. <div
  1723. className={`bg-bambu-dark-tertiary rounded p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  1724. >
  1725. <div
  1726. className="w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2"
  1727. style={{
  1728. backgroundColor: tray?.tray_color ? `#${tray.tray_color}` : (tray?.tray_type ? '#333' : 'transparent'),
  1729. borderColor: isEmpty ? '#666' : 'rgba(255,255,255,0.1)',
  1730. borderStyle: isEmpty ? 'dashed' : 'solid',
  1731. }}
  1732. />
  1733. <div className="text-[9px] text-white font-bold truncate">
  1734. {tray?.tray_type || '—'}
  1735. </div>
  1736. {/* Fill bar */}
  1737. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  1738. {hasFillLevel && tray ? (
  1739. <div
  1740. className="h-full rounded-full transition-all"
  1741. style={{
  1742. width: `${tray.remain}%`,
  1743. backgroundColor: getFillBarColor(tray.remain),
  1744. }}
  1745. />
  1746. ) : tray?.tray_type ? (
  1747. <div className="h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40" />
  1748. ) : null}
  1749. </div>
  1750. </div>
  1751. );
  1752. // Wrapper with menu button, dropdown, and loading overlay (outside hover card)
  1753. return (
  1754. <div key={slotIdx} className="relative group">
  1755. {/* Loading overlay during RFID re-read */}
  1756. {isRefreshing && (
  1757. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  1758. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  1759. </div>
  1760. )}
  1761. {/* Menu button - appears on hover, hidden when printer busy */}
  1762. {status?.state !== 'RUNNING' && (
  1763. <button
  1764. onClick={(e) => {
  1765. e.stopPropagation();
  1766. setAmsSlotMenu(
  1767. amsSlotMenu?.amsId === ams.id && amsSlotMenu?.slotId === slotIdx
  1768. ? null
  1769. : { amsId: ams.id, slotId: slotIdx }
  1770. );
  1771. }}
  1772. className="absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary"
  1773. title="Slot options"
  1774. >
  1775. <MoreVertical className="w-2.5 h-2.5 text-bambu-gray" />
  1776. </button>
  1777. )}
  1778. {/* Dropdown menu */}
  1779. {status?.state !== 'RUNNING' && amsSlotMenu?.amsId === ams.id && amsSlotMenu?.slotId === slotIdx && (
  1780. <div className="absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]">
  1781. <button
  1782. className="w-full px-3 py-1.5 text-left text-xs text-white hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1783. onClick={(e) => {
  1784. e.stopPropagation();
  1785. refreshAmsSlotMutation.mutate({ amsId: ams.id, slotId: slotIdx });
  1786. setAmsSlotMenu(null);
  1787. }}
  1788. disabled={isRefreshing}
  1789. >
  1790. <RefreshCw className={`w-3 h-3 ${isRefreshing ? 'animate-spin' : ''}`} />
  1791. Re-read RFID
  1792. </button>
  1793. </div>
  1794. )}
  1795. {/* Hover card wraps only the visual content */}
  1796. {filamentData ? (
  1797. <FilamentHoverCard
  1798. data={filamentData}
  1799. spoolman={{
  1800. enabled: spoolmanEnabled,
  1801. onLinkSpool: spoolmanEnabled && filamentData.trayUuid ? (uuid) => {
  1802. setLinkSpoolModal({
  1803. trayUuid: uuid,
  1804. trayInfo: {
  1805. type: filamentData.profile,
  1806. color: filamentData.colorHex || '',
  1807. location: `${getAmsLabel(ams.id, ams.tray.length)} Slot ${slotIdx + 1}`,
  1808. },
  1809. });
  1810. } : undefined,
  1811. }}
  1812. >
  1813. {slotVisual}
  1814. </FilamentHoverCard>
  1815. ) : (
  1816. <EmptySlotHoverCard>
  1817. {slotVisual}
  1818. </EmptySlotHoverCard>
  1819. )}
  1820. </div>
  1821. );
  1822. })}
  1823. </div>
  1824. </div>
  1825. );
  1826. })}
  1827. </div>
  1828. )}
  1829. {/* Row 3: HT AMS + External spools (same style as regular AMS, 4 across) */}
  1830. {(htAms.length > 0 || (status.vt_tray && status.vt_tray.tray_type)) && (
  1831. <div className="grid grid-cols-4 gap-3">
  1832. {/* HT AMS units - name/badge top, slot left, stats right */}
  1833. {htAms.map((ams) => {
  1834. const mappedExtruderId = amsExtruderMap[String(ams.id)];
  1835. const normalizedId = ams.id >= 128 ? ams.id - 128 : ams.id;
  1836. const extruderId = mappedExtruderId !== undefined ? mappedExtruderId : normalizedId;
  1837. const isLeftNozzle = extruderId === 1;
  1838. const isRightNozzle = extruderId === 0;
  1839. const tray = ams.tray[0];
  1840. const hasFillLevel = tray?.tray_type && tray.remain >= 0;
  1841. const isEmpty = !tray?.tray_type;
  1842. // Check if this is the currently loaded tray
  1843. // Global tray ID = ams.id * 4 + tray.id
  1844. const globalTrayId = ams.id * 4 + (tray?.id ?? 0);
  1845. const isActive = effectiveTrayNow === globalTrayId;
  1846. // Get cloud preset info if available
  1847. const cloudInfo = tray?.tray_info_idx ? filamentInfo?.[tray.tray_info_idx] : null;
  1848. // Build filament data for hover card
  1849. const filamentData = tray?.tray_type ? {
  1850. vendor: (tray.tray_uuid ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  1851. profile: cloudInfo?.name || tray.tray_sub_brands || tray.tray_type,
  1852. colorName: getBambuColorName(tray.tray_id_name) || hexToBasicColorName(tray.tray_color),
  1853. colorHex: tray.tray_color || null,
  1854. kFactor: formatKValue(tray.k),
  1855. fillLevel: hasFillLevel ? tray.remain : null,
  1856. trayUuid: tray.tray_uuid || null,
  1857. } : null;
  1858. const htSlotId = tray?.id ?? 0;
  1859. // Check if this specific slot is being refreshed
  1860. const isHtRefreshing = refreshingSlot?.amsId === ams.id &&
  1861. refreshingSlot?.slotId === htSlotId;
  1862. // Slot visual content (goes inside hover card)
  1863. const slotVisual = (
  1864. <div
  1865. className={`bg-bambu-dark-tertiary rounded p-1 text-center ${isEmpty ? 'opacity-50' : ''} ${isActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}
  1866. >
  1867. <div
  1868. className="w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2"
  1869. style={{
  1870. backgroundColor: tray?.tray_color ? `#${tray.tray_color}` : (tray?.tray_type ? '#333' : 'transparent'),
  1871. borderColor: isEmpty ? '#666' : 'rgba(255,255,255,0.1)',
  1872. borderStyle: isEmpty ? 'dashed' : 'solid',
  1873. }}
  1874. />
  1875. <div className="text-[9px] text-white font-bold truncate">
  1876. {tray?.tray_type || '—'}
  1877. </div>
  1878. {/* Fill bar */}
  1879. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  1880. {hasFillLevel ? (
  1881. <div
  1882. className="h-full rounded-full transition-all"
  1883. style={{
  1884. width: `${tray.remain}%`,
  1885. backgroundColor: getFillBarColor(tray.remain),
  1886. }}
  1887. />
  1888. ) : tray?.tray_type ? (
  1889. <div className="h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40" />
  1890. ) : null}
  1891. </div>
  1892. </div>
  1893. );
  1894. return (
  1895. <div key={ams.id} className="p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30">
  1896. {/* Row 1: Label + Nozzle */}
  1897. <div className="flex items-center gap-1 mb-2">
  1898. <span className="text-[10px] text-white font-medium">
  1899. {getAmsLabel(ams.id, ams.tray.length)}
  1900. </span>
  1901. {isDualNozzle && (isLeftNozzle || isRightNozzle) && (
  1902. <NozzleBadge side={isLeftNozzle ? 'L' : 'R'} />
  1903. )}
  1904. </div>
  1905. {/* Row 2: Slot (left) + Stats (right stacked) */}
  1906. <div className="flex gap-1.5">
  1907. {/* Slot wrapper with menu button, dropdown, and loading overlay */}
  1908. <div className="relative group flex-1">
  1909. {/* Loading overlay during RFID re-read */}
  1910. {isHtRefreshing && (
  1911. <div className="absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20">
  1912. <RefreshCw className="w-4 h-4 text-bambu-green animate-spin" />
  1913. </div>
  1914. )}
  1915. {/* Menu button - appears on hover, hidden when printer busy */}
  1916. {status?.state !== 'RUNNING' && (
  1917. <button
  1918. onClick={(e) => {
  1919. e.stopPropagation();
  1920. setAmsSlotMenu(
  1921. amsSlotMenu?.amsId === ams.id && amsSlotMenu?.slotId === htSlotId
  1922. ? null
  1923. : { amsId: ams.id, slotId: htSlotId }
  1924. );
  1925. }}
  1926. className="absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary"
  1927. title="Slot options"
  1928. >
  1929. <MoreVertical className="w-2.5 h-2.5 text-bambu-gray" />
  1930. </button>
  1931. )}
  1932. {/* Dropdown menu */}
  1933. {status?.state !== 'RUNNING' && amsSlotMenu?.amsId === ams.id && amsSlotMenu?.slotId === htSlotId && (
  1934. <div className="absolute top-full left-0 mt-1 z-50 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]">
  1935. <button
  1936. className="w-full px-3 py-1.5 text-left text-xs text-white hover:bg-bambu-dark-tertiary flex items-center gap-2"
  1937. onClick={(e) => {
  1938. e.stopPropagation();
  1939. refreshAmsSlotMutation.mutate({ amsId: ams.id, slotId: htSlotId });
  1940. setAmsSlotMenu(null);
  1941. }}
  1942. disabled={isHtRefreshing}
  1943. >
  1944. <RefreshCw className={`w-3 h-3 ${isHtRefreshing ? 'animate-spin' : ''}`} />
  1945. Re-read RFID
  1946. </button>
  1947. </div>
  1948. )}
  1949. {/* Hover card wraps only the visual content */}
  1950. {filamentData ? (
  1951. <FilamentHoverCard
  1952. data={filamentData}
  1953. spoolman={{
  1954. enabled: spoolmanEnabled,
  1955. onLinkSpool: spoolmanEnabled && filamentData.trayUuid ? (uuid) => {
  1956. setLinkSpoolModal({
  1957. trayUuid: uuid,
  1958. trayInfo: {
  1959. type: filamentData.profile,
  1960. color: filamentData.colorHex || '',
  1961. location: getAmsLabel(ams.id, ams.tray.length),
  1962. },
  1963. });
  1964. } : undefined,
  1965. }}
  1966. >
  1967. {slotVisual}
  1968. </FilamentHoverCard>
  1969. ) : (
  1970. <EmptySlotHoverCard>
  1971. {slotVisual}
  1972. </EmptySlotHoverCard>
  1973. )}
  1974. </div>
  1975. {/* Stats stacked vertically: Temp on top, Humidity below */}
  1976. {(ams.humidity != null || ams.temp != null) && (
  1977. <div className="flex flex-col justify-center gap-1 shrink-0">
  1978. {ams.temp != null && (
  1979. <TemperatureIndicator
  1980. temp={ams.temp}
  1981. goodThreshold={amsThresholds?.tempGood}
  1982. fairThreshold={amsThresholds?.tempFair}
  1983. onClick={() => setAmsHistoryModal({
  1984. amsId: ams.id,
  1985. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  1986. mode: 'temperature',
  1987. })}
  1988. compact
  1989. />
  1990. )}
  1991. {ams.humidity != null && (
  1992. <HumidityIndicator
  1993. humidity={ams.humidity}
  1994. goodThreshold={amsThresholds?.humidityGood}
  1995. fairThreshold={amsThresholds?.humidityFair}
  1996. onClick={() => setAmsHistoryModal({
  1997. amsId: ams.id,
  1998. amsLabel: getAmsLabel(ams.id, ams.tray.length),
  1999. mode: 'humidity',
  2000. })}
  2001. compact
  2002. />
  2003. )}
  2004. </div>
  2005. )}
  2006. </div>
  2007. </div>
  2008. );
  2009. })}
  2010. {/* External spool - name top, slot below (no stats) */}
  2011. {status.vt_tray && status.vt_tray.tray_type && (() => {
  2012. const extTray = status.vt_tray;
  2013. // Check if external spool is active (tray_now = 254)
  2014. const isExtActive = effectiveTrayNow === 254;
  2015. // Get cloud preset info if available
  2016. const extCloudInfo = extTray.tray_info_idx ? filamentInfo?.[extTray.tray_info_idx] : null;
  2017. // Build filament data for hover card
  2018. const extFilamentData = {
  2019. vendor: (extTray.tray_uuid ? 'Bambu Lab' : 'Generic') as 'Bambu Lab' | 'Generic',
  2020. profile: extCloudInfo?.name || extTray.tray_sub_brands || extTray.tray_type || 'Unknown',
  2021. colorName: getBambuColorName(extTray.tray_id_name) || hexToBasicColorName(extTray.tray_color),
  2022. colorHex: extTray.tray_color || null,
  2023. kFactor: formatKValue(extTray.k),
  2024. fillLevel: null, // External spool has unknown fill level
  2025. trayUuid: extTray.tray_uuid || null,
  2026. };
  2027. const extSlotContent = (
  2028. <div className={`bg-bambu-dark-tertiary rounded p-1 text-center cursor-default ${isExtActive ? 'ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark' : ''}`}>
  2029. <div
  2030. className="w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2"
  2031. style={{
  2032. backgroundColor: extTray.tray_color ? `#${extTray.tray_color}` : '#333',
  2033. borderColor: isExtActive ? 'var(--accent)' : 'rgba(255,255,255,0.1)',
  2034. }}
  2035. />
  2036. <div className="text-[9px] text-white font-bold truncate">
  2037. {extTray.tray_type || 'Spool'}
  2038. </div>
  2039. {/* Unknown fill level - subtle bar */}
  2040. <div className="mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden">
  2041. <div className="h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40" />
  2042. </div>
  2043. </div>
  2044. );
  2045. return (
  2046. <div className="p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30">
  2047. {/* Row 1: Label */}
  2048. <div className="flex items-center gap-1 mb-2">
  2049. <span className="text-[10px] text-white font-medium">External</span>
  2050. </div>
  2051. {/* Row 2: Slot (full width since no stats) */}
  2052. <FilamentHoverCard
  2053. data={extFilamentData}
  2054. spoolman={{
  2055. enabled: spoolmanEnabled,
  2056. onLinkSpool: spoolmanEnabled && extFilamentData.trayUuid ? (uuid) => {
  2057. setLinkSpoolModal({
  2058. trayUuid: uuid,
  2059. trayInfo: {
  2060. type: extFilamentData.profile,
  2061. color: extFilamentData.colorHex || '',
  2062. location: 'External Spool',
  2063. },
  2064. });
  2065. } : undefined,
  2066. }}
  2067. >
  2068. {extSlotContent}
  2069. </FilamentHoverCard>
  2070. </div>
  2071. );
  2072. })()}
  2073. </div>
  2074. )}
  2075. </div>
  2076. </div>
  2077. );
  2078. })()}
  2079. </>
  2080. )}
  2081. {/* Smart Plug Controls - hidden in compact mode */}
  2082. {smartPlug && viewMode === 'expanded' && (
  2083. <div className="mt-4 pt-4 border-t border-bambu-dark-tertiary">
  2084. <div className="flex items-center gap-3">
  2085. {/* Plug name and status */}
  2086. <div className="flex items-center gap-2 min-w-0">
  2087. <Zap className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  2088. <span className="text-sm text-white truncate">{smartPlug.name}</span>
  2089. {plugStatus && (
  2090. <span
  2091. className={`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${
  2092. plugStatus.state === 'ON'
  2093. ? 'bg-bambu-green/20 text-bambu-green'
  2094. : plugStatus.state === 'OFF'
  2095. ? 'bg-red-500/20 text-red-400'
  2096. : 'bg-bambu-gray/20 text-bambu-gray'
  2097. }`}
  2098. >
  2099. {plugStatus.state || '?'}
  2100. </span>
  2101. )}
  2102. {/* Power consumption display */}
  2103. {plugStatus?.energy?.power != null && plugStatus.state === 'ON' && (
  2104. <span className="text-xs text-yellow-400 font-medium flex-shrink-0">
  2105. {plugStatus.energy.power}W
  2106. </span>
  2107. )}
  2108. </div>
  2109. {/* Spacer */}
  2110. <div className="flex-1" />
  2111. {/* Power buttons */}
  2112. <div className="flex items-center gap-1">
  2113. <button
  2114. onClick={() => setShowPowerOnConfirm(true)}
  2115. disabled={powerControlMutation.isPending || plugStatus?.state === 'ON'}
  2116. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  2117. plugStatus?.state === 'ON'
  2118. ? 'bg-bambu-green text-white'
  2119. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary'
  2120. }`}
  2121. >
  2122. <Power className="w-3 h-3" />
  2123. On
  2124. </button>
  2125. <button
  2126. onClick={() => setShowPowerOffConfirm(true)}
  2127. disabled={powerControlMutation.isPending || plugStatus?.state === 'OFF'}
  2128. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  2129. plugStatus?.state === 'OFF'
  2130. ? 'bg-red-500/30 text-red-400'
  2131. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary'
  2132. }`}
  2133. >
  2134. <PowerOff className="w-3 h-3" />
  2135. Off
  2136. </button>
  2137. </div>
  2138. {/* Auto-off toggle */}
  2139. <div className="flex items-center gap-2 flex-shrink-0">
  2140. <span className={`text-xs hidden sm:inline ${smartPlug.auto_off_executed ? 'text-bambu-green' : 'text-bambu-gray'}`}>
  2141. {smartPlug.auto_off_executed ? 'Auto-off done' : 'Auto-off'}
  2142. </span>
  2143. <button
  2144. onClick={() => toggleAutoOffMutation.mutate(!smartPlug.auto_off)}
  2145. disabled={toggleAutoOffMutation.isPending || smartPlug.auto_off_executed}
  2146. title={smartPlug.auto_off_executed ? 'Auto-off was executed - turn printer on to reset' : 'Auto power-off after print'}
  2147. className={`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${
  2148. smartPlug.auto_off_executed
  2149. ? 'bg-bambu-green/50 cursor-not-allowed'
  2150. : smartPlug.auto_off ? 'bg-bambu-green' : 'bg-bambu-dark-tertiary'
  2151. }`}
  2152. >
  2153. <span
  2154. className={`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${
  2155. smartPlug.auto_off || smartPlug.auto_off_executed ? 'translate-x-4' : 'translate-x-0'
  2156. }`}
  2157. />
  2158. </button>
  2159. </div>
  2160. </div>
  2161. </div>
  2162. )}
  2163. {/* Connection Info & Actions - hidden in compact mode */}
  2164. {viewMode === 'expanded' && (
  2165. <div className="mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-between">
  2166. <div className="text-xs text-bambu-gray">
  2167. <p>{printer.ip_address}</p>
  2168. <p className="truncate">{printer.serial_number}</p>
  2169. </div>
  2170. <div className="flex items-center gap-2">
  2171. <Button
  2172. variant="secondary"
  2173. size="sm"
  2174. onClick={() => {
  2175. // Use saved window state or defaults
  2176. const saved = localStorage.getItem('cameraWindowState');
  2177. const state = saved ? JSON.parse(saved) : { width: 640, height: 400 };
  2178. const features = [
  2179. `width=${state.width}`,
  2180. `height=${state.height}`,
  2181. state.left !== undefined ? `left=${state.left}` : '',
  2182. state.top !== undefined ? `top=${state.top}` : '',
  2183. 'menubar=no,toolbar=no,location=no,status=no',
  2184. ].filter(Boolean).join(',');
  2185. window.open(`/camera/${printer.id}`, `camera-${printer.id}`, features);
  2186. }}
  2187. disabled={!status?.connected}
  2188. title="Open camera in new window"
  2189. >
  2190. <Video className="w-4 h-4" />
  2191. </Button>
  2192. <Button
  2193. variant="secondary"
  2194. size="sm"
  2195. onClick={() => setShowFileManager(true)}
  2196. title="Browse printer files"
  2197. >
  2198. <HardDrive className="w-4 h-4" />
  2199. Files
  2200. </Button>
  2201. </div>
  2202. </div>
  2203. )}
  2204. </CardContent>
  2205. {/* File Manager Modal */}
  2206. {showFileManager && (
  2207. <FileManagerModal
  2208. printerId={printer.id}
  2209. printerName={printer.name}
  2210. onClose={() => setShowFileManager(false)}
  2211. />
  2212. )}
  2213. {/* MQTT Debug Modal */}
  2214. {showMQTTDebug && (
  2215. <MQTTDebugModal
  2216. printerId={printer.id}
  2217. printerName={printer.name}
  2218. onClose={() => setShowMQTTDebug(false)}
  2219. />
  2220. )}
  2221. {/* Power On Confirmation */}
  2222. {showPowerOnConfirm && smartPlug && (
  2223. <ConfirmModal
  2224. title="Power On Printer"
  2225. message={`Are you sure you want to turn ON the power for "${printer.name}"?`}
  2226. confirmText="Power On"
  2227. variant="default"
  2228. onConfirm={() => {
  2229. powerControlMutation.mutate('on');
  2230. setShowPowerOnConfirm(false);
  2231. }}
  2232. onCancel={() => setShowPowerOnConfirm(false)}
  2233. />
  2234. )}
  2235. {/* Power Off Confirmation */}
  2236. {showPowerOffConfirm && smartPlug && (
  2237. <ConfirmModal
  2238. title="Power Off Printer"
  2239. message={
  2240. status?.state === 'RUNNING'
  2241. ? `WARNING: "${printer.name}" is currently printing! Are you sure you want to turn OFF the power? This will interrupt the print and may damage the printer.`
  2242. : `Are you sure you want to turn OFF the power for "${printer.name}"?`
  2243. }
  2244. confirmText="Power Off"
  2245. variant="danger"
  2246. onConfirm={() => {
  2247. powerControlMutation.mutate('off');
  2248. setShowPowerOffConfirm(false);
  2249. }}
  2250. onCancel={() => setShowPowerOffConfirm(false)}
  2251. />
  2252. )}
  2253. {/* Stop Print Confirmation */}
  2254. {showStopConfirm && (
  2255. <ConfirmModal
  2256. title="Stop Print"
  2257. message={`Are you sure you want to stop the current print on "${printer.name}"? This will cancel the print job.`}
  2258. confirmText="Stop Print"
  2259. variant="danger"
  2260. onConfirm={() => {
  2261. stopPrintMutation.mutate();
  2262. setShowStopConfirm(false);
  2263. }}
  2264. onCancel={() => setShowStopConfirm(false)}
  2265. />
  2266. )}
  2267. {/* Pause Print Confirmation */}
  2268. {showPauseConfirm && (
  2269. <ConfirmModal
  2270. title="Pause Print"
  2271. message={`Are you sure you want to pause the current print on "${printer.name}"?`}
  2272. confirmText="Pause Print"
  2273. variant="default"
  2274. onConfirm={() => {
  2275. pausePrintMutation.mutate();
  2276. setShowPauseConfirm(false);
  2277. }}
  2278. onCancel={() => setShowPauseConfirm(false)}
  2279. />
  2280. )}
  2281. {/* Resume Print Confirmation */}
  2282. {showResumeConfirm && (
  2283. <ConfirmModal
  2284. title="Resume Print"
  2285. message={`Are you sure you want to resume the print on "${printer.name}"?`}
  2286. confirmText="Resume Print"
  2287. variant="default"
  2288. onConfirm={() => {
  2289. resumePrintMutation.mutate();
  2290. setShowResumeConfirm(false);
  2291. }}
  2292. onCancel={() => setShowResumeConfirm(false)}
  2293. />
  2294. )}
  2295. {/* Skip Objects Popup */}
  2296. {showSkipObjectsModal && (
  2297. <div
  2298. className="fixed inset-0 z-50 flex items-center justify-center"
  2299. onClick={() => setShowSkipObjectsModal(false)}
  2300. onKeyDown={(e) => e.key === 'Escape' && setShowSkipObjectsModal(false)}
  2301. tabIndex={-1}
  2302. ref={(el) => el?.focus()}
  2303. >
  2304. {/* Backdrop */}
  2305. <div className="absolute inset-0 bg-black/50 z-0" />
  2306. {/* Modal */}
  2307. <div
  2308. className="relative z-10 bg-white dark:bg-bambu-dark border border-gray-200 dark:border-bambu-dark-tertiary rounded-xl shadow-2xl w-[560px] overflow-hidden"
  2309. onClick={(e) => e.stopPropagation()}
  2310. >
  2311. {/* Header */}
  2312. <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark">
  2313. <div className="flex items-center gap-2">
  2314. <SkipObjectsIcon className="w-4 h-4 text-bambu-green" />
  2315. <span className="text-sm font-medium text-gray-900 dark:text-white">Skip Objects</span>
  2316. </div>
  2317. <button
  2318. onClick={() => setShowSkipObjectsModal(false)}
  2319. className="p-1 text-gray-500 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white rounded transition-colors"
  2320. >
  2321. <X className="w-4 h-4" />
  2322. </button>
  2323. </div>
  2324. {!objectsData ? (
  2325. <div className="flex items-center justify-center py-12">
  2326. <Loader2 className="w-5 h-5 animate-spin text-bambu-gray" />
  2327. </div>
  2328. ) : objectsData.objects.length === 0 ? (
  2329. <div className="text-center py-8 px-4 text-bambu-gray">
  2330. <p className="text-sm">No objects found</p>
  2331. <p className="text-xs mt-1 opacity-70">Objects are loaded when a print starts</p>
  2332. </div>
  2333. ) : (
  2334. <div className="flex flex-col">
  2335. {/* Info Banner */}
  2336. <div className="flex items-center gap-3 px-4 py-2.5 bg-blue-50 dark:bg-blue-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary">
  2337. <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-500/20 flex items-center justify-center">
  2338. <Monitor className="w-4 h-4 text-blue-500 dark:text-blue-400" />
  2339. </div>
  2340. <div className="flex-1 min-w-0">
  2341. <p className="text-xs text-blue-600 dark:text-blue-300">Match IDs with your printer display</p>
  2342. <p className="text-[10px] text-blue-500/70 dark:text-blue-300/60">The printer screen shows object IDs on the build plate</p>
  2343. </div>
  2344. <div className="flex-shrink-0 text-xs text-gray-500 dark:text-bambu-gray">
  2345. {objectsData.skipped_count}/{objectsData.total} skipped
  2346. </div>
  2347. </div>
  2348. {/* Layer Warning */}
  2349. {(status?.layer_num ?? 0) <= 1 && (
  2350. <div className="flex items-center gap-2 px-4 py-2 bg-amber-50 dark:bg-amber-500/10 border-b border-gray-200 dark:border-bambu-dark-tertiary">
  2351. <AlertCircle className="w-4 h-4 text-amber-500 dark:text-amber-400 flex-shrink-0" />
  2352. <p className="text-xs text-amber-600 dark:text-amber-400">
  2353. Wait for layer 2+ to skip objects (currently layer {status?.layer_num ?? 0})
  2354. </p>
  2355. </div>
  2356. )}
  2357. {/* Content: Image + List side by side */}
  2358. <div className="flex">
  2359. {/* Left: Preview Image with object markers */}
  2360. <div className="w-52 flex-shrink-0 p-4 border-r border-gray-200 dark:border-bambu-dark-tertiary bg-gray-50 dark:bg-bambu-dark-secondary">
  2361. <div className="relative">
  2362. {status?.cover_url ? (
  2363. <img
  2364. src={`${status.cover_url}?view=top`}
  2365. alt="Print preview"
  2366. className="w-full aspect-square object-contain rounded-lg bg-gray-900 dark:bg-gray-900 border border-gray-300 dark:border-gray-600"
  2367. />
  2368. ) : (
  2369. <div className="w-full aspect-square rounded-lg bg-gray-100 dark:bg-bambu-dark flex items-center justify-center">
  2370. <Box className="w-8 h-8 text-gray-300 dark:text-bambu-gray/30" />
  2371. </div>
  2372. )}
  2373. {/* Object ID markers overlay - positioned based on object data */}
  2374. {objectsData.objects.length > 0 && (
  2375. <div className="absolute inset-0 pointer-events-none">
  2376. {objectsData.objects.map((obj, idx) => {
  2377. let x: number, y: number;
  2378. // Use position data if available, otherwise fall back to grid
  2379. if (obj.x != null && obj.y != null && objectsData.bbox_all) {
  2380. // bbox_all is [x_min, y_min, x_max, y_max] - the bounds of all objects
  2381. // The top_N.png image is rendered to show this area with ~10% padding
  2382. const [xMin, yMin, xMax, yMax] = objectsData.bbox_all;
  2383. const bboxWidth = xMax - xMin;
  2384. const bboxHeight = yMax - yMin;
  2385. // Calculate position relative to bbox, with padding
  2386. // The image has roughly 10% padding on each side
  2387. const padding = 10;
  2388. const contentArea = 100 - (padding * 2);
  2389. x = padding + ((obj.x - xMin) / bboxWidth) * contentArea;
  2390. // Y axis: in 3D coords Y increases toward back, in image Y increases down
  2391. // So we need to flip: high Y in 3D = low Y in image (top)
  2392. y = padding + ((yMax - obj.y) / bboxHeight) * contentArea;
  2393. // Clamp to valid range
  2394. x = Math.max(5, Math.min(95, x));
  2395. y = Math.max(5, Math.min(95, y));
  2396. } else if (obj.x != null && obj.y != null) {
  2397. // Fallback: use full build plate (256mm for X1C)
  2398. const buildPlateSize = 256;
  2399. x = Math.max(10, Math.min(90, (obj.x / buildPlateSize) * 100));
  2400. y = Math.max(10, Math.min(90, 100 - (obj.y / buildPlateSize) * 100));
  2401. } else {
  2402. // Fallback: arrange in a grid pattern over the build plate area
  2403. const cols = Math.ceil(Math.sqrt(objectsData.objects.length));
  2404. const row = Math.floor(idx / cols);
  2405. const col = idx % cols;
  2406. const rows = Math.ceil(objectsData.objects.length / cols);
  2407. x = 15 + (col * (70 / cols)) + (35 / cols);
  2408. y = 15 + (row * (70 / rows)) + (35 / rows);
  2409. }
  2410. return (
  2411. <div
  2412. key={obj.id}
  2413. className={`absolute flex items-center justify-center w-6 h-6 rounded-full text-[10px] font-bold shadow-lg ${
  2414. obj.skipped
  2415. ? 'bg-red-500 text-white line-through'
  2416. : 'bg-bambu-green text-black'
  2417. }`}
  2418. style={{
  2419. left: `${x}%`,
  2420. top: `${y}%`,
  2421. transform: 'translate(-50%, -50%)'
  2422. }}
  2423. title={obj.name}
  2424. >
  2425. {obj.id}
  2426. </div>
  2427. );
  2428. })}
  2429. </div>
  2430. )}
  2431. {/* Object count overlay */}
  2432. <div className="absolute bottom-2 right-2 px-2 py-1 bg-white/90 dark:bg-black/80 rounded text-[10px] text-gray-700 dark:text-white shadow-sm">
  2433. {objectsData.objects.filter(o => !o.skipped).length} active
  2434. </div>
  2435. </div>
  2436. </div>
  2437. {/* Right: Object List with prominent IDs */}
  2438. <div className="flex-1 min-w-0">
  2439. {objectsData.objects.map((obj) => (
  2440. <div
  2441. key={obj.id}
  2442. className={`
  2443. flex items-center gap-3 px-4 py-3 border-b border-gray-200 dark:border-bambu-dark-tertiary/50 last:border-0
  2444. ${obj.skipped ? 'bg-red-50 dark:bg-red-500/10' : 'hover:bg-gray-50 dark:hover:bg-bambu-dark/50'}
  2445. `}
  2446. >
  2447. {/* Large prominent ID badge */}
  2448. <div className={`
  2449. w-12 h-12 flex-shrink-0 rounded-lg flex flex-col items-center justify-center
  2450. ${obj.skipped
  2451. ? 'bg-red-100 dark:bg-red-500/20 border border-red-300 dark:border-red-500/40'
  2452. : 'bg-green-100 dark:bg-bambu-green/20 border border-green-300 dark:border-bambu-green/40'}
  2453. `}>
  2454. <span className={`text-lg font-mono font-bold ${obj.skipped ? 'text-red-500 dark:text-red-400' : 'text-green-600 dark:text-bambu-green'}`}>
  2455. {obj.id}
  2456. </span>
  2457. <span className={`text-[8px] uppercase tracking-wider ${obj.skipped ? 'text-red-400/60' : 'text-green-500/60 dark:text-bambu-green/60'}`}>
  2458. ID
  2459. </span>
  2460. </div>
  2461. {/* Object name and status */}
  2462. <div className="flex-1 min-w-0">
  2463. <span className={`block text-sm truncate ${obj.skipped ? 'text-red-500 dark:text-red-400 line-through' : 'text-gray-900 dark:text-white'}`}>
  2464. {obj.name}
  2465. </span>
  2466. {obj.skipped && (
  2467. <span className="text-[10px] text-red-400/60">Will be skipped</span>
  2468. )}
  2469. </div>
  2470. {/* Skip button */}
  2471. {!obj.skipped ? (
  2472. <button
  2473. onClick={() => skipObjectsMutation.mutate([obj.id])}
  2474. disabled={skipObjectsMutation.isPending || (status?.layer_num ?? 0) <= 1}
  2475. className={`px-4 py-2 text-xs font-medium rounded-lg transition-colors ${
  2476. (status?.layer_num ?? 0) <= 1
  2477. ? 'bg-gray-100 dark:bg-bambu-dark text-gray-400 dark:text-bambu-gray/50 cursor-not-allowed'
  2478. : 'bg-red-100 dark:bg-red-500/20 text-red-600 dark:text-red-400 hover:bg-red-200 dark:hover:bg-red-500/30 border border-red-300 dark:border-red-500/30'
  2479. }`}
  2480. title={(status?.layer_num ?? 0) <= 1 ? 'Wait for layer 2+' : 'Skip this object'}
  2481. >
  2482. Skip
  2483. </button>
  2484. ) : (
  2485. <span className="px-4 py-2 text-xs text-red-500 dark:text-red-400/70 bg-red-100 dark:bg-red-500/10 rounded-lg">
  2486. Skipped
  2487. </span>
  2488. )}
  2489. </div>
  2490. ))}
  2491. </div>
  2492. </div>
  2493. </div>
  2494. )}
  2495. </div>
  2496. </div>
  2497. )}
  2498. {/* HMS Error Modal */}
  2499. {showHMSModal && (
  2500. <HMSErrorModal
  2501. printerName={printer.name}
  2502. errors={status?.hms_errors || []}
  2503. onClose={() => setShowHMSModal(false)}
  2504. />
  2505. )}
  2506. {/* AMS History Modal */}
  2507. {amsHistoryModal && (
  2508. <AMSHistoryModal
  2509. isOpen={!!amsHistoryModal}
  2510. onClose={() => setAmsHistoryModal(null)}
  2511. printerId={printer.id}
  2512. printerName={printer.name}
  2513. amsId={amsHistoryModal.amsId}
  2514. amsLabel={amsHistoryModal.amsLabel}
  2515. initialMode={amsHistoryModal.mode}
  2516. thresholds={amsThresholds}
  2517. />
  2518. )}
  2519. {/* Link Spool Modal */}
  2520. {linkSpoolModal && (
  2521. <LinkSpoolModal
  2522. isOpen={!!linkSpoolModal}
  2523. onClose={() => setLinkSpoolModal(null)}
  2524. trayUuid={linkSpoolModal.trayUuid}
  2525. trayInfo={linkSpoolModal.trayInfo}
  2526. />
  2527. )}
  2528. {/* Edit Printer Modal */}
  2529. {showEditModal && (
  2530. <EditPrinterModal
  2531. printer={printer}
  2532. onClose={() => setShowEditModal(false)}
  2533. />
  2534. )}
  2535. {/* AMS Slot Menu Backdrop - closes menu when clicking outside */}
  2536. {amsSlotMenu && (
  2537. <div
  2538. className="fixed inset-0 z-40"
  2539. onClick={() => setAmsSlotMenu(null)}
  2540. />
  2541. )}
  2542. </Card>
  2543. );
  2544. }
  2545. function AddPrinterModal({
  2546. onClose,
  2547. onAdd,
  2548. existingSerials,
  2549. }: {
  2550. onClose: () => void;
  2551. onAdd: (data: PrinterCreate) => void;
  2552. existingSerials: string[];
  2553. }) {
  2554. const [form, setForm] = useState<PrinterCreate>({
  2555. name: '',
  2556. serial_number: '',
  2557. ip_address: '',
  2558. access_code: '',
  2559. model: '',
  2560. auto_archive: true,
  2561. });
  2562. // Discovery state
  2563. const [discovering, setDiscovering] = useState(false);
  2564. const [discovered, setDiscovered] = useState<DiscoveredPrinter[]>([]);
  2565. const [discoveryError, setDiscoveryError] = useState('');
  2566. const [hasScanned, setHasScanned] = useState(false);
  2567. const [isDocker, setIsDocker] = useState(false);
  2568. const [subnet, setSubnet] = useState('192.168.1.0/24');
  2569. const [scanProgress, setScanProgress] = useState({ scanned: 0, total: 0 });
  2570. // Fetch discovery info on mount
  2571. useEffect(() => {
  2572. discoveryApi.getInfo().then(info => {
  2573. setIsDocker(info.is_docker);
  2574. }).catch(() => {
  2575. // Ignore errors, assume not Docker
  2576. });
  2577. }, []);
  2578. // Filter out already-added printers
  2579. const newPrinters = discovered.filter(p => !existingSerials.includes(p.serial));
  2580. const startDiscovery = async () => {
  2581. setDiscoveryError('');
  2582. setDiscovered([]);
  2583. setDiscovering(true);
  2584. setHasScanned(false);
  2585. setScanProgress({ scanned: 0, total: 0 });
  2586. try {
  2587. if (isDocker) {
  2588. // Use subnet scanning for Docker
  2589. await discoveryApi.startSubnetScan(subnet);
  2590. // Poll for scan status and results
  2591. const pollInterval = setInterval(async () => {
  2592. try {
  2593. const status = await discoveryApi.getScanStatus();
  2594. setScanProgress({ scanned: status.scanned, total: status.total });
  2595. const printers = await discoveryApi.getDiscoveredPrinters();
  2596. setDiscovered(printers);
  2597. if (!status.running) {
  2598. clearInterval(pollInterval);
  2599. setDiscovering(false);
  2600. setHasScanned(true);
  2601. }
  2602. } catch (e) {
  2603. console.error('Failed to get scan status:', e);
  2604. }
  2605. }, 500);
  2606. } else {
  2607. // Use SSDP discovery for native installs
  2608. await discoveryApi.startDiscovery(10);
  2609. // Poll for discovered printers every second
  2610. const pollInterval = setInterval(async () => {
  2611. try {
  2612. const printers = await discoveryApi.getDiscoveredPrinters();
  2613. setDiscovered(printers);
  2614. } catch (e) {
  2615. console.error('Failed to get discovered printers:', e);
  2616. }
  2617. }, 1000);
  2618. // Stop after 10 seconds
  2619. setTimeout(async () => {
  2620. clearInterval(pollInterval);
  2621. try {
  2622. await discoveryApi.stopDiscovery();
  2623. } catch (e) {
  2624. // Ignore stop errors
  2625. }
  2626. setDiscovering(false);
  2627. setHasScanned(true);
  2628. // Final fetch
  2629. try {
  2630. const printers = await discoveryApi.getDiscoveredPrinters();
  2631. setDiscovered(printers);
  2632. } catch (e) {
  2633. console.error('Failed to get final discovered printers:', e);
  2634. }
  2635. }, 10000);
  2636. }
  2637. } catch (e) {
  2638. console.error('Failed to start discovery:', e);
  2639. setDiscoveryError(e instanceof Error ? e.message : 'Failed to start discovery');
  2640. setDiscovering(false);
  2641. setHasScanned(true);
  2642. }
  2643. };
  2644. // Map SSDP model codes to dropdown values
  2645. const mapModelCode = (ssdpModel: string | null): string => {
  2646. if (!ssdpModel) return '';
  2647. const modelMap: Record<string, string> = {
  2648. // H2 Series
  2649. 'O1D': 'H2D',
  2650. 'O1C': 'H2C',
  2651. 'O1S': 'H2S',
  2652. // X1 Series
  2653. 'BL-P001': 'X1C',
  2654. 'BL-P002': 'X1',
  2655. 'BL-P003': 'X1E',
  2656. // P Series
  2657. 'C11': 'P1S',
  2658. 'C12': 'P1P',
  2659. 'C13': 'P2S',
  2660. // A1 Series
  2661. 'N2S': 'A1',
  2662. 'N1': 'A1 Mini',
  2663. // Direct matches
  2664. 'X1C': 'X1C',
  2665. 'X1': 'X1',
  2666. 'X1E': 'X1E',
  2667. 'P1S': 'P1S',
  2668. 'P1P': 'P1P',
  2669. 'P2S': 'P2S',
  2670. 'A1': 'A1',
  2671. 'A1 Mini': 'A1 Mini',
  2672. 'H2D': 'H2D',
  2673. 'H2C': 'H2C',
  2674. 'H2S': 'H2S',
  2675. };
  2676. return modelMap[ssdpModel] || ssdpModel;
  2677. };
  2678. const selectPrinter = (printer: DiscoveredPrinter) => {
  2679. setForm({
  2680. ...form,
  2681. name: printer.name || '',
  2682. serial_number: printer.serial,
  2683. ip_address: printer.ip_address,
  2684. model: mapModelCode(printer.model),
  2685. });
  2686. // Clear discovery results after selection
  2687. setDiscovered([]);
  2688. };
  2689. // Cleanup discovery on unmount
  2690. useEffect(() => {
  2691. return () => {
  2692. discoveryApi.stopDiscovery().catch(() => {});
  2693. discoveryApi.stopSubnetScan().catch(() => {});
  2694. };
  2695. }, []);
  2696. // Close on Escape key
  2697. useEffect(() => {
  2698. const handleKeyDown = (e: KeyboardEvent) => {
  2699. if (e.key === 'Escape') onClose();
  2700. };
  2701. window.addEventListener('keydown', handleKeyDown);
  2702. return () => window.removeEventListener('keydown', handleKeyDown);
  2703. }, [onClose]);
  2704. return (
  2705. <div
  2706. className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
  2707. onClick={onClose}
  2708. >
  2709. <Card className="w-full max-w-md" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  2710. <CardContent>
  2711. <h2 className="text-xl font-semibold mb-4">Add Printer</h2>
  2712. {/* Discovery Section */}
  2713. <div className="mb-4 pb-4 border-b border-bambu-dark-tertiary">
  2714. {isDocker && (
  2715. <div className="mb-3">
  2716. <label className="block text-sm text-bambu-gray mb-1">
  2717. Subnet to scan
  2718. </label>
  2719. <input
  2720. type="text"
  2721. 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"
  2722. value={subnet}
  2723. onChange={(e) => setSubnet(e.target.value)}
  2724. placeholder="192.168.1.0/24"
  2725. disabled={discovering}
  2726. />
  2727. <p className="mt-1 text-xs text-bambu-gray">
  2728. Docker detected. Enter your printer's subnet in CIDR notation.
  2729. Requires <code className="text-bambu-green">network_mode: host</code> in docker-compose.yml.
  2730. </p>
  2731. </div>
  2732. )}
  2733. <Button
  2734. type="button"
  2735. variant="secondary"
  2736. onClick={startDiscovery}
  2737. disabled={discovering}
  2738. className="w-full"
  2739. >
  2740. {discovering ? (
  2741. <>
  2742. <Loader2 className="w-4 h-4 animate-spin" />
  2743. {isDocker && scanProgress.total > 0
  2744. ? `Scanning... ${scanProgress.scanned}/${scanProgress.total}`
  2745. : 'Scanning...'}
  2746. </>
  2747. ) : (
  2748. <>
  2749. <Search className="w-4 h-4" />
  2750. {isDocker ? 'Scan Subnet for Printers' : 'Discover Printers on Network'}
  2751. </>
  2752. )}
  2753. </Button>
  2754. {discoveryError && (
  2755. <div className="mt-2 text-sm text-red-400">{discoveryError}</div>
  2756. )}
  2757. {newPrinters.length > 0 && (
  2758. <div className="mt-3 space-y-2 max-h-40 overflow-y-auto">
  2759. {newPrinters.map((printer) => (
  2760. <div
  2761. key={printer.serial}
  2762. className="flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors"
  2763. onClick={() => selectPrinter(printer)}
  2764. >
  2765. <div className="min-w-0 flex-1">
  2766. <p className="font-medium text-white text-sm truncate">
  2767. {printer.name || printer.serial}
  2768. </p>
  2769. <p className="text-xs text-bambu-gray truncate">
  2770. {mapModelCode(printer.model) || 'Unknown'} • {printer.ip_address}
  2771. </p>
  2772. </div>
  2773. <ChevronDown className="w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2" />
  2774. </div>
  2775. ))}
  2776. </div>
  2777. )}
  2778. {discovering && (
  2779. <p className="mt-2 text-sm text-bambu-gray text-center">
  2780. {isDocker ? 'Scanning subnet for Bambu printers...' : 'Scanning network...'}
  2781. </p>
  2782. )}
  2783. {hasScanned && !discovering && discovered.length === 0 && (
  2784. <p className="mt-2 text-sm text-bambu-gray text-center">
  2785. No printers found{isDocker ? ' in the specified subnet' : ' on the network'}.
  2786. </p>
  2787. )}
  2788. {hasScanned && !discovering && discovered.length > 0 && newPrinters.length === 0 && (
  2789. <p className="mt-2 text-sm text-bambu-gray text-center">
  2790. All discovered printers are already configured.
  2791. </p>
  2792. )}
  2793. </div>
  2794. <form
  2795. onSubmit={(e) => {
  2796. e.preventDefault();
  2797. onAdd(form);
  2798. }}
  2799. className="space-y-4"
  2800. >
  2801. <div>
  2802. <label className="block text-sm text-bambu-gray mb-1">Name</label>
  2803. <input
  2804. type="text"
  2805. required
  2806. 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"
  2807. value={form.name}
  2808. onChange={(e) => setForm({ ...form, name: e.target.value })}
  2809. placeholder="My Printer"
  2810. />
  2811. </div>
  2812. <div>
  2813. <label className="block text-sm text-bambu-gray mb-1">IP Address</label>
  2814. <input
  2815. type="text"
  2816. required
  2817. pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
  2818. 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"
  2819. value={form.ip_address}
  2820. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  2821. placeholder="192.168.1.100"
  2822. />
  2823. </div>
  2824. <div>
  2825. <label className="block text-sm text-bambu-gray mb-1">Serial Number</label>
  2826. <input
  2827. type="text"
  2828. required
  2829. 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"
  2830. value={form.serial_number}
  2831. onChange={(e) => setForm({ ...form, serial_number: e.target.value })}
  2832. placeholder="01P00A000000000"
  2833. />
  2834. </div>
  2835. <div>
  2836. <label className="block text-sm text-bambu-gray mb-1">Access Code</label>
  2837. <input
  2838. type="password"
  2839. required
  2840. 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"
  2841. value={form.access_code}
  2842. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  2843. placeholder="From printer settings"
  2844. />
  2845. </div>
  2846. <div>
  2847. <label className="block text-sm text-bambu-gray mb-1">Model (optional)</label>
  2848. <select
  2849. 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"
  2850. value={form.model || ''}
  2851. onChange={(e) => setForm({ ...form, model: e.target.value })}
  2852. >
  2853. <option value="">Select model...</option>
  2854. <optgroup label="H2 Series">
  2855. <option value="H2C">H2C</option>
  2856. <option value="H2D">H2D</option>
  2857. <option value="H2S">H2S</option>
  2858. </optgroup>
  2859. <optgroup label="X1 Series">
  2860. <option value="X1E">X1E</option>
  2861. <option value="X1C">X1 Carbon</option>
  2862. <option value="X1">X1</option>
  2863. </optgroup>
  2864. <optgroup label="P Series">
  2865. <option value="P2S">P2S</option>
  2866. <option value="P1S">P1S</option>
  2867. <option value="P1P">P1P</option>
  2868. </optgroup>
  2869. <optgroup label="A1 Series">
  2870. <option value="A1">A1</option>
  2871. <option value="A1 Mini">A1 Mini</option>
  2872. </optgroup>
  2873. </select>
  2874. </div>
  2875. <div className="flex items-center gap-2">
  2876. <input
  2877. type="checkbox"
  2878. id="auto_archive"
  2879. checked={form.auto_archive}
  2880. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  2881. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  2882. />
  2883. <label htmlFor="auto_archive" className="text-sm text-bambu-gray">
  2884. Auto-archive completed prints
  2885. </label>
  2886. </div>
  2887. <div className="flex gap-3 pt-4">
  2888. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  2889. Cancel
  2890. </Button>
  2891. <Button type="submit" className="flex-1">
  2892. Add Printer
  2893. </Button>
  2894. </div>
  2895. </form>
  2896. </CardContent>
  2897. </Card>
  2898. </div>
  2899. );
  2900. }
  2901. function EditPrinterModal({
  2902. printer,
  2903. onClose,
  2904. }: {
  2905. printer: Printer;
  2906. onClose: () => void;
  2907. }) {
  2908. const queryClient = useQueryClient();
  2909. const [form, setForm] = useState({
  2910. name: printer.name,
  2911. ip_address: printer.ip_address,
  2912. access_code: '',
  2913. model: printer.model || '',
  2914. location: printer.location || '',
  2915. auto_archive: printer.auto_archive,
  2916. });
  2917. const updateMutation = useMutation({
  2918. mutationFn: (data: Partial<PrinterCreate>) => api.updatePrinter(printer.id, data),
  2919. onSuccess: () => {
  2920. queryClient.invalidateQueries({ queryKey: ['printers'] });
  2921. queryClient.invalidateQueries({ queryKey: ['printerStatus', printer.id] });
  2922. onClose();
  2923. },
  2924. });
  2925. // Close on Escape key
  2926. useEffect(() => {
  2927. const handleKeyDown = (e: KeyboardEvent) => {
  2928. if (e.key === 'Escape') onClose();
  2929. };
  2930. window.addEventListener('keydown', handleKeyDown);
  2931. return () => window.removeEventListener('keydown', handleKeyDown);
  2932. }, [onClose]);
  2933. const handleSubmit = (e: React.FormEvent) => {
  2934. e.preventDefault();
  2935. const data: Partial<PrinterCreate> = {
  2936. name: form.name,
  2937. ip_address: form.ip_address,
  2938. model: form.model || undefined,
  2939. location: form.location || undefined,
  2940. auto_archive: form.auto_archive,
  2941. };
  2942. // Only include access_code if it was changed
  2943. if (form.access_code) {
  2944. data.access_code = form.access_code;
  2945. }
  2946. updateMutation.mutate(data);
  2947. };
  2948. return (
  2949. <div
  2950. className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
  2951. onClick={onClose}
  2952. >
  2953. <Card className="w-full max-w-md" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
  2954. <CardContent>
  2955. <h2 className="text-xl font-semibold mb-4">Edit Printer</h2>
  2956. <form onSubmit={handleSubmit} className="space-y-4">
  2957. <div>
  2958. <label className="block text-sm text-bambu-gray mb-1">Name</label>
  2959. <input
  2960. type="text"
  2961. required
  2962. 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"
  2963. value={form.name}
  2964. onChange={(e) => setForm({ ...form, name: e.target.value })}
  2965. placeholder="My Printer"
  2966. />
  2967. </div>
  2968. <div>
  2969. <label className="block text-sm text-bambu-gray mb-1">IP Address</label>
  2970. <input
  2971. type="text"
  2972. required
  2973. pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
  2974. 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"
  2975. value={form.ip_address}
  2976. onChange={(e) => setForm({ ...form, ip_address: e.target.value })}
  2977. placeholder="192.168.1.100"
  2978. />
  2979. </div>
  2980. <div>
  2981. <label className="block text-sm text-bambu-gray mb-1">Serial Number</label>
  2982. <input
  2983. type="text"
  2984. disabled
  2985. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed"
  2986. value={printer.serial_number}
  2987. />
  2988. <p className="text-xs text-bambu-gray mt-1">Serial number cannot be changed</p>
  2989. </div>
  2990. <div>
  2991. <label className="block text-sm text-bambu-gray mb-1">Access Code</label>
  2992. <input
  2993. type="password"
  2994. 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"
  2995. value={form.access_code}
  2996. onChange={(e) => setForm({ ...form, access_code: e.target.value })}
  2997. placeholder="Leave empty to keep current"
  2998. />
  2999. </div>
  3000. <div>
  3001. <label className="block text-sm text-bambu-gray mb-1">Model</label>
  3002. <select
  3003. 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"
  3004. value={form.model}
  3005. onChange={(e) => setForm({ ...form, model: e.target.value })}
  3006. >
  3007. <option value="">Select model...</option>
  3008. <optgroup label="H2 Series">
  3009. <option value="H2C">H2C</option>
  3010. <option value="H2D">H2D</option>
  3011. <option value="H2S">H2S</option>
  3012. </optgroup>
  3013. <optgroup label="X1 Series">
  3014. <option value="X1E">X1E</option>
  3015. <option value="X1C">X1 Carbon</option>
  3016. <option value="X1">X1</option>
  3017. </optgroup>
  3018. <optgroup label="P Series">
  3019. <option value="P2S">P2S</option>
  3020. <option value="P1S">P1S</option>
  3021. <option value="P1P">P1P</option>
  3022. </optgroup>
  3023. <optgroup label="A1 Series">
  3024. <option value="A1">A1</option>
  3025. <option value="A1 Mini">A1 Mini</option>
  3026. </optgroup>
  3027. </select>
  3028. </div>
  3029. <div>
  3030. <label className="block text-sm text-bambu-gray mb-1">Location / Group</label>
  3031. <input
  3032. type="text"
  3033. 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"
  3034. value={form.location}
  3035. onChange={(e) => setForm({ ...form, location: e.target.value })}
  3036. placeholder="e.g., Workshop, Office, Basement"
  3037. />
  3038. <p className="text-xs text-bambu-gray mt-1">Used to group printers on the dashboard</p>
  3039. </div>
  3040. <div className="flex items-center gap-2">
  3041. <input
  3042. type="checkbox"
  3043. id="edit_auto_archive"
  3044. checked={form.auto_archive}
  3045. onChange={(e) => setForm({ ...form, auto_archive: e.target.checked })}
  3046. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  3047. />
  3048. <label htmlFor="edit_auto_archive" className="text-sm text-bambu-gray">
  3049. Auto-archive completed prints
  3050. </label>
  3051. </div>
  3052. <div className="flex gap-3 pt-4">
  3053. <Button type="button" variant="secondary" onClick={onClose} className="flex-1">
  3054. Cancel
  3055. </Button>
  3056. <Button type="submit" className="flex-1" disabled={updateMutation.isPending}>
  3057. {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
  3058. </Button>
  3059. </div>
  3060. </form>
  3061. </CardContent>
  3062. </Card>
  3063. </div>
  3064. );
  3065. }
  3066. // Component to check if a printer is offline (for power dropdown)
  3067. function usePrinterOfflineStatus(printerId: number) {
  3068. const { data: status } = useQuery({
  3069. queryKey: ['printerStatus', printerId],
  3070. queryFn: () => api.getPrinterStatus(printerId),
  3071. refetchInterval: 30000,
  3072. });
  3073. return !status?.connected;
  3074. }
  3075. // Power dropdown item for an offline printer
  3076. function PowerDropdownItem({
  3077. printer,
  3078. plug,
  3079. onPowerOn,
  3080. isPowering,
  3081. }: {
  3082. printer: Printer;
  3083. plug: { id: number; name: string };
  3084. onPowerOn: (plugId: number) => void;
  3085. isPowering: boolean;
  3086. }) {
  3087. const isOffline = usePrinterOfflineStatus(printer.id);
  3088. // Fetch plug status
  3089. const { data: plugStatus } = useQuery({
  3090. queryKey: ['smartPlugStatus', plug.id],
  3091. queryFn: () => api.getSmartPlugStatus(plug.id),
  3092. refetchInterval: 10000,
  3093. });
  3094. // Only show if printer is offline
  3095. if (!isOffline) {
  3096. return null;
  3097. }
  3098. return (
  3099. <div className="flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary">
  3100. <div className="flex items-center gap-2 min-w-0">
  3101. <span className="text-sm text-gray-900 dark:text-white truncate">{printer.name}</span>
  3102. {plugStatus && (
  3103. <span
  3104. className={`text-xs px-1.5 py-0.5 rounded ${
  3105. plugStatus.state === 'ON'
  3106. ? 'bg-bambu-green/20 text-bambu-green'
  3107. : 'bg-red-500/20 text-red-400'
  3108. }`}
  3109. >
  3110. {plugStatus.state || '?'}
  3111. </span>
  3112. )}
  3113. </div>
  3114. <button
  3115. onClick={() => onPowerOn(plug.id)}
  3116. disabled={isPowering || plugStatus?.state === 'ON'}
  3117. className={`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${
  3118. plugStatus?.state === 'ON'
  3119. ? 'bg-bambu-green/20 text-bambu-green cursor-default'
  3120. : 'bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white'
  3121. }`}
  3122. >
  3123. <Power className="w-3 h-3" />
  3124. {isPowering ? '...' : 'On'}
  3125. </button>
  3126. </div>
  3127. );
  3128. }
  3129. export function PrintersPage() {
  3130. const [showAddModal, setShowAddModal] = useState(false);
  3131. const [hideDisconnected, setHideDisconnected] = useState(() => {
  3132. return localStorage.getItem('hideDisconnectedPrinters') === 'true';
  3133. });
  3134. const [showPowerDropdown, setShowPowerDropdown] = useState(false);
  3135. const [poweringOn, setPoweringOn] = useState<number | null>(null);
  3136. const [sortBy, setSortBy] = useState<SortOption>(() => {
  3137. return (localStorage.getItem('printerSortBy') as SortOption) || 'name';
  3138. });
  3139. const [sortAsc, setSortAsc] = useState<boolean>(() => {
  3140. return localStorage.getItem('printerSortAsc') !== 'false';
  3141. });
  3142. const [viewMode, setViewMode] = useState<ViewMode>(() => {
  3143. return (localStorage.getItem('printerViewMode') as ViewMode) || 'expanded';
  3144. });
  3145. const queryClient = useQueryClient();
  3146. const { data: printers, isLoading } = useQuery({
  3147. queryKey: ['printers'],
  3148. queryFn: api.getPrinters,
  3149. });
  3150. // Fetch app settings for AMS thresholds
  3151. const { data: settings } = useQuery({
  3152. queryKey: ['settings'],
  3153. queryFn: api.getSettings,
  3154. });
  3155. // Fetch all smart plugs to know which printers have them
  3156. const { data: smartPlugs } = useQuery({
  3157. queryKey: ['smart-plugs'],
  3158. queryFn: api.getSmartPlugs,
  3159. });
  3160. // Fetch maintenance overview for all printers to show badges
  3161. const { data: maintenanceOverview } = useQuery({
  3162. queryKey: ['maintenanceOverview'],
  3163. queryFn: api.getMaintenanceOverview,
  3164. staleTime: 60 * 1000, // 1 minute
  3165. });
  3166. // Fetch Spoolman status to enable link spool feature
  3167. const { data: spoolmanStatus } = useQuery({
  3168. queryKey: ['spoolman-status'],
  3169. queryFn: api.getSpoolmanStatus,
  3170. staleTime: 60 * 1000, // 1 minute
  3171. });
  3172. const spoolmanEnabled = spoolmanStatus?.enabled && spoolmanStatus?.connected;
  3173. // Create a map of printer_id -> maintenance info for quick lookup
  3174. const maintenanceByPrinter = maintenanceOverview?.reduce(
  3175. (acc, overview) => {
  3176. acc[overview.printer_id] = {
  3177. due_count: overview.due_count,
  3178. warning_count: overview.warning_count,
  3179. total_print_hours: overview.total_print_hours,
  3180. };
  3181. return acc;
  3182. },
  3183. {} as Record<number, PrinterMaintenanceInfo>
  3184. ) || {};
  3185. // Create a map of printer_id -> smart plug
  3186. const smartPlugByPrinter = smartPlugs?.reduce(
  3187. (acc, plug) => {
  3188. if (plug.printer_id) {
  3189. acc[plug.printer_id] = plug;
  3190. }
  3191. return acc;
  3192. },
  3193. {} as Record<number, typeof smartPlugs[0]>
  3194. ) || {};
  3195. const addMutation = useMutation({
  3196. mutationFn: api.createPrinter,
  3197. onSuccess: () => {
  3198. queryClient.invalidateQueries({ queryKey: ['printers'] });
  3199. setShowAddModal(false);
  3200. },
  3201. });
  3202. const powerOnMutation = useMutation({
  3203. mutationFn: (plugId: number) => api.controlSmartPlug(plugId, 'on'),
  3204. onSuccess: () => {
  3205. queryClient.invalidateQueries({ queryKey: ['smart-plugs'] });
  3206. setPoweringOn(null);
  3207. },
  3208. onError: () => {
  3209. setPoweringOn(null);
  3210. },
  3211. });
  3212. const toggleHideDisconnected = () => {
  3213. const newValue = !hideDisconnected;
  3214. setHideDisconnected(newValue);
  3215. localStorage.setItem('hideDisconnectedPrinters', String(newValue));
  3216. };
  3217. const handleSortChange = (newSort: SortOption) => {
  3218. setSortBy(newSort);
  3219. localStorage.setItem('printerSortBy', newSort);
  3220. };
  3221. const toggleSortDirection = () => {
  3222. const newAsc = !sortAsc;
  3223. setSortAsc(newAsc);
  3224. localStorage.setItem('printerSortAsc', String(newAsc));
  3225. };
  3226. const toggleViewMode = () => {
  3227. const newMode = viewMode === 'expanded' ? 'compact' : 'expanded';
  3228. setViewMode(newMode);
  3229. localStorage.setItem('printerViewMode', newMode);
  3230. };
  3231. // Sort printers based on selected option
  3232. const sortedPrinters = useMemo(() => {
  3233. if (!printers) return [];
  3234. const sorted = [...printers];
  3235. switch (sortBy) {
  3236. case 'name':
  3237. sorted.sort((a, b) => a.name.localeCompare(b.name));
  3238. break;
  3239. case 'model':
  3240. sorted.sort((a, b) => (a.model || '').localeCompare(b.model || ''));
  3241. break;
  3242. case 'location':
  3243. // Sort by location, with ungrouped printers last
  3244. sorted.sort((a, b) => {
  3245. const locA = a.location || '';
  3246. const locB = b.location || '';
  3247. if (!locA && locB) return 1;
  3248. if (locA && !locB) return -1;
  3249. return locA.localeCompare(locB) || a.name.localeCompare(b.name);
  3250. });
  3251. break;
  3252. case 'status':
  3253. // Sort by status: printing > idle > offline
  3254. sorted.sort((a, b) => {
  3255. const statusA = queryClient.getQueryData<{ connected: boolean; state: string | null }>(['printerStatus', a.id]);
  3256. const statusB = queryClient.getQueryData<{ connected: boolean; state: string | null }>(['printerStatus', b.id]);
  3257. const getPriority = (s: typeof statusA) => {
  3258. if (!s?.connected) return 2; // offline
  3259. if (s.state === 'RUNNING') return 0; // printing
  3260. return 1; // idle
  3261. };
  3262. return getPriority(statusA) - getPriority(statusB);
  3263. });
  3264. break;
  3265. }
  3266. // Apply ascending/descending
  3267. if (!sortAsc) {
  3268. sorted.reverse();
  3269. }
  3270. return sorted;
  3271. }, [printers, sortBy, sortAsc, queryClient]);
  3272. // Group printers by location when sorted by location
  3273. const groupedPrinters = useMemo(() => {
  3274. if (sortBy !== 'location') return null;
  3275. const groups: Record<string, typeof sortedPrinters> = {};
  3276. sortedPrinters.forEach(printer => {
  3277. const location = printer.location || 'Ungrouped';
  3278. if (!groups[location]) groups[location] = [];
  3279. groups[location].push(printer);
  3280. });
  3281. return groups;
  3282. }, [sortBy, sortedPrinters]);
  3283. return (
  3284. <div className="p-4 md:p-8">
  3285. <div className="flex items-center justify-between mb-6">
  3286. <div>
  3287. <h1 className="text-2xl font-bold text-white">Printers</h1>
  3288. <StatusSummaryBar printers={printers} />
  3289. </div>
  3290. <div className="flex items-center gap-3">
  3291. {/* Sort dropdown */}
  3292. <div className="flex items-center gap-1">
  3293. <select
  3294. value={sortBy}
  3295. onChange={(e) => handleSortChange(e.target.value as SortOption)}
  3296. className="text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none"
  3297. >
  3298. <option value="name">Name</option>
  3299. <option value="status">Status</option>
  3300. <option value="model">Model</option>
  3301. <option value="location">Location</option>
  3302. </select>
  3303. <button
  3304. onClick={toggleSortDirection}
  3305. className="p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  3306. title={sortAsc ? 'Sort descending' : 'Sort ascending'}
  3307. >
  3308. {sortAsc ? (
  3309. <ArrowUp className="w-4 h-4 text-bambu-gray" />
  3310. ) : (
  3311. <ArrowDown className="w-4 h-4 text-bambu-gray" />
  3312. )}
  3313. </button>
  3314. </div>
  3315. {/* View mode toggle */}
  3316. <button
  3317. onClick={toggleViewMode}
  3318. className="p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors"
  3319. title={viewMode === 'expanded' ? 'Switch to compact view' : 'Switch to expanded view'}
  3320. >
  3321. {viewMode === 'expanded' ? (
  3322. <LayoutList className="w-5 h-5 text-bambu-gray" />
  3323. ) : (
  3324. <LayoutGrid className="w-5 h-5 text-bambu-gray" />
  3325. )}
  3326. </button>
  3327. <div className="w-px h-6 bg-bambu-dark-tertiary" />
  3328. <label className="flex items-center gap-2 text-sm text-bambu-gray cursor-pointer">
  3329. <input
  3330. type="checkbox"
  3331. checked={hideDisconnected}
  3332. onChange={toggleHideDisconnected}
  3333. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  3334. />
  3335. Hide offline
  3336. </label>
  3337. {/* Power dropdown for offline printers with smart plugs */}
  3338. {hideDisconnected && Object.keys(smartPlugByPrinter).length > 0 && (
  3339. <div className="relative">
  3340. <button
  3341. onClick={() => setShowPowerDropdown(!showPowerDropdown)}
  3342. className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors"
  3343. >
  3344. <Power className="w-4 h-4" />
  3345. Power On
  3346. <ChevronDown className={`w-3 h-3 transition-transform ${showPowerDropdown ? 'rotate-180' : ''}`} />
  3347. </button>
  3348. {showPowerDropdown && (
  3349. <>
  3350. {/* Backdrop to close dropdown */}
  3351. <div
  3352. className="fixed inset-0 z-10"
  3353. onClick={() => setShowPowerDropdown(false)}
  3354. />
  3355. <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">
  3356. <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">
  3357. Offline printers with smart plugs
  3358. </div>
  3359. {printers?.filter(p => smartPlugByPrinter[p.id]).map(printer => (
  3360. <PowerDropdownItem
  3361. key={printer.id}
  3362. printer={printer}
  3363. plug={smartPlugByPrinter[printer.id]}
  3364. onPowerOn={(plugId) => {
  3365. setPoweringOn(plugId);
  3366. powerOnMutation.mutate(plugId);
  3367. }}
  3368. isPowering={poweringOn === smartPlugByPrinter[printer.id]?.id}
  3369. />
  3370. ))}
  3371. {printers?.filter(p => smartPlugByPrinter[p.id]).length === 0 && (
  3372. <div className="px-3 py-2 text-sm text-bambu-gray">
  3373. No printers with smart plugs
  3374. </div>
  3375. )}
  3376. </div>
  3377. </>
  3378. )}
  3379. </div>
  3380. )}
  3381. <Button onClick={() => setShowAddModal(true)}>
  3382. <Plus className="w-4 h-4" />
  3383. Add Printer
  3384. </Button>
  3385. </div>
  3386. </div>
  3387. {isLoading ? (
  3388. <div className="text-center py-12 text-bambu-gray">Loading printers...</div>
  3389. ) : printers?.length === 0 ? (
  3390. <Card>
  3391. <CardContent className="text-center py-12">
  3392. <p className="text-bambu-gray mb-4">No printers configured yet</p>
  3393. <Button onClick={() => setShowAddModal(true)}>
  3394. <Plus className="w-4 h-4" />
  3395. Add Your First Printer
  3396. </Button>
  3397. </CardContent>
  3398. </Card>
  3399. ) : groupedPrinters ? (
  3400. /* Grouped by location view */
  3401. <div className="space-y-6">
  3402. {Object.entries(groupedPrinters).map(([location, locationPrinters]) => (
  3403. <div key={location}>
  3404. <h2 className="text-lg font-semibold text-white mb-3 flex items-center gap-2">
  3405. <span className="w-2 h-2 rounded-full bg-bambu-green" />
  3406. {location}
  3407. <span className="text-sm font-normal text-bambu-gray">({locationPrinters.length})</span>
  3408. </h2>
  3409. <div className={`grid gap-4 ${
  3410. viewMode === 'compact'
  3411. ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4'
  3412. : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'
  3413. }`}>
  3414. {locationPrinters.map((printer) => (
  3415. <PrinterCard
  3416. key={printer.id}
  3417. printer={printer}
  3418. hideIfDisconnected={hideDisconnected}
  3419. maintenanceInfo={maintenanceByPrinter[printer.id]}
  3420. viewMode={viewMode}
  3421. amsThresholds={settings ? {
  3422. humidityGood: Number(settings.ams_humidity_good) || 40,
  3423. humidityFair: Number(settings.ams_humidity_fair) || 60,
  3424. tempGood: Number(settings.ams_temp_good) || 28,
  3425. tempFair: Number(settings.ams_temp_fair) || 35,
  3426. } : undefined}
  3427. spoolmanEnabled={spoolmanEnabled}
  3428. />
  3429. ))}
  3430. </div>
  3431. </div>
  3432. ))}
  3433. </div>
  3434. ) : (
  3435. /* Regular grid view */
  3436. <div className={`grid gap-4 ${
  3437. viewMode === 'compact'
  3438. ? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4'
  3439. : 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'
  3440. }`}>
  3441. {sortedPrinters.map((printer) => (
  3442. <PrinterCard
  3443. key={printer.id}
  3444. printer={printer}
  3445. hideIfDisconnected={hideDisconnected}
  3446. maintenanceInfo={maintenanceByPrinter[printer.id]}
  3447. viewMode={viewMode}
  3448. spoolmanEnabled={spoolmanEnabled}
  3449. amsThresholds={settings ? {
  3450. humidityGood: Number(settings.ams_humidity_good) || 40,
  3451. humidityFair: Number(settings.ams_humidity_fair) || 60,
  3452. tempGood: Number(settings.ams_temp_good) || 28,
  3453. tempFair: Number(settings.ams_temp_fair) || 35,
  3454. } : undefined}
  3455. />
  3456. ))}
  3457. </div>
  3458. )}
  3459. {showAddModal && (
  3460. <AddPrinterModal
  3461. onClose={() => setShowAddModal(false)}
  3462. onAdd={(data) => addMutation.mutate(data)}
  3463. existingSerials={printers?.map(p => p.serial_number) || []}
  3464. />
  3465. )}
  3466. </div>
  3467. );
  3468. }