PrintersPage.tsx 160 KB

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