QueuePage.tsx 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454
  1. import { useState, useMemo, useEffect, useCallback } from 'react';
  2. import { bulkUpdateToast } from '../utils/queueBulkUpdate';
  3. import { useTranslation } from 'react-i18next';
  4. import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query';
  5. import { Link } from 'react-router-dom';
  6. import {
  7. DndContext,
  8. DragOverlay,
  9. closestCenter,
  10. KeyboardSensor,
  11. PointerSensor,
  12. useSensor,
  13. useSensors,
  14. } from '@dnd-kit/core';
  15. import type { DragEndEvent, DragStartEvent } from '@dnd-kit/core';
  16. import {
  17. SortableContext,
  18. sortableKeyboardCoordinates,
  19. useSortable,
  20. verticalListSortingStrategy,
  21. } from '@dnd-kit/sortable';
  22. import { CSS } from '@dnd-kit/utilities';
  23. import { queueItemDisplayName } from '../utils/queueItemName';
  24. import { queueItemThumbnailUrl } from '../utils/queueItemThumbnail';
  25. import {
  26. Clock,
  27. Trash2,
  28. Play,
  29. X,
  30. CheckCircle,
  31. XCircle,
  32. AlertCircle,
  33. Calendar,
  34. Printer,
  35. GripVertical,
  36. SkipForward,
  37. ExternalLink,
  38. Power,
  39. StopCircle,
  40. Pencil,
  41. RefreshCw,
  42. Timer,
  43. ListOrdered,
  44. Layers,
  45. ArrowUp,
  46. ArrowDown,
  47. Hand,
  48. Check,
  49. CheckSquare,
  50. Square,
  51. User,
  52. Pause,
  53. Weight,
  54. ChevronDown,
  55. ChevronRight,
  56. ChevronUp,
  57. List,
  58. GanttChart,
  59. Code,
  60. Snail,
  61. Package,
  62. PackageOpen,
  63. Ungroup,
  64. Ban,
  65. PlayCircle,
  66. Workflow,
  67. ThumbsUp,
  68. } from 'lucide-react';
  69. import { api, ApiError } from '../api/client';
  70. import { PipelineRunsView } from './PipelineRunsPage';
  71. import { type TimeFormat, formatETA, formatDuration, formatRelativeTime, parseUTCDate } from '../utils/date';
  72. import { getBedTypeInfo } from '../utils/bedType';
  73. import { getColorName } from '../utils/colors';
  74. import { productLineOf, useFilamentNameByIdx } from '../components/PrintModal/useFilamentLabels';
  75. import type { PrintQueueItem, PrintQueueBulkUpdate, Permission, CalibrationMode, PrinterStatus, SlotSpoolIdentity } from '../api/client';
  76. import { formatSlotLabel, getEmptySlotKind } from '../utils/amsHelpers';
  77. import type { PlateMetadata } from '../types/plates';
  78. import { Card } from '../components/Card';
  79. import { FilamentSwatch } from '../components/FilamentSwatch';
  80. import { Button } from '../components/Button';
  81. import { ConfirmModal } from '../components/ConfirmModal';
  82. import { PrintModal } from '../components/PrintModal';
  83. import { useToast } from '../contexts/ToastContext';
  84. import { useAuth } from '../contexts/AuthContext';
  85. import { QueueStatsBar } from '../components/QueueStatsBar';
  86. import { CompactHistoryRow } from '../components/CompactHistoryRow';
  87. import { QueueTimelineView } from '../components/QueueTimelineView';
  88. import { compareQueueOrder } from '../utils/queueOrder';
  89. import { BatchOrdersView } from '../components/BatchOrdersView';
  90. import { buildLoadedFilaments, type LoadedFilament } from '../hooks/useFilamentMapping';
  91. import { hasGcodeSnippets, useUiSettings } from '../hooks/useUiSettings';
  92. // The scheduler's MODEL_GATE_WAIT_REASON (print_scheduler.py).
  93. const MODEL_GATE_WAIT_REASON = 'The last print failed on every free matching printer';
  94. type QueueFilamentDisplay = {
  95. slotId: number;
  96. type: string;
  97. color: string;
  98. colorName: string;
  99. slotLabel?: string;
  100. spoolName?: string;
  101. extraColors?: string;
  102. effectType?: string;
  103. subtype?: string;
  104. /** The stored mapping names a slot the printer reports as empty. */
  105. emptySlot?: boolean;
  106. };
  107. /**
  108. * Slot label for a mapped tray the printer positively reports as empty.
  109. *
  110. * The scheduler dispatches a stored mapping as-is, so a spool unloaded after
  111. * queueing leaves the job pointed at an empty slot. Returns undefined when the
  112. * status doesn't describe that slot (offline, still loading, unit removed) or
  113. * when the slot may still hold an unconfigured spool (a non-RFID spool has no
  114. * tray_type either, #2527), so the card only warns on a positive finding.
  115. */
  116. function emptyMappedSlotLabel(status: PrinterStatus | undefined, trayId: number): string | undefined {
  117. // The external holder reports no presence signal (the status route sends
  118. // vt_tray without state / exists), so its emptiness can't be confirmed.
  119. if (!status?.connected || trayId >= 254) return undefined;
  120. const isHt = trayId >= 128;
  121. const amsId = isHt ? trayId : Math.floor(trayId / 4);
  122. const slot = isHt ? 0 : trayId % 4;
  123. const unit = status.ams?.find((ams) => ams.id === amsId);
  124. const tray = isHt ? unit?.tray[0] : unit?.tray.find((candidate) => candidate.id === slot);
  125. if (getEmptySlotKind(tray) !== 'physical') return undefined;
  126. return formatSlotLabel(amsId, slot, isHt, false);
  127. }
  128. /**
  129. * The backup tray each mapped tray handed over to during the running print.
  130. *
  131. * With AMS Filament Backup on, a spool that runs out is replaced by an identical
  132. * one in another slot, and the job's stored mapping still names the empty slot.
  133. * The printer's tray log shows the switch: a tray the mapping doesn't name, right
  134. * after the tray it took over from. A backup that runs out in turn hands over
  135. * again, so the chain resolves to the slot the mapping named.
  136. */
  137. function backupTrays(mapping: number[] | null | undefined, log: [number, number][] | undefined): Map<number, number> {
  138. const backups = new Map<number, number>();
  139. if (!mapping?.length || !log?.length) return backups;
  140. const mapped = new Set(mapping.filter((tray) => tray >= 0));
  141. // Backup tray -> the mapped tray it stands in for.
  142. const standsInFor = new Map<number, number>();
  143. let previous: number | undefined;
  144. for (const [tray] of log) {
  145. if (previous !== undefined && !mapped.has(tray) && !standsInFor.has(tray)) {
  146. const original = mapped.has(previous) ? previous : standsInFor.get(previous);
  147. if (original !== undefined) {
  148. standsInFor.set(tray, original);
  149. backups.set(original, tray);
  150. }
  151. }
  152. previous = tray;
  153. }
  154. return backups;
  155. }
  156. function queueFilamentLabel(filament: QueueFilamentDisplay): string {
  157. return filament.slotLabel
  158. ? [
  159. filament.slotLabel,
  160. filament.spoolName || filament.type,
  161. filament.colorName,
  162. ].filter(Boolean).join(' · ')
  163. : filament.colorName;
  164. }
  165. /**
  166. * Resolve the filament colours a queued job is actually configured to use.
  167. *
  168. * Plate metadata is the source of truth for which 3MF slots the selected plate
  169. * consumes. A queue-level override replaces only its matching slot, so a
  170. * multi-colour job can mix original 3MF colours and user-selected overrides
  171. * without losing either (#3132).
  172. */
  173. function resolveQueueFilaments(
  174. item: PrintQueueItem,
  175. plates: PlateMetadata[],
  176. loadedFilaments: LoadedFilament[] = [],
  177. status?: PrinterStatus,
  178. emptyLabel = 'Empty',
  179. filamentNameByIdx: Record<string, string> = {},
  180. ): QueueFilamentDisplay[] {
  181. // A stored AMS mapping names the physical tray that will actually feed a 3MF
  182. // slot. Once its live tray data is available, that is more specific than
  183. // either the queue override or the original slice. When the printer reports
  184. // that tray as empty, keep the intended colour but say the slot is empty.
  185. // While the job prints, a slot whose spool ran out shows the backup spool the
  186. // printer switched to instead.
  187. const backups =
  188. item.status === 'printing' ? backupTrays(item.ams_mapping, status?.tray_change_log) : new Map<number, number>();
  189. const resolveSlot = (planned: QueueFilamentDisplay): QueueFilamentDisplay => {
  190. const slotId = planned.slotId;
  191. const storedTrayId = slotId > 0 ? item.ams_mapping?.[slotId - 1] : undefined;
  192. if (storedTrayId == null || storedTrayId < 0) return planned;
  193. const mappedTrayId = backups.get(storedTrayId) ?? storedTrayId;
  194. const loaded = loadedFilaments.find((filament) => filament.globalTrayId === mappedTrayId);
  195. if (loaded) {
  196. return {
  197. slotId,
  198. type: loaded.type,
  199. color: loaded.color,
  200. colorName: loaded.colorName,
  201. slotLabel: loaded.label,
  202. spoolName: loaded.spoolName,
  203. extraColors: loaded.extraColors,
  204. effectType: loaded.effectType,
  205. subtype: loaded.spoolSubtype,
  206. };
  207. }
  208. const emptySlotLabel = emptyMappedSlotLabel(status, mappedTrayId);
  209. if (emptySlotLabel) {
  210. return { ...planned, slotLabel: emptySlotLabel, spoolName: emptyLabel, emptySlot: true };
  211. }
  212. return planned;
  213. };
  214. const selectedPlate =
  215. item.plate_id != null
  216. ? plates.find((plate) => plate.index === item.plate_id)
  217. : plates[0];
  218. if (selectedPlate) {
  219. const overrides = new Map(
  220. (item.filament_overrides ?? []).map((override) => [override.slot_id, override]),
  221. );
  222. return selectedPlate.filaments
  223. .filter((filament) => filament.used_in_plate !== false && filament.used_grams > 0)
  224. .map((filament) => {
  225. const override = overrides.get(filament.slot_id);
  226. const color = override?.color ?? filament.color;
  227. const type = override?.type ?? filament.type;
  228. // An override is another filament: the plate's preset is not its own.
  229. const productLine = override
  230. ? productLineOf(override.tray_info_idx, override.type, filamentNameByIdx)
  231. : productLineOf(filament.tray_info_idx, filament.type, filamentNameByIdx);
  232. return resolveSlot({
  233. slotId: filament.slot_id,
  234. type,
  235. color,
  236. colorName: override?.color_name?.trim() || getColorName(color, productLine),
  237. });
  238. });
  239. }
  240. // The queue row can render before plate metadata arrives (or an old source
  241. // may no longer expose it). Prefer a resolved physical tray when possible,
  242. // then explicit queue overrides because they describe the user's intention.
  243. if (item.filament_overrides?.length) {
  244. return item.filament_overrides.map((override) =>
  245. resolveSlot({
  246. slotId: override.slot_id,
  247. type: override.type,
  248. color: override.color,
  249. colorName:
  250. override.color_name?.trim() ||
  251. getColorName(override.color, productLineOf(override.tray_info_idx, override.type, filamentNameByIdx)),
  252. }),
  253. );
  254. }
  255. // Last-resort compatibility fallback for older/simpler queue responses.
  256. if (item.filament_color) {
  257. return [
  258. resolveSlot({
  259. slotId: 1,
  260. type: item.filament_type ?? '',
  261. color: item.filament_color,
  262. colorName: getColorName(item.filament_color, item.filament_type),
  263. }),
  264. ];
  265. }
  266. return [];
  267. }
  268. function formatWeight(g: number, useKg = false): string {
  269. if (useKg && g >= 1000) return `${(g / 1000).toFixed(1)}kg`;
  270. return `${Math.round(g)}g`;
  271. }
  272. function StatusBadge({ status, waitingReason, printerState, t }: { status: PrintQueueItem['status']; waitingReason?: string | null; printerState?: string | null; t: (key: string) => string }) {
  273. // Special case: pending with waiting_reason shows as "Waiting"
  274. if (status === 'pending' && waitingReason) {
  275. return (
  276. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-purple-700 dark:text-purple-400 bg-purple-50 dark:bg-purple-400/10 border-purple-200 dark:border-purple-400/20">
  277. <Clock className="w-3.5 h-3.5" />
  278. {t('queue.status.waiting')}
  279. </span>
  280. );
  281. }
  282. // Special case: printing but printer is paused
  283. if (status === 'printing' && printerState === 'PAUSE') {
  284. return (
  285. <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border text-yellow-700 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-400/10 border-yellow-200 dark:border-yellow-400/20">
  286. <Pause className="w-3.5 h-3.5" />
  287. {t('queue.status.paused')}
  288. </span>
  289. );
  290. }
  291. const config = {
  292. pending: { icon: Clock, color: 'text-status-warning bg-status-warning/10 border-status-warning/20', label: t('queue.status.pending') },
  293. printing: { icon: Play, color: 'text-blue-700 dark:text-blue-400 bg-blue-50 dark:bg-blue-400/10 border-blue-200 dark:border-blue-400/20', label: t('queue.status.printing') },
  294. completed: { icon: CheckCircle, color: 'text-status-ok bg-status-ok/10 border-status-ok/20', label: t('queue.status.completed') },
  295. failed: { icon: XCircle, color: 'text-status-error bg-status-error/10 border-status-error/20', label: t('queue.status.failed') },
  296. skipped: { icon: SkipForward, color: 'text-orange-700 dark:text-orange-400 bg-orange-50 dark:bg-orange-400/10 border-orange-200 dark:border-orange-400/20', label: t('queue.status.skipped') },
  297. cancelled: { icon: X, color: 'text-gray-400 bg-gray-400/10 border-gray-400/20', label: t('queue.status.cancelled') },
  298. };
  299. const { icon: Icon, color, label } = config[status];
  300. return (
  301. <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border ${color}`}>
  302. <Icon className="w-3.5 h-3.5" />
  303. {label}
  304. </span>
  305. );
  306. }
  307. // Bulk edit modal for multiple queue items
  308. function BulkEditModal({
  309. selectedCount,
  310. printers,
  311. onSave,
  312. onClose,
  313. isSaving,
  314. canControlPrinter,
  315. hasGcodeSnippets,
  316. t,
  317. }: {
  318. selectedCount: number;
  319. printers: { id: number; name: string; nozzle_count?: number }[];
  320. onSave: (data: Partial<PrintQueueBulkUpdate>) => void;
  321. onClose: () => void;
  322. isSaving: boolean;
  323. canControlPrinter: boolean;
  324. hasGcodeSnippets: boolean;
  325. t: (key: string, options?: Record<string, unknown>) => string;
  326. }) {
  327. const [printerId, setPrinterId] = useState<number | null | 'unchanged'>('unchanged');
  328. const [manualStart, setManualStart] = useState<boolean | 'unchanged'>('unchanged');
  329. const [autoOffAfter, setAutoOffAfter] = useState<boolean | 'unchanged'>('unchanged');
  330. const [requirePreviousSuccess, setRequirePreviousSuccess] = useState<boolean | 'unchanged'>('unchanged');
  331. const [gcodeInjection, setGcodeInjection] = useState<boolean | 'unchanged'>('unchanged');
  332. const [bedLevelling, setBedLevelling] = useState<CalibrationMode | 'unchanged'>('unchanged');
  333. const [flowCali, setFlowCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  334. const [vibrationCali, setVibrationCali] = useState<boolean | 'unchanged'>('unchanged');
  335. const [layerInspect, setLayerInspect] = useState<boolean | 'unchanged'>('unchanged');
  336. const [timelapse, setTimelapse] = useState<boolean | 'unchanged'>('unchanged');
  337. const [useAms, setUseAms] = useState<boolean | 'unchanged'>('unchanged');
  338. const [confirmOutcome, setConfirmOutcome] = useState<boolean | 'unchanged'>('unchanged');
  339. const [nozzleOffsetCali, setNozzleOffsetCali] = useState<CalibrationMode | 'unchanged'>('unchanged');
  340. // Show the dual-nozzle-only toggle when the user has at least one
  341. // dual-nozzle printer registered (H2D/H2D Pro/H2C/X2D). Single-nozzle
  342. // queues never see it — the MQTT layer ignores the field anyway.
  343. const hasDualNozzlePrinter = printers.some(p => p.nozzle_count === 2);
  344. const handleSave = () => {
  345. const data: Partial<PrintQueueBulkUpdate> = {};
  346. if (printerId !== 'unchanged') data.printer_id = printerId;
  347. if (manualStart !== 'unchanged') data.manual_start = manualStart;
  348. if (autoOffAfter !== 'unchanged') data.auto_off_after = autoOffAfter;
  349. if (requirePreviousSuccess !== 'unchanged') data.require_previous_success = requirePreviousSuccess;
  350. if (gcodeInjection !== 'unchanged') data.gcode_injection = gcodeInjection;
  351. if (bedLevelling !== 'unchanged') data.bed_levelling = bedLevelling;
  352. if (flowCali !== 'unchanged') data.flow_cali = flowCali;
  353. if (vibrationCali !== 'unchanged') data.vibration_cali = vibrationCali;
  354. if (layerInspect !== 'unchanged') data.layer_inspect = layerInspect;
  355. if (timelapse !== 'unchanged') data.timelapse = timelapse;
  356. if (useAms !== 'unchanged') data.use_ams = useAms;
  357. if (confirmOutcome !== 'unchanged') data.confirm_outcome = confirmOutcome;
  358. if (nozzleOffsetCali !== 'unchanged') data.nozzle_offset_cali = nozzleOffsetCali;
  359. onSave(data);
  360. };
  361. const hasChanges = printerId !== 'unchanged' || manualStart !== 'unchanged' || autoOffAfter !== 'unchanged' ||
  362. requirePreviousSuccess !== 'unchanged' || bedLevelling !== 'unchanged' || flowCali !== 'unchanged' ||
  363. vibrationCali !== 'unchanged' || layerInspect !== 'unchanged' || timelapse !== 'unchanged' || useAms !== 'unchanged' ||
  364. confirmOutcome !== 'unchanged' || nozzleOffsetCali !== 'unchanged' || gcodeInjection !== 'unchanged';
  365. return (
  366. <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
  367. <div className="bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg max-h-[90vh] overflow-y-auto">
  368. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary">
  369. <h2 className="text-lg font-semibold text-white">
  370. {t('queue.bulkEdit.title', { count: selectedCount })}
  371. </h2>
  372. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  373. <X className="w-5 h-5 text-bambu-gray" />
  374. </button>
  375. </div>
  376. <div className="p-4 space-y-4">
  377. <p className="text-sm text-bambu-gray">
  378. {t('queue.bulkEdit.description')}
  379. </p>
  380. {/* Printer Assignment */}
  381. <div>
  382. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printer')}</label>
  383. <select
  384. value={printerId === null ? 'null' : printerId === 'unchanged' ? 'unchanged' : String(printerId)}
  385. onChange={(e) => {
  386. const val = e.target.value;
  387. if (val === 'unchanged') setPrinterId('unchanged');
  388. else if (val === 'null') setPrinterId(null);
  389. else setPrinterId(Number(val));
  390. }}
  391. 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"
  392. >
  393. <option value="unchanged">{t('queue.bulkEdit.noChange')}</option>
  394. <option value="null">{t('queue.filter.unassigned')}</option>
  395. {printers.map(p => (
  396. <option key={p.id} value={p.id}>{p.name}</option>
  397. ))}
  398. </select>
  399. </div>
  400. {/* Queue Options */}
  401. <div>
  402. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.queueOptions')}</label>
  403. <div className="space-y-2">
  404. <TriStateToggle label={t('queue.bulkEdit.staged')} value={manualStart} onChange={setManualStart} t={t} />
  405. <TriStateToggle label={t('queue.bulkEdit.autoPowerOff')} value={autoOffAfter} onChange={setAutoOffAfter} disabled={!canControlPrinter} t={t} />
  406. <TriStateToggle label={t('queue.bulkEdit.requirePrevious')} value={requirePreviousSuccess} onChange={setRequirePreviousSuccess} t={t} />
  407. {/* Same gate as the print modal's checkbox (#3058): hidden until an
  408. admin has saved a snippet for some printer model, so the toggle
  409. never promises an injection that has nothing to inject. */}
  410. {hasGcodeSnippets && (
  411. <TriStateToggle label={t('queue.bulkEdit.gcodeInjection')} value={gcodeInjection} onChange={setGcodeInjection} t={t} />
  412. )}
  413. </div>
  414. </div>
  415. {/* Print Options */}
  416. <div>
  417. <label className="block text-sm font-medium text-white mb-2">{t('queue.bulkEdit.printOptions')}</label>
  418. <div className="space-y-2">
  419. <CalibrationModeToggle label={t('queue.bulkEdit.bedLevelling')} value={bedLevelling} onChange={setBedLevelling} t={t} />
  420. <CalibrationModeToggle label={t('queue.bulkEdit.flowCalibration')} value={flowCali} onChange={setFlowCali} t={t} />
  421. <TriStateToggle label={t('queue.bulkEdit.vibrationCalibration')} value={vibrationCali} onChange={setVibrationCali} t={t} />
  422. <TriStateToggle label={t('queue.bulkEdit.layerInspection')} value={layerInspect} onChange={setLayerInspect} t={t} />
  423. <TriStateToggle label={t('queue.bulkEdit.timelapse')} value={timelapse} onChange={setTimelapse} t={t} />
  424. <TriStateToggle label={t('queue.bulkEdit.useAms')} value={useAms} onChange={setUseAms} t={t} />
  425. <TriStateToggle label={t('queue.bulkEdit.confirmOutcome')} value={confirmOutcome} onChange={setConfirmOutcome} t={t} />
  426. {hasDualNozzlePrinter && (
  427. <CalibrationModeToggle label={t('queue.bulkEdit.nozzleOffsetCali')} value={nozzleOffsetCali} onChange={setNozzleOffsetCali} t={t} />
  428. )}
  429. </div>
  430. </div>
  431. </div>
  432. <div className="flex justify-end gap-3 p-4 border-t border-bambu-dark-tertiary">
  433. <Button variant="secondary" onClick={onClose}>{t('common.cancel')}</Button>
  434. <Button
  435. onClick={handleSave}
  436. disabled={!hasChanges || isSaving}
  437. >
  438. {isSaving ? t('common.saving') : t('queue.bulkEdit.applyChanges')}
  439. </Button>
  440. </div>
  441. </div>
  442. </div>
  443. );
  444. }
  445. // Tri-state toggle for bulk edit (unchanged / on / off)
  446. function TriStateToggle({
  447. label,
  448. value,
  449. onChange,
  450. disabled,
  451. t,
  452. }: {
  453. label: string;
  454. value: boolean | 'unchanged';
  455. onChange: (val: boolean | 'unchanged') => void;
  456. disabled?: boolean;
  457. t: (key: string) => string;
  458. }) {
  459. return (
  460. <div className={`flex items-center justify-between py-1 ${disabled ? 'opacity-50' : ''}`}>
  461. <span className="text-sm text-bambu-gray">{label}</span>
  462. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  463. <button
  464. onClick={() => onChange('unchanged')}
  465. disabled={disabled}
  466. className={`px-2 py-1 text-xs rounded ${value === 'unchanged' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  467. >
  468. —
  469. </button>
  470. <button
  471. onClick={() => onChange(false)}
  472. disabled={disabled}
  473. className={`px-2 py-1 text-xs rounded ${value === false ? 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  474. >
  475. {t('common.off')}
  476. </button>
  477. <button
  478. onClick={() => onChange(true)}
  479. disabled={disabled}
  480. className={`px-2 py-1 text-xs rounded ${value === true ? 'bg-bambu-green/20 text-bambu-green' : 'text-bambu-gray hover:text-white'} disabled:cursor-not-allowed`}
  481. >
  482. {t('common.on')}
  483. </button>
  484. </div>
  485. </div>
  486. );
  487. }
  488. // Four-state selector for the tri-state calibration options in bulk edit
  489. // (unchanged / off / auto / on). Mirrors TriStateToggle's chrome.
  490. function CalibrationModeToggle({
  491. label,
  492. value,
  493. onChange,
  494. t,
  495. }: {
  496. label: string;
  497. value: CalibrationMode | 'unchanged';
  498. onChange: (val: CalibrationMode | 'unchanged') => void;
  499. t: (key: string) => string;
  500. }) {
  501. const modes: Array<{ key: CalibrationMode | 'unchanged'; label: string; active: string }> = [
  502. { key: 'unchanged', label: '—', active: 'bg-bambu-dark-tertiary text-white' },
  503. { key: 'off', label: t('settings.calibrationMode_off'), active: 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400' },
  504. { key: 'auto', label: t('settings.calibrationMode_auto'), active: 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400' },
  505. { key: 'on', label: t('settings.calibrationMode_on'), active: 'bg-bambu-green/20 text-bambu-green' },
  506. ];
  507. return (
  508. <div className="flex items-center justify-between py-1">
  509. <span className="text-sm text-bambu-gray">{label}</span>
  510. <div className="flex items-center gap-1 bg-bambu-dark rounded-lg p-0.5">
  511. {modes.map(({ key, label: modeLabel, active }) => (
  512. <button
  513. key={key}
  514. onClick={() => onChange(key)}
  515. className={`px-2 py-1 text-xs rounded ${value === key ? active : 'text-bambu-gray hover:text-white'}`}
  516. >
  517. {modeLabel}
  518. </button>
  519. ))}
  520. </div>
  521. </div>
  522. );
  523. }
  524. // Sortable queue item for drag and drop
  525. function SortableQueueItem({
  526. item,
  527. position,
  528. onEdit,
  529. onCancel,
  530. onRemove,
  531. onStop,
  532. onRequeue,
  533. onStart,
  534. onMoveUp,
  535. onMoveDown,
  536. timeFormat = 'system',
  537. isSelected = false,
  538. onToggleSelect,
  539. hasPermission,
  540. canModify,
  541. printerState,
  542. showEta = false,
  543. etaNow,
  544. t,
  545. }: {
  546. item: PrintQueueItem;
  547. position?: number;
  548. onEdit: () => void;
  549. onCancel: () => void;
  550. onRemove: () => void;
  551. onStop: () => void;
  552. onRequeue: () => void;
  553. onStart: () => void;
  554. // Mobile tap-to-reorder (#2667). Undefined = at a list boundary (button
  555. // shown disabled) or reordering isn't available; the desktop drag handle
  556. // is unaffected. Move one step among siblings, then persist via reorder.
  557. onMoveUp?: () => void;
  558. onMoveDown?: () => void;
  559. timeFormat?: TimeFormat;
  560. isSelected?: boolean;
  561. onToggleSelect?: () => void;
  562. hasPermission: (permission: Permission) => boolean;
  563. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  564. printerState?: string | null;
  565. // Whether this item qualifies for an "if started now" ETA (#2740), and the
  566. // instant to measure it from. Both are decided by the page so every row on
  567. // screen quotes the same clock.
  568. showEta?: boolean;
  569. etaNow?: number;
  570. t: (key: string, options?: Record<string, unknown>) => string;
  571. }) {
  572. const { hasAnyPermission } = useAuth();
  573. // Their waiting jobs are started by someone who manages the queue (#1620)
  574. const awaitingReview = !hasAnyPermission('queue:update_all', 'queue:start_unreviewed');
  575. const hasPhysicalAmsMapping =
  576. item.printer_id != null && (item.ams_mapping?.some((trayId) => trayId >= 0) ?? false);
  577. // Printing rows already need live status for progress. A queued item with a
  578. // stored AMS mapping also needs it so the card can turn global tray ids into
  579. // the actual slot / colour that will feed the print (#3132). React Query
  580. // deduplicates rows sharing a printer.
  581. const { data: status } = useQuery({
  582. queryKey: ['printerStatus', item.printer_id],
  583. queryFn: () => api.getPrinterStatus(item.printer_id!),
  584. refetchInterval: printerState === 'printing' ? 30000 : false,
  585. enabled: item.printer_id != null && (printerState === 'printing' || hasPhysicalAmsMapping),
  586. });
  587. // Inventory identity is display-only: printer telemetry knows the tray colour
  588. // and material but not that a third-party spool is e.g. "eSUN PLA Basic".
  589. // Reuse the same payload / key as PrintModal so a mapped queue row names the
  590. // physical spool consistently with the mapping picker.
  591. const { data: inventoryRemain } = useQuery({
  592. queryKey: ['printer-inventory-remain', item.printer_id],
  593. queryFn: () => api.getInventoryRemain(item.printer_id!),
  594. enabled: hasPhysicalAmsMapping,
  595. staleTime: 30 * 1000,
  596. });
  597. const slotSpools = useMemo(() => {
  598. const slots = inventoryRemain?.slot_materials;
  599. if (!slots?.length) return undefined;
  600. const map = new Map<number, SlotSpoolIdentity>();
  601. slots.forEach((slot) => {
  602. if (slot.spool) map.set(slot.global_tray_id, slot.spool);
  603. });
  604. return map.size > 0 ? map : undefined;
  605. }, [inventoryRemain]);
  606. const loadedFilaments = useMemo(
  607. () => buildLoadedFilaments(status, slotSpools),
  608. [status, slotSpools],
  609. );
  610. // Determine if we're printing a library file
  611. const isLibraryFile = !!item.library_file_id && !item.archive_id;
  612. // Fetch archive plate details. Skip when the linked archive has been
  613. // soft-deleted (#1348 follow-up): its 3MF is gone from disk so the
  614. // /plates endpoint just 404-storms the queue page.
  615. const { data: archivePlatesData } = useQuery({
  616. queryKey: ['archive-plates', item.archive_id],
  617. queryFn: () => api.getArchivePlates(item.archive_id!),
  618. enabled: !!item.archive_id && !isLibraryFile && !item.archive_deleted,
  619. });
  620. // Fetch library file plate details
  621. const { data: libraryPlatesData } = useQuery({
  622. queryKey: ['library-file-plates', item.library_file_id],
  623. queryFn: () => api.getLibraryFilePlates(item.library_file_id!),
  624. enabled: isLibraryFile && !!item.library_file_id,
  625. });
  626. // Combine plates data from either source
  627. const platesData = isLibraryFile ? libraryPlatesData : archivePlatesData;
  628. const plates = platesData?.plates ?? [];
  629. const filamentNameByIdx = useFilamentNameByIdx();
  630. const queueFilaments = resolveQueueFilaments(
  631. item,
  632. plates,
  633. loadedFilaments,
  634. status,
  635. t('ams.empty'),
  636. filamentNameByIdx,
  637. );
  638. const canReorder = hasPermission('queue:reorder');
  639. const {
  640. attributes,
  641. listeners,
  642. setNodeRef,
  643. transform,
  644. transition,
  645. isDragging,
  646. } = useSortable({ id: item.id, disabled: item.status !== 'pending' || !canReorder });
  647. const style = {
  648. transform: CSS.Transform.toString(transform),
  649. transition,
  650. };
  651. const isPrinting = item.status === 'printing';
  652. const isPending = item.status === 'pending';
  653. const isHistory = ['completed', 'failed', 'skipped', 'cancelled'].includes(item.status);
  654. // This is an "if started now" estimate, not a cumulative queue forecast, so
  655. // it is only shown for items the page determined could actually start now
  656. // (see etaEligibleIds). etaNow is the caller's ticking clock — deriving the
  657. // ETA from it rather than from Date.now() keeps this render deterministic and
  658. // stops the value freezing at first paint.
  659. const queueItemEta =
  660. isPending && showEta && item.print_time_seconds != null && item.print_time_seconds > 0
  661. ? formatETA(item.print_time_seconds / 60, timeFormat, t, etaNow)
  662. : null;
  663. const isMobileSelectable = isPending && onToggleSelect;
  664. const thumbnailUrl = queueItemThumbnailUrl(item);
  665. return (
  666. <div
  667. ref={setNodeRef}
  668. style={style}
  669. className={`
  670. group relative bg-bambu-dark-secondary rounded-xl border transition-all duration-200
  671. border-l-[3px] ${
  672. isPrinting ? 'border-l-blue-500' :
  673. isPending ? 'border-l-yellow-500' :
  674. item.status === 'completed' ? 'border-l-emerald-500' :
  675. item.status === 'failed' ? 'border-l-red-500' :
  676. 'border-l-gray-500'
  677. }
  678. ${isDragging ? 'opacity-50 scale-[1.02] shadow-xl z-50' : ''}
  679. ${isPrinting ? 'border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent' : ''}
  680. ${isSelected && isMobileSelectable ? 'sm:border-bambu-dark-tertiary border-bambu-green/40' : ''}
  681. ${!isSelected && !isPrinting ? 'border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80' : ''}
  682. ${isMobileSelectable ? 'cursor-pointer sm:cursor-default' : ''}
  683. `}
  684. onClick={isMobileSelectable ? () => {
  685. if (window.innerWidth < 640) onToggleSelect();
  686. } : undefined}
  687. >
  688. {/* Mobile selected left accent bar */}
  689. {isMobileSelectable && isSelected && (
  690. <div className="sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green" />
  691. )}
  692. <div className="flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4">
  693. {/* Mobile reorder arrows (#2667). The desktop drag handle is hidden on
  694. phones and touch-drag is unreliable there, so pending rows get
  695. tap-to-move up/down controls instead. Shown only below `sm`. */}
  696. {isPending && (onMoveUp || onMoveDown) && (
  697. <div
  698. className="flex sm:hidden flex-col shrink-0 -my-1"
  699. onClick={(e) => e.stopPropagation()}
  700. >
  701. <button
  702. type="button"
  703. onClick={onMoveUp}
  704. disabled={!onMoveUp}
  705. title={t('queue.moveUp')}
  706. aria-label={t('queue.moveUp')}
  707. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  708. >
  709. <ChevronUp className="w-5 h-5" />
  710. </button>
  711. <button
  712. type="button"
  713. onClick={onMoveDown}
  714. disabled={!onMoveDown}
  715. title={t('queue.moveDown')}
  716. aria-label={t('queue.moveDown')}
  717. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  718. >
  719. <ChevronDown className="w-5 h-5" />
  720. </button>
  721. </div>
  722. )}
  723. {/* Mobile selection indicator — left accent bar only, no tick */}
  724. {/* Selection checkbox for pending items - hidden on mobile, tap card instead */}
  725. {isPending && onToggleSelect && (
  726. <button
  727. onClick={(e) => {
  728. e.stopPropagation();
  729. onToggleSelect();
  730. }}
  731. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  732. isSelected
  733. ? 'bg-bambu-green border-bambu-green text-white'
  734. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  735. }`}
  736. >
  737. {isSelected && <Check className="w-4 h-4" />}
  738. </button>
  739. )}
  740. {/* Drag handle or position number - hidden on mobile */}
  741. {isPending ? (
  742. <div
  743. {...attributes}
  744. {...listeners}
  745. className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-none shrink-0"
  746. >
  747. <GripVertical className="w-4 h-4 text-bambu-gray" />
  748. </div>
  749. ) : position !== undefined ? (
  750. <div className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0">
  751. #{position}
  752. </div>
  753. ) : (
  754. <div className="hidden sm:block w-8 shrink-0" />
  755. )}
  756. {/* Thumbnail - use plate-specific thumbnail if plate_id is set */}
  757. <div className="w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden">
  758. {thumbnailUrl ? (
  759. <img src={thumbnailUrl} alt="" className="w-full h-full object-cover" />
  760. ) : (
  761. <div className="w-full h-full flex items-center justify-center text-bambu-gray">
  762. <Layers className="w-5 h-5 sm:w-6 sm:h-6" />
  763. </div>
  764. )}
  765. </div>
  766. {/* Info */}
  767. <div className="flex-1 min-w-0">
  768. <div className="flex items-center gap-2 mb-1">
  769. <p className="text-sm sm:text-base text-white font-medium truncate">
  770. {queueItemDisplayName(item, (n) => t('common.plusNMore', { count: n }))}
  771. {(platesData?.is_multi_plate ?? false) && item.plate_id !== undefined && item.plate_id !== null && ` • ${plates.find(plate => plate.index === item.plate_id)?.name || t('queue.plateNumber', { index: item.plate_id })}`}
  772. </p>
  773. {item.archive_id ? (
  774. <Link
  775. to={`/archives?highlight=${item.archive_id}`}
  776. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  777. title={t('queue.viewArchive')}
  778. >
  779. <ExternalLink className="w-3.5 h-3.5" />
  780. </Link>
  781. ) : item.library_file_id ? (
  782. <Link
  783. to={`/library?highlight=${item.library_file_id}`}
  784. className="text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0"
  785. title={t('queue.viewInFileManager')}
  786. >
  787. <ExternalLink className="w-3.5 h-3.5" />
  788. </Link>
  789. ) : null}
  790. {item.batch_name && (
  791. <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-cyan-100 dark:bg-cyan-500/20 text-cyan-700 dark:text-cyan-300 rounded border border-cyan-300 dark:border-cyan-500/30">
  792. {item.batch_name}
  793. </span>
  794. )}
  795. </div>
  796. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  797. <span className={`flex items-center gap-1 sm:gap-1.5 ${item.printer_id === null && !item.target_model ? 'text-orange-700 dark:text-orange-400' : ''} ${item.target_model && !item.printer_id ? 'text-blue-700 dark:text-blue-400' : ''}`}>
  798. <Printer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  799. <span className="truncate max-w-[120px] sm:max-w-none">
  800. {/* A cross-model item (#671) is waiting on several models at once.
  801. Showing only target_model would name whichever candidate is
  802. first and read as a lie the moment the other one runs. */}
  803. {(item.variants?.length ?? 0) > 1 && !item.printer_id
  804. ? `${t('queue.filter.any')} ${item.variants!.map(v => v.target_model).join(' / ')}${item.target_location ? ` @ ${item.target_location}` : ''}`
  805. : item.target_model && !item.printer_id
  806. ? `${t('queue.filter.any')} ${item.target_model}${item.target_location ? ` @ ${item.target_location}` : ''}${item.required_filament_types?.length ? ` (${item.required_filament_types.join(', ')})` : ''}`
  807. : item.printer_id === null
  808. ? t('queue.filter.unassigned')
  809. : (item.printer_name || `${t('common.printer')} #${item.printer_id}`)}
  810. </span>
  811. </span>
  812. {item.print_time_seconds && (
  813. <span className="flex items-center gap-1 sm:gap-1.5">
  814. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  815. {formatDuration(item.print_time_seconds)}
  816. </span>
  817. )}
  818. {queueItemEta && (
  819. <span
  820. data-testid="queue-item-eta"
  821. className="text-bambu-green font-medium"
  822. title={t('queue.time.etaIfStartedNow')}
  823. >
  824. ETA {queueItemEta}
  825. </span>
  826. )}
  827. {item.filament_used_grams && (
  828. <span className="flex items-center gap-1 sm:gap-1.5">
  829. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  830. {formatWeight(item.filament_used_grams)}
  831. </span>
  832. )}
  833. {queueFilaments.length > 2 ? (
  834. <span
  835. data-testid="queue-filament-compact"
  836. className="flex items-center gap-0.5 flex-shrink-0"
  837. title={queueFilaments.map(queueFilamentLabel).join('\n')}
  838. // The tooltip needs a hover; touch screens and screen readers
  839. // get the same lines through the accessible name instead.
  840. role="img"
  841. aria-label={queueFilaments.map(queueFilamentLabel).join(', ')}
  842. >
  843. {queueFilaments.map((filament) => (
  844. <FilamentSwatch
  845. key={`filament-${filament.slotId}`}
  846. rgba={filament.color}
  847. extraColors={filament.extraColors}
  848. effectType={filament.effectType}
  849. subtype={filament.subtype}
  850. className="w-2.5 h-2.5 sm:w-3 sm:h-3 pointer-events-none"
  851. effectSize="table"
  852. />
  853. ))}
  854. {queueFilaments.some((filament) => filament.emptySlot) && (
  855. <AlertCircle
  856. className="w-3 h-3 ml-0.5 text-yellow-700 dark:text-yellow-400"
  857. aria-hidden="true"
  858. />
  859. )}
  860. </span>
  861. ) : (
  862. queueFilaments.map((filament) => {
  863. const mappedLabel = queueFilamentLabel(filament);
  864. return (
  865. <span
  866. key={`filament-${filament.slotId}`}
  867. className="flex items-center gap-1 sm:gap-1.5 min-w-0"
  868. title={mappedLabel}
  869. >
  870. <FilamentSwatch
  871. rgba={filament.color}
  872. extraColors={filament.extraColors}
  873. effectType={filament.effectType}
  874. subtype={filament.subtype}
  875. className="w-3 h-3 sm:w-3.5 sm:h-3.5"
  876. effectSize="table"
  877. />
  878. <span
  879. className={`truncate max-w-[110px] sm:max-w-[260px]${
  880. filament.emptySlot ? ' text-yellow-700 dark:text-yellow-400' : ''
  881. }`}
  882. >
  883. {mappedLabel}
  884. </span>
  885. </span>
  886. );
  887. })
  888. )}
  889. {(() => {
  890. // Build plate badge so the user knows which plate to mount before
  891. // walking to the printer (#1281). Hidden when the 3MF doesn't
  892. // carry curr_bed_type or the slicer used an unknown label.
  893. const bed = getBedTypeInfo(item.bed_type);
  894. if (!bed) return null;
  895. return (
  896. <span className="flex items-center gap-1 sm:gap-1.5" title={bed.label}>
  897. <img src={bed.icon} alt="" className="w-3.5 h-3.5 sm:w-4 sm:h-4 object-contain" />
  898. <span className="truncate max-w-[120px]">{bed.label}</span>
  899. </span>
  900. );
  901. })()}
  902. {item.created_by_username && (
  903. <span className="hidden sm:flex items-center gap-1.5" title={t('queue.addedBy', { name: item.created_by_username })}>
  904. <User className="w-3.5 h-3.5" />
  905. {item.created_by_username}
  906. </span>
  907. )}
  908. {isPending && !item.manual_start && (
  909. <span className="flex items-center gap-1.5">
  910. <Clock className="w-3.5 h-3.5" />
  911. {/* An item with no scheduled time used to render as "ASAP", which is the
  912. name of a dispatch mode the user may well not have picked -- ASAP and
  913. Queue differ only in insert position, and neither is stored on the
  914. item, so the two are indistinguishable here. Someone who chose Queue
  915. saw their row labelled ASAP and read it as Bambuddy overriding them
  916. (#2557, #3018). This column answers "when does it run", so it now says
  917. that instead of borrowing a mode name. */}
  918. {item.scheduled_time
  919. ? ((parseUTCDate(item.scheduled_time)?.getTime() ?? 0) - Date.now() < -60000
  920. ? t?.('queue.time.overdue') ?? 'Overdue'
  921. : formatRelativeTime(item.scheduled_time, timeFormat, t))
  922. : t?.('queue.time.whenFree') ?? 'When a printer is free'}
  923. </span>
  924. )}
  925. </div>
  926. {/* Options badges */}
  927. <div className="flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2">
  928. {item.manual_start && (
  929. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-400 rounded-full border border-purple-200 dark:border-purple-500/20 flex items-center gap-1">
  930. <Hand className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  931. {awaitingReview ? t('queue.badges.awaitingReview') : t('queue.badges.staged')}
  932. </span>
  933. )}
  934. {item.require_previous_success && (
  935. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-50 dark:bg-orange-500/10 text-orange-700 dark:text-orange-400 rounded-full border border-orange-200 dark:border-orange-500/20">
  936. {t('queue.badges.requiresPrevious')}
  937. </span>
  938. )}
  939. {item.auto_off_after && (
  940. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-50 dark:bg-blue-500/10 text-blue-700 dark:text-blue-400 rounded-full border border-blue-200 dark:border-blue-500/20 flex items-center gap-1">
  941. <Power className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  942. {t('queue.badges.autoPowerOff')}
  943. </span>
  944. )}
  945. {item.gcode_injection && (
  946. <span className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-50 dark:bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 rounded-full border border-emerald-200 dark:border-emerald-500/20 flex items-center gap-1">
  947. <Code className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  948. {t('queue.badges.gcodeInjection')}
  949. </span>
  950. )}
  951. {item.confirm_outcome && (
  952. <span
  953. title={t('queue.badges.confirmOutcomeTitle')}
  954. className="text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-green-50 dark:bg-green-500/10 text-green-700 dark:text-green-400 rounded-full border border-green-200 dark:border-green-500/20 flex items-center gap-1"
  955. >
  956. <ThumbsUp className="w-2.5 h-2.5 sm:w-3 sm:h-3" />
  957. {t('queue.badges.confirmOutcome')}
  958. </span>
  959. )}
  960. </div>
  961. {/* Progress bar for printing items - TODO: integrate with WebSocket */}
  962. {isPrinting && status && (() => {
  963. // Gate progress/remaining/layer on printer actually running this print.
  964. // Between dispatch and RUNNING transition (H2D/P1 MQTT lag), status.progress
  965. // is stale from the previous print — showing 100% then snapping back to 0%
  966. // once the new print starts. Only trust these fields when state is active.
  967. const isActive = status.state === 'RUNNING' || status.state === 'PAUSE';
  968. const progress = isActive ? (status.progress || 0) : 0;
  969. const remaining = isActive ? status.remaining_time : null;
  970. const layerNum = isActive ? status.layer_num : null;
  971. const totalLayers = isActive ? status.total_layers : null;
  972. return (
  973. <div className="mt-2 sm:mt-3">
  974. <div className="flex items-center justify-between text-xs sm:text-sm">
  975. <div className="flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3">
  976. <div
  977. className="bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all"
  978. style={{ width: `${progress}%` }}
  979. />
  980. </div>
  981. <span className="text-white">{Math.round(progress)}%</span>
  982. </div>
  983. <div className="flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray">
  984. {remaining != null && remaining > 0 && (
  985. <>
  986. <span className="flex items-center gap-1">
  987. <Clock className="w-3 h-3" />
  988. {formatDuration(remaining * 60)}
  989. </span>
  990. <span className="text-bambu-green font-medium" title={t('printers.estimatedCompletion')}>
  991. ETA {formatETA(remaining, timeFormat, t)}
  992. </span>
  993. </>
  994. )}
  995. {layerNum != null && totalLayers != null && totalLayers > 0 && (
  996. <span className="flex items-center gap-1">
  997. <Layers className="w-3 h-3" />
  998. {layerNum}/{totalLayers}
  999. </span>
  1000. )}
  1001. </div>
  1002. </div>
  1003. );
  1004. })()}
  1005. {/* Waiting reason for model-based assignments */}
  1006. {item.waiting_reason && item.status === 'pending' && (
  1007. <p className="text-[10px] sm:text-xs text-purple-700 dark:text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1">
  1008. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1009. <span>{item.waiting_reason}</span>
  1010. </p>
  1011. )}
  1012. {/* Filament-short flag from the dispatch pre-flight (#1496). */}
  1013. {item.filament_short && item.status === 'pending' && (
  1014. <p
  1015. className="text-[10px] sm:text-xs text-yellow-700 dark:text-yellow-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  1016. title={t('queue.filamentShort.rowTooltip')}
  1017. >
  1018. <AlertCircle className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1019. <span>{t('queue.filamentShort.rowBadge')}</span>
  1020. </p>
  1021. )}
  1022. {/* Archive carries the slicer's own live-resolved AMS-slot pick
  1023. (extra_data.slicer_ams_mapping) — reprints of this archive reuse
  1024. the exact physical spool instead of re-deriving one. */}
  1025. {item.archive_has_slicer_ams_mapping && (
  1026. <p
  1027. className="text-[10px] sm:text-xs text-green-700 dark:text-green-400 mt-1.5 sm:mt-2 flex items-start gap-1"
  1028. title={t('queue.slicerAmsMapping.rowTooltip')}
  1029. >
  1030. <Check className="w-3 h-3 mt-0.5 flex-shrink-0" />
  1031. <span>{t('queue.slicerAmsMapping.rowBadge')}</span>
  1032. </p>
  1033. )}
  1034. {/* Error message */}
  1035. {item.error_message && (
  1036. <p className="text-[10px] sm:text-xs text-red-700 dark:text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1">
  1037. <AlertCircle className="w-3 h-3" />
  1038. {item.error_message}
  1039. </p>
  1040. )}
  1041. </div>
  1042. {/* Status badge + Actions */}
  1043. <div className="flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
  1044. <StatusBadge status={item.status} waitingReason={item.waiting_reason} printerState={printerState} t={t} />
  1045. <div className="flex items-center gap-0.5 sm:gap-1">
  1046. {isPrinting && (
  1047. <Button
  1048. variant="ghost"
  1049. size="sm"
  1050. onClick={onStop}
  1051. disabled={!canModify('queue', 'update', item.created_by_id)}
  1052. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noStopPrint') : t('queue.actions.stopPrint')}
  1053. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10 p-1.5 sm:p-2"
  1054. >
  1055. <StopCircle className="w-4 h-4" />
  1056. </Button>
  1057. )}
  1058. {isPending && (
  1059. <>
  1060. {item.manual_start && (
  1061. <Button
  1062. variant="ghost"
  1063. size="sm"
  1064. onClick={onStart}
  1065. disabled={awaitingReview || !canModify('queue', 'update', item.created_by_id)}
  1066. title={
  1067. awaitingReview
  1068. ? t('queue.permissions.awaitingReview')
  1069. : !canModify('queue', 'update', item.created_by_id)
  1070. ? t('queue.permissions.noStartPrint')
  1071. : t('queue.actions.startPrint')
  1072. }
  1073. className="text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2"
  1074. >
  1075. <Play className="w-4 h-4" />
  1076. </Button>
  1077. )}
  1078. <Button
  1079. variant="ghost"
  1080. size="sm"
  1081. onClick={onEdit}
  1082. disabled={!canModify('queue', 'update', item.created_by_id)}
  1083. title={!canModify('queue', 'update', item.created_by_id) ? t('queue.permissions.noEdit') : t('common.edit')}
  1084. className="p-1.5 sm:p-2"
  1085. >
  1086. <Pencil className="w-4 h-4" />
  1087. </Button>
  1088. <Button
  1089. variant="ghost"
  1090. size="sm"
  1091. onClick={onCancel}
  1092. disabled={!canModify('queue', 'delete', item.created_by_id)}
  1093. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noCancel') : t('common.cancel')}
  1094. className="text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300 hover:bg-red-50 dark:hover:bg-red-500/10 p-1.5 sm:p-2"
  1095. >
  1096. <X className="w-4 h-4" />
  1097. </Button>
  1098. </>
  1099. )}
  1100. {isHistory && (
  1101. <>
  1102. <Button
  1103. variant="ghost"
  1104. size="sm"
  1105. onClick={onRequeue}
  1106. disabled={!hasPermission('queue:create')}
  1107. title={!hasPermission('queue:create') ? t('queue.permissions.noRequeue') : t('queue.actions.requeue')}
  1108. className="text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2"
  1109. >
  1110. <RefreshCw className="w-4 h-4" />
  1111. </Button>
  1112. <Button
  1113. variant="ghost"
  1114. size="sm"
  1115. onClick={onRemove}
  1116. disabled={!canModify('queue', 'delete', item.created_by_id)}
  1117. title={!canModify('queue', 'delete', item.created_by_id) ? t('queue.permissions.noRemove') : t('common.remove')}
  1118. className="p-1.5 sm:p-2"
  1119. >
  1120. <Trash2 className="w-4 h-4" />
  1121. </Button>
  1122. </>
  1123. )}
  1124. </div>
  1125. </div>
  1126. </div>
  1127. </div>
  1128. );
  1129. }
  1130. type QueueRow =
  1131. | { kind: 'item'; item: PrintQueueItem }
  1132. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  1133. interface QueueRowRenderProps {
  1134. row: QueueRow;
  1135. collapsed: boolean;
  1136. onToggleBatch?: () => void;
  1137. onUngroup?: () => void;
  1138. setEditItem: (item: PrintQueueItem) => void;
  1139. setConfirmAction: (a: { type: 'cancel' | 'remove' | 'stop'; item: PrintQueueItem }) => void;
  1140. startMutation: { mutate: (vars: { id: number; skipFilamentCheck?: boolean }) => void };
  1141. selectedItems: number[];
  1142. handleToggleSelect: (id: number) => void;
  1143. timeFormat: TimeFormat;
  1144. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1145. hasPermission: (p: any) => boolean;
  1146. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1147. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  1148. t: (key: string, options?: Record<string, unknown>) => string;
  1149. // Items that qualify for an "if started now" ETA, and the shared clock it is
  1150. // measured from (#2740).
  1151. etaEligibleIds: Set<number>;
  1152. etaNow: number;
  1153. aggregateForRows: (rows: QueueRow[]) => { count: number; time: number; weight: number };
  1154. // Mobile tap-to-reorder (#2667). onMoveUp/onMoveDown move this whole row
  1155. // (single item or batch) one step among its siblings; onMoveBlock is the
  1156. // low-level primitive SortableBatchRow uses to move a child within the
  1157. // batch. All undefined when reordering isn't available (non-manual sort).
  1158. onMoveUp?: () => void;
  1159. onMoveDown?: () => void;
  1160. onMoveBlock?: (movingIds: number[], anchorId: number, placeAfter: boolean) => void;
  1161. }
  1162. /** Renders either a single item or a collapsible batch group containing N
  1163. * sibling items. The batch parent shows aggregate stats; children render
  1164. * with the existing SortableQueueItem (only draggable inside the batch). */
  1165. function QueueRowRender(props: QueueRowRenderProps) {
  1166. const {
  1167. row,
  1168. setEditItem,
  1169. setConfirmAction,
  1170. startMutation,
  1171. selectedItems,
  1172. handleToggleSelect,
  1173. timeFormat,
  1174. hasPermission,
  1175. canModify,
  1176. t,
  1177. etaEligibleIds,
  1178. etaNow,
  1179. onMoveUp,
  1180. onMoveDown,
  1181. } = props;
  1182. if (row.kind === 'item') {
  1183. return (
  1184. <SortableQueueItem
  1185. item={row.item}
  1186. onEdit={() => setEditItem(row.item)}
  1187. onCancel={() => setConfirmAction({ type: 'cancel', item: row.item })}
  1188. onRemove={() => {}}
  1189. onStop={() => {}}
  1190. onRequeue={() => {}}
  1191. onStart={() => startMutation.mutate({ id: row.item.id })}
  1192. onMoveUp={onMoveUp}
  1193. onMoveDown={onMoveDown}
  1194. timeFormat={timeFormat}
  1195. isSelected={selectedItems.includes(row.item.id)}
  1196. onToggleSelect={() => handleToggleSelect(row.item.id)}
  1197. hasPermission={hasPermission}
  1198. canModify={canModify}
  1199. showEta={etaEligibleIds.has(row.item.id)}
  1200. etaNow={etaNow}
  1201. t={t}
  1202. />
  1203. );
  1204. }
  1205. return <SortableBatchRow {...props} />;
  1206. }
  1207. /** Batch parent header registered with dnd-kit so the whole group can be
  1208. * reordered as one unit. Drag handle lives in the header itself; children
  1209. * remain individually draggable while expanded for within-batch reorder. */
  1210. function SortableBatchRow({
  1211. row,
  1212. collapsed,
  1213. onToggleBatch,
  1214. onUngroup,
  1215. setEditItem,
  1216. setConfirmAction,
  1217. startMutation,
  1218. selectedItems,
  1219. handleToggleSelect,
  1220. timeFormat,
  1221. hasPermission,
  1222. canModify,
  1223. t,
  1224. etaEligibleIds,
  1225. etaNow,
  1226. aggregateForRows,
  1227. onMoveUp,
  1228. onMoveDown,
  1229. onMoveBlock,
  1230. }: QueueRowRenderProps) {
  1231. // Dispatcher (QueueRowRender) only mounts this with row.kind === 'batch';
  1232. // narrow up-front so the hook below can reference batchId unconditionally.
  1233. const batchRow = row as Extract<QueueRow, { kind: 'batch' }>;
  1234. const canReorder = hasPermission('queue:reorder');
  1235. const {
  1236. attributes,
  1237. listeners,
  1238. setNodeRef,
  1239. transform,
  1240. transition,
  1241. isDragging,
  1242. } = useSortable({ id: `batch-${batchRow.batchId}`, disabled: !canReorder });
  1243. const style = {
  1244. transform: CSS.Transform.toString(transform),
  1245. transition,
  1246. };
  1247. const agg = aggregateForRows([batchRow]);
  1248. const allChildIds = batchRow.items.map((i) => i.id);
  1249. const allSelected = allChildIds.length > 0 && allChildIds.every((id) => selectedItems.includes(id));
  1250. // Status rollup: worst-of-children (failed > printing > pending).
  1251. const childStatuses = new Set(batchRow.items.map((i) => i.status));
  1252. // We never put non-pending into a batch grouping but render defensively.
  1253. const rollupStatus: PrintQueueItem['status'] = childStatuses.has('failed')
  1254. ? 'failed'
  1255. : childStatuses.has('printing')
  1256. ? 'printing'
  1257. : 'pending';
  1258. const pendingChildren = batchRow.items.filter((i) => i.status === 'pending').length;
  1259. return (
  1260. <div
  1261. ref={setNodeRef}
  1262. style={style}
  1263. className={`bg-bambu-dark-secondary rounded-xl border border-l-[3px] border-l-cyan-400 border-bambu-dark-tertiary overflow-hidden ${
  1264. isDragging ? 'opacity-50 scale-[1.01] shadow-xl z-50' : ''
  1265. }`}
  1266. >
  1267. {/* Parent header */}
  1268. <div className="flex items-center gap-2 sm:gap-3 p-3 sm:p-4">
  1269. {/* Mobile reorder arrows for the whole group (#2667), mirroring the
  1270. desktop drag handle which is hidden on phones. */}
  1271. {canReorder && (onMoveUp || onMoveDown) && (
  1272. <div className="flex sm:hidden flex-col shrink-0 -my-1">
  1273. <button
  1274. type="button"
  1275. onClick={onMoveUp}
  1276. disabled={!onMoveUp}
  1277. title={t('queue.moveUp')}
  1278. aria-label={t('queue.moveUp')}
  1279. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  1280. >
  1281. <ChevronUp className="w-5 h-5" />
  1282. </button>
  1283. <button
  1284. type="button"
  1285. onClick={onMoveDown}
  1286. disabled={!onMoveDown}
  1287. title={t('queue.moveDown')}
  1288. aria-label={t('queue.moveDown')}
  1289. className="flex items-center justify-center w-8 h-7 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark disabled:opacity-25 disabled:hover:bg-transparent transition-colors"
  1290. >
  1291. <ChevronDown className="w-5 h-5" />
  1292. </button>
  1293. </div>
  1294. )}
  1295. <button
  1296. onClick={(e) => {
  1297. e.stopPropagation();
  1298. allChildIds.forEach((id) => {
  1299. if (allSelected && selectedItems.includes(id)) {
  1300. handleToggleSelect(id);
  1301. } else if (!allSelected && !selectedItems.includes(id)) {
  1302. handleToggleSelect(id);
  1303. }
  1304. });
  1305. }}
  1306. className={`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${
  1307. allSelected
  1308. ? 'bg-bambu-green border-bambu-green text-white'
  1309. : 'border-white/30 bg-black/30 hover:border-bambu-green/50'
  1310. }`}
  1311. title={allSelected ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  1312. >
  1313. {allSelected && <Check className="w-4 h-4" />}
  1314. </button>
  1315. {canReorder && (
  1316. <div
  1317. {...attributes}
  1318. {...listeners}
  1319. className="hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-none shrink-0"
  1320. title={t('queue.batch.dragGroup', { defaultValue: 'Drag group' })}
  1321. >
  1322. <GripVertical className="w-4 h-4 text-bambu-gray" />
  1323. </div>
  1324. )}
  1325. <button
  1326. onClick={onToggleBatch}
  1327. className="flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary transition-colors shrink-0"
  1328. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  1329. >
  1330. {collapsed ? (
  1331. <ChevronRight className="w-4 h-4 text-bambu-gray" />
  1332. ) : (
  1333. <ChevronDown className="w-4 h-4 text-bambu-gray" />
  1334. )}
  1335. </button>
  1336. <div className="w-10 h-10 sm:w-12 sm:h-12 flex-shrink-0 bg-bambu-dark rounded-lg flex items-center justify-center">
  1337. {collapsed ? (
  1338. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  1339. ) : (
  1340. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  1341. )}
  1342. </div>
  1343. <div className="flex-1 min-w-0">
  1344. <div className="flex items-center gap-2 mb-1">
  1345. <p className="text-sm sm:text-base text-white font-medium truncate">{batchRow.batchName}</p>
  1346. <span className="flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-cyan-100 dark:bg-cyan-500/15 text-cyan-700 dark:text-cyan-300 rounded border border-cyan-300 dark:border-cyan-500/30">
  1347. {t('queue.batch.label', { count: agg.count })}
  1348. </span>
  1349. </div>
  1350. <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray">
  1351. {agg.time > 0 && (
  1352. <span className="flex items-center gap-1 sm:gap-1.5">
  1353. <Timer className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1354. {formatDuration(agg.time)}
  1355. </span>
  1356. )}
  1357. {agg.weight > 0 && (
  1358. <span className="flex items-center gap-1 sm:gap-1.5">
  1359. <Weight className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1360. {formatWeight(agg.weight)}
  1361. </span>
  1362. )}
  1363. {pendingChildren > 0 && rollupStatus === 'pending' && (
  1364. <span className="flex items-center gap-1 sm:gap-1.5 text-yellow-700 dark:text-yellow-400">
  1365. <Clock className="w-3 h-3 sm:w-3.5 sm:h-3.5" />
  1366. {t('queue.batch.pendingCount', { count: pendingChildren })}
  1367. </span>
  1368. )}
  1369. </div>
  1370. </div>
  1371. <div className="flex items-center gap-1 shrink-0">
  1372. {onUngroup && (
  1373. <Button
  1374. variant="ghost"
  1375. size="sm"
  1376. onClick={onUngroup}
  1377. title={t('queue.batch.ungroup')}
  1378. className="text-cyan-700 dark:text-cyan-300 hover:text-cyan-900 dark:hover:text-cyan-200 hover:bg-cyan-50 dark:hover:bg-cyan-500/10 p-1.5 sm:p-2"
  1379. >
  1380. <Ungroup className="w-4 h-4" />
  1381. </Button>
  1382. )}
  1383. </div>
  1384. </div>
  1385. {/* Children (only when expanded) */}
  1386. {!collapsed && (
  1387. <div className="border-t border-bambu-dark-tertiary bg-black/20 p-2 sm:p-3 space-y-2">
  1388. {batchRow.items.map((child, ci) => (
  1389. <SortableQueueItem
  1390. key={child.id}
  1391. item={child}
  1392. onEdit={() => setEditItem(child)}
  1393. onCancel={() => setConfirmAction({ type: 'cancel', item: child })}
  1394. onRemove={() => {}}
  1395. onStop={() => {}}
  1396. onRequeue={() => {}}
  1397. onStart={() => startMutation.mutate({ id: child.id })}
  1398. onMoveUp={
  1399. onMoveBlock && ci > 0
  1400. ? () => onMoveBlock([child.id], batchRow.items[ci - 1].id, false)
  1401. : undefined
  1402. }
  1403. onMoveDown={
  1404. onMoveBlock && ci < batchRow.items.length - 1
  1405. ? () => onMoveBlock([child.id], batchRow.items[ci + 1].id, true)
  1406. : undefined
  1407. }
  1408. timeFormat={timeFormat}
  1409. isSelected={selectedItems.includes(child.id)}
  1410. onToggleSelect={() => handleToggleSelect(child.id)}
  1411. hasPermission={hasPermission}
  1412. canModify={canModify}
  1413. showEta={etaEligibleIds.has(child.id)}
  1414. etaNow={etaNow}
  1415. t={t}
  1416. />
  1417. ))}
  1418. </div>
  1419. )}
  1420. </div>
  1421. );
  1422. }
  1423. type HistoryRow =
  1424. | { kind: 'item'; item: PrintQueueItem }
  1425. | { kind: 'batch'; batchId: number; batchName: string; items: PrintQueueItem[] };
  1426. interface HistorySectionProps {
  1427. items: PrintQueueItem[];
  1428. collapsed: boolean;
  1429. visibleCount: number;
  1430. onShowMore: () => void;
  1431. sortBy: 'date' | 'name' | 'printer';
  1432. sortAsc: boolean;
  1433. onSortByChange: (v: 'date' | 'name' | 'printer') => void;
  1434. onSortAscToggle: () => void;
  1435. onRemove: (item: PrintQueueItem) => void;
  1436. onRequeue: (item: PrintQueueItem) => void;
  1437. timeFormat: TimeFormat;
  1438. batchCollapsed: Record<number, boolean>;
  1439. toggleBatchCollapsed: (id: number) => void;
  1440. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1441. hasPermission: (p: any) => boolean;
  1442. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  1443. canModify: (resource: any, action: any, createdById?: number | null) => boolean;
  1444. t: (key: string, options?: Record<string, unknown>) => string;
  1445. }
  1446. function HistorySection({
  1447. items,
  1448. visibleCount,
  1449. onShowMore,
  1450. sortBy,
  1451. sortAsc,
  1452. onSortByChange,
  1453. onSortAscToggle,
  1454. onRemove,
  1455. onRequeue,
  1456. timeFormat,
  1457. batchCollapsed,
  1458. toggleBatchCollapsed,
  1459. hasPermission,
  1460. canModify,
  1461. t,
  1462. }: HistorySectionProps) {
  1463. if (items.length === 0) {
  1464. return (
  1465. <Card className="p-12 text-center border-dashed">
  1466. <ListOrdered className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  1467. <h3 className="text-xl font-medium text-white mb-2">{t('queue.history.emptyTitle')}</h3>
  1468. <p className="text-bambu-gray max-w-md mx-auto">{t('queue.history.emptyDescription')}</p>
  1469. </Card>
  1470. );
  1471. }
  1472. // Group siblings sharing a batch_id into a single collapsible row.
  1473. // First-seen order is preserved for batches; items keep their sorted
  1474. // position from the parent's sort selector.
  1475. const rows: HistoryRow[] = [];
  1476. const seenBatches = new Set<number>();
  1477. for (const item of items.slice(0, visibleCount)) {
  1478. if (item.batch_id != null) {
  1479. if (seenBatches.has(item.batch_id)) continue;
  1480. seenBatches.add(item.batch_id);
  1481. const siblings = items.filter((s) => s.batch_id === item.batch_id);
  1482. rows.push({
  1483. kind: 'batch',
  1484. batchId: item.batch_id,
  1485. batchName: item.batch_name || t('queue.batch.defaultName'),
  1486. items: siblings,
  1487. });
  1488. } else {
  1489. rows.push({ kind: 'item', item });
  1490. }
  1491. }
  1492. return (
  1493. <div>
  1494. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  1495. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  1496. {t('queue.sections.history')}
  1497. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  1498. ({t('queue.itemCount', { count: items.length })})
  1499. </span>
  1500. </h2>
  1501. <div className="flex items-center gap-2">
  1502. <select
  1503. className="px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  1504. value={sortBy}
  1505. onChange={(e) => onSortByChange(e.target.value as 'date' | 'name' | 'printer')}
  1506. >
  1507. <option value="date">{t('queue.sort.byDate')}</option>
  1508. <option value="name">{t('queue.sort.byName')}</option>
  1509. <option value="printer">{t('queue.sort.byPrinter')}</option>
  1510. </select>
  1511. <Button
  1512. variant="ghost"
  1513. size="sm"
  1514. onClick={onSortAscToggle}
  1515. title={sortAsc ? t('queue.sort.ascendingOldest') : t('queue.sort.descendingNewest')}
  1516. className="px-2"
  1517. >
  1518. {sortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  1519. </Button>
  1520. </div>
  1521. </div>
  1522. <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
  1523. {rows.map((row) => {
  1524. if (row.kind === 'item') {
  1525. return (
  1526. <CompactHistoryRow
  1527. key={row.item.id}
  1528. item={row.item}
  1529. onRemove={() => onRemove(row.item)}
  1530. onRequeue={() => onRequeue(row.item)}
  1531. timeFormat={timeFormat}
  1532. hasPermission={hasPermission}
  1533. canModify={canModify}
  1534. t={t}
  1535. />
  1536. );
  1537. }
  1538. // Batch group — spans the full grid width so it visually anchors
  1539. // its children below it. The children themselves render in the
  1540. // same responsive grid pattern inside the expanded body.
  1541. const collapsed = batchCollapsed[row.batchId] ?? true;
  1542. const completed = row.items.filter((i) => i.status === 'completed').length;
  1543. const failed = row.items.filter((i) => i.status === 'failed').length;
  1544. const skipped = row.items.filter((i) => i.status === 'skipped').length;
  1545. const cancelled = row.items.filter((i) => i.status === 'cancelled').length;
  1546. const latest = row.items
  1547. .map((i) => i.completed_at || i.created_at)
  1548. .filter((v): v is string => !!v)
  1549. .sort()
  1550. .at(-1);
  1551. return (
  1552. <div
  1553. key={`batch-${row.batchId}`}
  1554. className="md:col-span-2 xl:col-span-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary border-l-[3px] border-l-cyan-400"
  1555. >
  1556. <button
  1557. onClick={() => toggleBatchCollapsed(row.batchId)}
  1558. className="w-full flex items-center gap-2 sm:gap-3 px-3 py-2 hover:bg-bambu-dark/30 transition-colors text-left"
  1559. title={collapsed ? t('queue.batch.expand') : t('queue.batch.collapse')}
  1560. >
  1561. {collapsed ? (
  1562. <ChevronRight className="w-4 h-4 text-bambu-gray shrink-0" />
  1563. ) : (
  1564. <ChevronDown className="w-4 h-4 text-bambu-gray shrink-0" />
  1565. )}
  1566. {collapsed ? (
  1567. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1568. ) : (
  1569. <PackageOpen className="w-5 h-5 text-cyan-700 dark:text-cyan-300 shrink-0" />
  1570. )}
  1571. <span className="text-sm text-white font-medium truncate min-w-0 flex-1">
  1572. {row.batchName}
  1573. </span>
  1574. <div className="flex items-center gap-2 text-xs text-bambu-gray shrink-0">
  1575. {completed > 0 && (
  1576. <span className="flex items-center gap-1 text-emerald-700 dark:text-emerald-400">
  1577. <CheckCircle className="w-3 h-3" />
  1578. {completed}
  1579. </span>
  1580. )}
  1581. {failed > 0 && (
  1582. <span className="flex items-center gap-1 text-red-700 dark:text-red-400">
  1583. <XCircle className="w-3 h-3" />
  1584. {failed}
  1585. </span>
  1586. )}
  1587. {skipped > 0 && (
  1588. <span className="flex items-center gap-1 text-orange-700 dark:text-orange-400">
  1589. <SkipForward className="w-3 h-3" />
  1590. {skipped}
  1591. </span>
  1592. )}
  1593. {cancelled > 0 && (
  1594. <span className="flex items-center gap-1 text-gray-400">
  1595. <Ban className="w-3 h-3" />
  1596. {cancelled}
  1597. </span>
  1598. )}
  1599. <span title={latest ?? undefined}>
  1600. {latest ? formatRelativeTime(latest, timeFormat, t) : null}
  1601. </span>
  1602. </div>
  1603. </button>
  1604. {!collapsed && (
  1605. <div className="border-t border-bambu-dark-tertiary bg-black/20 p-2 grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-2">
  1606. {row.items.map((child) => (
  1607. <CompactHistoryRow
  1608. key={child.id}
  1609. item={child}
  1610. onRemove={() => onRemove(child)}
  1611. onRequeue={() => onRequeue(child)}
  1612. timeFormat={timeFormat}
  1613. hasPermission={hasPermission}
  1614. canModify={canModify}
  1615. t={t}
  1616. />
  1617. ))}
  1618. </div>
  1619. )}
  1620. </div>
  1621. );
  1622. })}
  1623. </div>
  1624. {items.length > visibleCount && (
  1625. <div className="mt-4 flex flex-col items-center gap-2">
  1626. <Button variant="secondary" size="sm" onClick={onShowMore}>
  1627. {t('queue.history.showMore')}
  1628. </Button>
  1629. <span className="text-xs text-bambu-gray">
  1630. {t('queue.history.showingCount', {
  1631. shown: Math.min(visibleCount, items.length),
  1632. total: items.length,
  1633. })}
  1634. </span>
  1635. </div>
  1636. )}
  1637. </div>
  1638. );
  1639. }
  1640. const HISTORY_PAGE_SIZE = 50;
  1641. export function QueuePage() {
  1642. const { t } = useTranslation();
  1643. const queryClient = useQueryClient();
  1644. const { showToast } = useToast();
  1645. const { hasPermission, hasAnyPermission, canModify } = useAuth();
  1646. const [filterPrinter, setFilterPrinter] = useState<number | null>(null);
  1647. const [filterStatus, setFilterStatus] = useState<string>('');
  1648. const [filterLocation, setFilterLocation] = useState<string>('');
  1649. const [showClearHistoryConfirm, setShowClearHistoryConfirm] = useState(false);
  1650. const [editItem, setEditItem] = useState<PrintQueueItem | null>(null);
  1651. const [requeueItem, setRequeueItem] = useState<PrintQueueItem | null>(null);
  1652. const [confirmAction, setConfirmAction] = useState<{
  1653. type: 'cancel' | 'remove' | 'stop';
  1654. item: PrintQueueItem;
  1655. } | null>(null);
  1656. const [selectedItems, setSelectedItems] = useState<number[]>([]);
  1657. const [showBulkEditModal, setShowBulkEditModal] = useState(false);
  1658. // #1818: per-printer Resume-after-failure confirm modal. Tracks which
  1659. // printer's gate the user is about to clear; null when no modal is open.
  1660. const [resumeConfirm, setResumeConfirm] = useState<{
  1661. printerId: number;
  1662. printerName: string;
  1663. skippedCount: number;
  1664. } | null>(null);
  1665. // Same for a model whose waiting jobs are held by failed last prints.
  1666. const [resumeModelConfirm, setResumeModelConfirm] = useState<string | null>(null);
  1667. const [historySortBy, setHistorySortBy] = useState<'date' | 'name' | 'printer'>(() => {
  1668. const saved = localStorage.getItem('queue.historySortBy');
  1669. return (saved as 'date' | 'name' | 'printer') || 'date';
  1670. });
  1671. const [historySortAsc, setHistorySortAsc] = useState(() => {
  1672. const saved = localStorage.getItem('queue.historySortAsc');
  1673. return saved !== null ? saved === 'true' : false;
  1674. });
  1675. // #2682: History renders progressively — start at one page, grow on demand.
  1676. // Reset happens only on a deliberate re-sort / filter change (below), NOT on
  1677. // the periodic queue poll, so an expanded view doesn't snap back mid-scroll.
  1678. const [historyVisibleCount, setHistoryVisibleCount] = useState(HISTORY_PAGE_SIZE);
  1679. const [pendingSortBy, setPendingSortBy] = useState<'position' | 'name' | 'printer' | 'time'>(() => {
  1680. const saved = localStorage.getItem('queue.pendingSortBy');
  1681. return (saved as 'position' | 'name' | 'printer' | 'time') || 'position';
  1682. });
  1683. const [pendingSortAsc, setPendingSortAsc] = useState(() => {
  1684. const saved = localStorage.getItem('queue.pendingSortAsc');
  1685. return saved !== null ? saved === 'true' : true;
  1686. });
  1687. // historyCollapsed legacy state retained only for localStorage migration; the
  1688. // History tab renders unconditionally so this no longer drives the UI.
  1689. // Tabbed page structure: Active queue stays as the main view; History
  1690. // and Timeline split off. Persists per-user via localStorage.
  1691. // /queue?batch=<id>: a link to one batch (e.g. from Bambuddy Orders), read once.
  1692. const [focusBatchId] = useState<number | null>(() => {
  1693. const id = Number(new URLSearchParams(window.location.search).get('batch'));
  1694. return Number.isInteger(id) && id > 0 ? id : null;
  1695. });
  1696. const [activeTab, setActiveTab] = useState<'queue' | 'batches' | 'history' | 'timeline' | 'pipelines'>(() => {
  1697. // URL deep-link wins so the legacy /pipelines/runs redirect lands on the
  1698. // right tab. localStorage holds the per-user last-selected fallback.
  1699. const search = new URLSearchParams(window.location.search);
  1700. const url = search.get('tab');
  1701. // A link to one batch (/queue?batch=<id>) opens the tab that shows it.
  1702. if (search.get('batch')) return 'batches';
  1703. if (url === 'pipelines' || url === 'history' || url === 'timeline' || url === 'queue' || url === 'batches') {
  1704. return url;
  1705. }
  1706. const saved = localStorage.getItem('queue.activeTab');
  1707. if (saved === 'history' || saved === 'timeline' || saved === 'pipelines' || saved === 'batches') return saved;
  1708. return 'queue';
  1709. });
  1710. // Active-tab layout toggle. "position" = today's flat list; "printer"
  1711. // groups items under per-printer section headers with aggregate stats.
  1712. const [activeLayout, setActiveLayout] = useState<'position' | 'printer'>(() => {
  1713. const saved = localStorage.getItem('queue.activeLayout');
  1714. return saved === 'printer' ? 'printer' : 'position';
  1715. });
  1716. // Per-batch collapse state, keyed by batch_id. Default = collapsed
  1717. // (matches the SimplyPrint/Files convention — show the rollup first).
  1718. const [batchCollapsed, setBatchCollapsed] = useState<Record<number, boolean>>(() => {
  1719. try {
  1720. const saved = localStorage.getItem('queue.batchCollapsed');
  1721. return saved ? JSON.parse(saved) : {};
  1722. } catch {
  1723. return {};
  1724. }
  1725. });
  1726. // Multi-drag bookkeeping for DragOverlay. Numeric for single items, string
  1727. // `batch-<id>` when a whole group is being dragged.
  1728. const [activeDragId, setActiveDragId] = useState<number | string | null>(null);
  1729. // "Group as batch" modal.
  1730. const [groupBatchModal, setGroupBatchModal] = useState(false);
  1731. // Ungroup confirm.
  1732. const [ungroupBatchId, setUngroupBatchId] = useState<number | null>(null);
  1733. // Persist sort settings to localStorage
  1734. useEffect(() => {
  1735. localStorage.setItem('queue.historySortBy', historySortBy);
  1736. }, [historySortBy]);
  1737. useEffect(() => {
  1738. localStorage.setItem('queue.historySortAsc', String(historySortAsc));
  1739. }, [historySortAsc]);
  1740. // Collapse History back to a single page when the user re-sorts or changes
  1741. // the location filter (deliberate view changes). Intentionally excludes the
  1742. // queue poll so periodic refetches keep the expanded count.
  1743. useEffect(() => {
  1744. setHistoryVisibleCount(HISTORY_PAGE_SIZE);
  1745. }, [historySortBy, historySortAsc, filterLocation]);
  1746. useEffect(() => {
  1747. localStorage.setItem('queue.pendingSortBy', pendingSortBy);
  1748. }, [pendingSortBy]);
  1749. useEffect(() => {
  1750. localStorage.setItem('queue.pendingSortAsc', String(pendingSortAsc));
  1751. }, [pendingSortAsc]);
  1752. useEffect(() => {
  1753. localStorage.setItem('queue.activeTab', activeTab);
  1754. }, [activeTab]);
  1755. useEffect(() => {
  1756. localStorage.setItem('queue.activeLayout', activeLayout);
  1757. }, [activeLayout]);
  1758. useEffect(() => {
  1759. localStorage.setItem('queue.batchCollapsed', JSON.stringify(batchCollapsed));
  1760. }, [batchCollapsed]);
  1761. const sensors = useSensors(
  1762. useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
  1763. useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  1764. );
  1765. const { data: settings } = useUiSettings();
  1766. const timeFormat: TimeFormat = settings?.time_format || 'system';
  1767. // Badge count for the Batches tab (#342). Deliberately its own query rather
  1768. // than derived from the queue: an order whose runs have all finished has no
  1769. // queue rows left, and those are precisely the orders the tab exists to
  1770. // surface. Shares the ['batches'] key with the tab itself, so dispatching or
  1771. // cancelling refreshes both.
  1772. const { data: activeBatches } = useQuery({
  1773. queryKey: ['batches', 'active'],
  1774. queryFn: () => api.getBatches('active'),
  1775. });
  1776. const activeBatchCount = activeBatches?.length ?? 0;
  1777. const { data: queue, isLoading } = useQuery({
  1778. queryKey: ['queue', filterPrinter, filterStatus],
  1779. queryFn: () => api.getQueue(filterPrinter || undefined, filterStatus || undefined),
  1780. refetchInterval: 5000,
  1781. });
  1782. const { data: printers } = useQuery({
  1783. queryKey: ['printers'],
  1784. queryFn: () => api.getPrinters(),
  1785. });
  1786. const sjfMutation = useMutation({
  1787. mutationFn: (enabled: boolean) => api.updateSettings({ queue_shortest_first: enabled }),
  1788. onSuccess: () => {
  1789. queryClient.invalidateQueries({ queryKey: ['settings'] });
  1790. queryClient.invalidateQueries({ queryKey: ['ui-settings'] });
  1791. },
  1792. });
  1793. const cancelMutation = useMutation({
  1794. mutationFn: (id: number) => api.cancelQueueItem(id),
  1795. onSuccess: () => {
  1796. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1797. showToast(t('queue.toast.cancelled'));
  1798. },
  1799. onError: () => showToast(t('queue.toast.cancelFailed'), 'error'),
  1800. });
  1801. const removeMutation = useMutation({
  1802. mutationFn: (id: number) => api.removeFromQueue(id),
  1803. onSuccess: (result) => {
  1804. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1805. queryClient.invalidateQueries({ queryKey: ['batches'] });
  1806. // The backend keeps an order's last run for a plate, cancelled rather
  1807. // than deleted, so the order can still re-queue it (#2960). Say so:
  1808. // the row stays on screen and silence would read as a failed delete.
  1809. showToast(result.deleted === false ? t('queue.toast.keptForOrder') : t('queue.toast.removed'));
  1810. },
  1811. onError: () => showToast(t('queue.toast.removeFailed'), 'error'),
  1812. });
  1813. const stopMutation = useMutation({
  1814. mutationFn: (id: number) => api.stopQueueItem(id),
  1815. onSuccess: () => {
  1816. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1817. showToast(t('queue.toast.stopped'));
  1818. },
  1819. onError: () => showToast(t('queue.toast.stopFailed'), 'error'),
  1820. });
  1821. // Filament-deficit confirmation state (#1496). When the backend returns
  1822. // 409 with `code=insufficient_filament` we stash the deficit + item id
  1823. // here; the modal at the bottom of the page reads it and the "Print
  1824. // Anyway" path re-issues the start with `skipFilamentCheck=true`.
  1825. const [filamentShortConfirm, setFilamentShortConfirm] = useState<{
  1826. itemId: number;
  1827. deficit: Array<{
  1828. slot_id: number;
  1829. required_grams: number;
  1830. remaining_grams: number | null;
  1831. filament_type?: string | null;
  1832. }>;
  1833. } | null>(null);
  1834. // A filament the printer has no tray for at all (#2799): 409 with
  1835. // `code=unmatched_filament` and the missing filaments. Same "Print Anyway"
  1836. // path as the deficit above.
  1837. const [filamentMissingConfirm, setFilamentMissingConfirm] = useState<{
  1838. itemId: number;
  1839. missing: string[];
  1840. } | null>(null);
  1841. const startMutation = useMutation({
  1842. mutationFn: ({ id, skipFilamentCheck }: { id: number; skipFilamentCheck?: boolean }) =>
  1843. api.startQueueItem(id, { skipFilamentCheck }),
  1844. onSuccess: () => {
  1845. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1846. showToast(t('queue.toast.released'));
  1847. setFilamentShortConfirm(null);
  1848. setFilamentMissingConfirm(null);
  1849. },
  1850. onError: (error: unknown, variables) => {
  1851. if (error instanceof ApiError && error.status === 409 && error.code === 'insufficient_filament') {
  1852. const deficitRaw = (error.detail?.deficit ?? []) as Array<{
  1853. slot_id: number;
  1854. required_grams: number;
  1855. remaining_grams: number | null;
  1856. filament_type?: string | null;
  1857. }>;
  1858. setFilamentShortConfirm({ itemId: variables.id, deficit: deficitRaw });
  1859. return;
  1860. }
  1861. if (error instanceof ApiError && error.status === 409 && error.code === 'unmatched_filament') {
  1862. const missing = (error.detail?.missing ?? []) as string[];
  1863. setFilamentMissingConfirm({ itemId: variables.id, missing });
  1864. return;
  1865. }
  1866. showToast(t('queue.toast.startFailed'), 'error');
  1867. },
  1868. });
  1869. const reorderMutation = useMutation({
  1870. mutationFn: (items: { id: number; position: number }[]) => api.reorderQueue(items),
  1871. onSuccess: () => {
  1872. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1873. },
  1874. onError: () => showToast(t('queue.toast.reorderFailed'), 'error'),
  1875. });
  1876. const clearHistoryMutation = useMutation({
  1877. mutationFn: async () => {
  1878. const historyItems = queue?.filter(i =>
  1879. ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)
  1880. ) || [];
  1881. let cleared = 0;
  1882. let kept = 0;
  1883. for (const item of historyItems) {
  1884. const result = await api.removeFromQueue(item.id);
  1885. // A row a batch order still needs is kept rather than deleted, so the
  1886. // count has to come from what the backend actually did (#2960).
  1887. if (result.deleted === false) kept += 1;
  1888. else cleared += 1;
  1889. }
  1890. return { cleared, kept };
  1891. },
  1892. onSuccess: ({ cleared, kept }) => {
  1893. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1894. queryClient.invalidateQueries({ queryKey: ['batches'] });
  1895. showToast(
  1896. kept > 0
  1897. ? `${t('queue.toast.historyCleared', { count: cleared })} ${t('queue.toast.historyKeptForOrders', { kept })}`
  1898. : t('queue.toast.historyCleared', { count: cleared })
  1899. );
  1900. },
  1901. onError: () => showToast(t('queue.toast.clearHistoryFailed'), 'error'),
  1902. });
  1903. const bulkUpdateMutation = useMutation({
  1904. mutationFn: (data: PrintQueueBulkUpdate) => api.bulkUpdateQueue(data),
  1905. onSuccess: (result) => {
  1906. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1907. setSelectedItems([]);
  1908. setShowBulkEditModal(false);
  1909. const toast = bulkUpdateToast(result);
  1910. showToast(t(toast.key, toast.params), toast.type);
  1911. },
  1912. onError: () => showToast(t('queue.toast.updateFailed'), 'error'),
  1913. });
  1914. const bulkCancelMutation = useMutation({
  1915. mutationFn: async (ids: number[]) => {
  1916. for (const id of ids) {
  1917. await api.cancelQueueItem(id);
  1918. }
  1919. return ids.length;
  1920. },
  1921. onSuccess: (count) => {
  1922. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1923. setSelectedItems([]);
  1924. showToast(t('queue.toast.bulkCancelled', { count }));
  1925. },
  1926. onError: () => showToast(t('queue.toast.bulkCancelFailed'), 'error'),
  1927. });
  1928. const resumeAfterFailureMutation = useMutation({
  1929. mutationFn: (printerId: number) => api.resumeQueueAfterFailure(printerId),
  1930. onSuccess: (result) => {
  1931. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1932. setResumeConfirm(null);
  1933. showToast(
  1934. t('queue.toast.resumedAfterFailure', {
  1935. restored: result.restored,
  1936. acknowledged: result.acknowledged,
  1937. }),
  1938. );
  1939. },
  1940. onError: () => showToast(t('queue.toast.resumeAfterFailureFailed'), 'error'),
  1941. });
  1942. const resumeModelMutation = useMutation({
  1943. mutationFn: (model: string) => api.resumeModelQueueAfterFailure(model),
  1944. onSuccess: (result) => {
  1945. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1946. setResumeModelConfirm(null);
  1947. showToast(t('queue.toast.resumedModelAfterFailure', { count: result.acknowledged }));
  1948. },
  1949. onError: () => showToast(t('queue.toast.resumeAfterFailureFailed'), 'error'),
  1950. });
  1951. const createBatchMutation = useMutation({
  1952. mutationFn: (data: { name: string; item_ids: number[] }) => api.createBatch(data),
  1953. onSuccess: (batch) => {
  1954. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1955. setSelectedItems([]);
  1956. setGroupBatchModal(false);
  1957. // New batches start expanded so the user sees what they just grouped.
  1958. setBatchCollapsed((prev) => ({ ...prev, [batch.id]: false }));
  1959. showToast(t('queue.toast.batchCreated', { name: batch.name }));
  1960. },
  1961. onError: () => showToast(t('queue.toast.batchCreateFailed'), 'error'),
  1962. });
  1963. const ungroupBatchMutation = useMutation({
  1964. mutationFn: (id: number) => api.ungroupBatch(id),
  1965. onSuccess: (result) => {
  1966. queryClient.invalidateQueries({ queryKey: ['queue'] });
  1967. setUngroupBatchId(null);
  1968. showToast(t('queue.toast.batchUngrouped', { count: result.ungrouped_count }));
  1969. },
  1970. onError: () => showToast(t('queue.toast.batchUngroupFailed'), 'error'),
  1971. });
  1972. const handleToggleSelect = (id: number) => {
  1973. setSelectedItems(prev =>
  1974. prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]
  1975. );
  1976. };
  1977. // Get unique locations from printers for the filter dropdown
  1978. const uniqueLocations = useMemo(() => {
  1979. const locations = new Set<string>();
  1980. printers?.forEach(p => {
  1981. if (p.location) locations.add(p.location);
  1982. });
  1983. // Also include locations from queue items (for model-based assignments)
  1984. queue?.forEach(item => {
  1985. if (item.target_location) locations.add(item.target_location);
  1986. });
  1987. return Array.from(locations).sort();
  1988. }, [printers, queue]);
  1989. // Helper to check if a queue item matches the location filter
  1990. const matchesLocationFilter = useCallback((item: PrintQueueItem): boolean => {
  1991. if (!filterLocation) return true;
  1992. // For model-based assignments, check target_location
  1993. if (item.target_location) return item.target_location === filterLocation;
  1994. // For printer-based assignments, check the printer's location
  1995. if (item.printer_id) {
  1996. const printer = printers?.find(p => p.id === item.printer_id);
  1997. return printer?.location === filterLocation;
  1998. }
  1999. return false;
  2000. }, [filterLocation, printers]);
  2001. const pendingItems = useMemo(() => {
  2002. let items = queue?.filter(i => i.status === 'pending') || [];
  2003. // Apply location filter
  2004. if (filterLocation) {
  2005. items = items.filter(matchesLocationFilter);
  2006. }
  2007. // Helper to get scheduled time as timestamp (ASAP/placeholder = 0 for earliest)
  2008. const getScheduledTime = (item: PrintQueueItem): number => {
  2009. if (!item.scheduled_time) return 0;
  2010. const time = parseUTCDate(item.scheduled_time)?.getTime() ?? 0;
  2011. // Placeholder dates (> 6 months out) are treated as ASAP
  2012. const sixMonthsFromNow = Date.now() + (180 * 24 * 60 * 60 * 1000);
  2013. return time > sixMonthsFromNow ? 0 : time;
  2014. };
  2015. // When SJF is enabled, override sort to match scheduler order
  2016. if (settings?.queue_shortest_first) {
  2017. return [...items].sort((a, b) => compareQueueOrder(a, b, true));
  2018. }
  2019. return [...items].sort((a, b) => {
  2020. let cmp: number;
  2021. if (pendingSortBy === 'name') {
  2022. const aName = a.archive_name || a.library_file_name || '';
  2023. const bName = b.archive_name || b.library_file_name || '';
  2024. cmp = aName.localeCompare(bName);
  2025. } else if (pendingSortBy === 'printer') {
  2026. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  2027. } else if (pendingSortBy === 'time') {
  2028. // Sort by scheduled start time (when print will begin)
  2029. cmp = getScheduledTime(a) - getScheduledTime(b);
  2030. } else {
  2031. cmp = a.position - b.position;
  2032. }
  2033. return pendingSortAsc ? cmp : -cmp;
  2034. });
  2035. }, [queue, pendingSortBy, pendingSortAsc, matchesLocationFilter, filterLocation, settings?.queue_shortest_first]);
  2036. const handleSelectAll = () => {
  2037. const allPendingIds = pendingItems.map(i => i.id);
  2038. if (selectedItems.length === allPendingIds.length) {
  2039. setSelectedItems([]);
  2040. } else {
  2041. setSelectedItems(allPendingIds);
  2042. }
  2043. };
  2044. const activeItems = useMemo(() => {
  2045. let items = queue?.filter(i => i.status === 'printing') || [];
  2046. if (filterLocation) {
  2047. items = items.filter(matchesLocationFilter);
  2048. }
  2049. return items;
  2050. }, [queue, filterLocation, matchesLocationFilter]);
  2051. // Queue items eligible for an "if started now" ETA (#2740).
  2052. //
  2053. // The ETA answers "when would this finish if it began right now", so it may
  2054. // only appear on items that really could begin right now. waiting_reason now
  2055. // covers the pinned-printer case too (#3074), but it is still not enough on
  2056. // its own: it says whether the scheduler had a reason to hold the item on its
  2057. // last pass, not whether this item is the one that printer takes next. Two
  2058. // items pinned to the same free printer both come back with no reason, and
  2059. // only one of them can start now — which is what the ordering below works out.
  2060. //
  2061. // Computed from the unfiltered queue on purpose — hiding a printer behind the
  2062. // location filter must not make its printer look free.
  2063. const etaEligibleIds = useMemo(() => {
  2064. const eligible = new Set<number>();
  2065. if (!queue) return eligible;
  2066. const busyPrinters = new Set<number>();
  2067. queue.forEach(item => {
  2068. if (item.status === 'printing' && item.printer_id) busyPrinters.add(item.printer_id);
  2069. });
  2070. const isFutureScheduled = (item: PrintQueueItem): boolean => {
  2071. if (!item.scheduled_time) return false;
  2072. return (parseUTCDate(item.scheduled_time)?.getTime() ?? 0) > Date.now();
  2073. };
  2074. // Mirrors the scheduler's own ordering so "next up" here means the item the
  2075. // scheduler would actually dispatch next, not whatever the user sorted by.
  2076. // Bucketed by printer immediately below, so the within-lane comparator is
  2077. // the right one -- no cross-lane grouping needed.
  2078. const schedulerOrder = (a: PrintQueueItem, b: PrintQueueItem): number =>
  2079. compareQueueOrder(a, b, settings?.queue_shortest_first ?? false);
  2080. // Claimants for each printer, in the order the scheduler would take them.
  2081. // Staged and future-scheduled items are excluded: the scheduler skips both
  2082. // without marking the printer busy, so neither holds up the item behind it.
  2083. const contenders = new Map<number, PrintQueueItem[]>();
  2084. queue
  2085. .filter(
  2086. item =>
  2087. item.status === 'pending' &&
  2088. item.printer_id != null &&
  2089. !item.manual_start &&
  2090. !isFutureScheduled(item)
  2091. )
  2092. .sort(schedulerOrder)
  2093. .forEach(item => {
  2094. const list = contenders.get(item.printer_id!) ?? [];
  2095. list.push(item);
  2096. contenders.set(item.printer_id!, list);
  2097. });
  2098. queue.forEach(item => {
  2099. if (item.status !== 'pending') return;
  2100. // Blocked, scheduled for later, or no usable duration to add.
  2101. if (item.waiting_reason) return;
  2102. if (isFutureScheduled(item)) return;
  2103. if (item.print_time_seconds == null || item.print_time_seconds <= 0) return;
  2104. // Conditional on an earlier print's outcome, which the UI cannot see: the
  2105. // scheduler may skip it outright rather than ever running it.
  2106. if (item.require_previous_success) return;
  2107. // Model-based items have no printer yet; an empty waiting_reason is the
  2108. // scheduler saying it found one, so trust that.
  2109. if (item.printer_id == null) {
  2110. eligible.add(item.id);
  2111. return;
  2112. }
  2113. if (busyPrinters.has(item.printer_id)) return;
  2114. // Staged items wait on the user, not on the queue, so they are startable
  2115. // whenever their printer is free regardless of what is queued ahead.
  2116. if (item.manual_start) {
  2117. eligible.add(item.id);
  2118. return;
  2119. }
  2120. if (contenders.get(item.printer_id)?.[0]?.id === item.id) eligible.add(item.id);
  2121. });
  2122. return eligible;
  2123. }, [queue, settings?.queue_shortest_first]);
  2124. // The ETA is "now + duration", so it goes stale on its own. Nothing else
  2125. // re-renders these rows while the queue payload is unchanged (react-query's
  2126. // structural sharing keeps the reference stable), so drive it from a clock of
  2127. // our own. Only runs while an ETA is actually on screen.
  2128. const [etaNow, setEtaNow] = useState(() => Date.now());
  2129. const hasEtas = etaEligibleIds.size > 0;
  2130. useEffect(() => {
  2131. if (!hasEtas) return;
  2132. setEtaNow(Date.now());
  2133. const id = setInterval(() => setEtaNow(Date.now()), 30000);
  2134. return () => clearInterval(id);
  2135. }, [hasEtas]);
  2136. // Get unique printer IDs from active items to fetch their statuses
  2137. const activePrinterIds = useMemo(() => {
  2138. const ids = new Set<number>();
  2139. activeItems.forEach(item => {
  2140. if (item.printer_id) ids.add(item.printer_id);
  2141. });
  2142. return Array.from(ids);
  2143. }, [activeItems]);
  2144. // Fetch printer statuses for printers with active jobs
  2145. const printerStatusQueries = useQueries({
  2146. queries: activePrinterIds.map(printerId => ({
  2147. queryKey: ['printerStatus', printerId],
  2148. queryFn: () => api.getPrinterStatus(printerId),
  2149. refetchInterval: 5000,
  2150. })),
  2151. });
  2152. // Build a map of printer_id -> state for quick lookup
  2153. const printerStateMap = useMemo(() => {
  2154. const map: Record<number, string | null> = {};
  2155. activePrinterIds.forEach((printerId, index) => {
  2156. const result = printerStatusQueries[index];
  2157. if (result?.data?.state) {
  2158. map[printerId] = result.data.state;
  2159. }
  2160. });
  2161. return map;
  2162. }, [activePrinterIds, printerStatusQueries]);
  2163. // Build a map of printer_id -> full status for timeline view
  2164. const printerStatusMap = useMemo(() => {
  2165. const map: Record<number, { progress?: number; remaining_time?: number; state?: string }> = {};
  2166. activePrinterIds.forEach((printerId, index) => {
  2167. const result = printerStatusQueries[index];
  2168. if (result?.data) {
  2169. map[printerId] = {
  2170. progress: result.data.progress ?? undefined,
  2171. remaining_time: result.data.remaining_time ?? undefined,
  2172. state: result.data.state ?? undefined,
  2173. };
  2174. }
  2175. });
  2176. return map;
  2177. }, [activePrinterIds, printerStatusQueries]);
  2178. const historyItems = useMemo(() => {
  2179. let items = queue?.filter(i => ['completed', 'failed', 'skipped', 'cancelled'].includes(i.status)) || [];
  2180. if (filterLocation) {
  2181. items = items.filter(matchesLocationFilter);
  2182. }
  2183. return [...items].sort((a, b) => {
  2184. let cmp: number;
  2185. if (historySortBy === 'name') {
  2186. const aName = a.archive_name || a.library_file_name || '';
  2187. const bName = b.archive_name || b.library_file_name || '';
  2188. cmp = aName.localeCompare(bName);
  2189. } else if (historySortBy === 'printer') {
  2190. cmp = (a.printer_name || '').localeCompare(b.printer_name || '');
  2191. } else {
  2192. // Default: by date - most recent first (desc) is the natural order
  2193. cmp = (parseUTCDate(b.completed_at || b.created_at)?.getTime() ?? 0) - (parseUTCDate(a.completed_at || a.created_at)?.getTime() ?? 0);
  2194. }
  2195. return historySortAsc ? -cmp : cmp;
  2196. });
  2197. }, [queue, historySortBy, historySortAsc, matchesLocationFilter, filterLocation]);
  2198. // Calculate total queue time
  2199. const totalQueueTime = useMemo(() => {
  2200. return pendingItems.reduce((acc, item) => acc + (item.print_time_seconds || 0), 0);
  2201. }, [pendingItems]);
  2202. // Calculate total material weight
  2203. const totalWeight = useMemo(() => {
  2204. return pendingItems.reduce((acc, item) => acc + (item.filament_used_grams || 0), 0);
  2205. }, [pendingItems]);
  2206. const handleDragStart = (event: DragStartEvent) => {
  2207. const id = event.active.id;
  2208. setActiveDragId(typeof id === 'number' || typeof id === 'string' ? id : null);
  2209. };
  2210. const handleDragEnd = (event: DragEndEvent) => {
  2211. const { active, over } = event;
  2212. setActiveDragId(null);
  2213. if (!over || active.id === over.id) return;
  2214. // Resolve dragged source → movingIds (preserving order from pendingItems).
  2215. // - `batch-<id>`: every child of that batch, in their current order
  2216. // - selected + dragged is one of them: contiguous multi-drag block
  2217. // - otherwise: single row
  2218. let movingIds: number[];
  2219. const activeId = active.id;
  2220. if (typeof activeId === 'string' && activeId.startsWith('batch-')) {
  2221. const batchId = Number(activeId.slice('batch-'.length));
  2222. movingIds = pendingItems.filter((i) => i.batch_id === batchId).map((i) => i.id);
  2223. } else {
  2224. const draggedId = activeId as number;
  2225. movingIds = selectedItems.includes(draggedId) && selectedItems.length > 1
  2226. ? selectedItems.slice().sort((a, b) => {
  2227. const ai = pendingItems.findIndex((i) => i.id === a);
  2228. const bi = pendingItems.findIndex((i) => i.id === b);
  2229. return ai - bi;
  2230. })
  2231. : [draggedId];
  2232. }
  2233. if (movingIds.length === 0) return;
  2234. // Resolve drop target → index inside pendingItems. A `batch-<id>` drop
  2235. // target anchors at the batch's first child, so dropping above another
  2236. // batch lands the moving block immediately before it.
  2237. let overIndex: number;
  2238. const overId = over.id;
  2239. if (typeof overId === 'string' && overId.startsWith('batch-')) {
  2240. const overBatchId = Number(overId.slice('batch-'.length));
  2241. overIndex = pendingItems.findIndex((i) => i.batch_id === overBatchId);
  2242. } else {
  2243. overIndex = pendingItems.findIndex((i) => i.id === overId);
  2244. }
  2245. if (overIndex === -1) return;
  2246. // Remove the moving items, then re-insert at overIndex (adjusted).
  2247. const overAnchor = pendingItems[overIndex];
  2248. const remaining = pendingItems.filter((i) => !movingIds.includes(i.id));
  2249. let insertAt = remaining.findIndex((i) => i.id === overAnchor.id);
  2250. if (insertAt === -1) insertAt = overIndex;
  2251. // If dragging downward across the drop target, insert AFTER it; upward
  2252. // = before. dnd-kit's `over` is the row under the pointer, not the gap.
  2253. const firstMovingIndex = pendingItems.findIndex((i) => i.id === movingIds[0]);
  2254. if (firstMovingIndex < overIndex) insertAt += 1;
  2255. const reordered = [
  2256. ...remaining.slice(0, insertAt),
  2257. ...movingIds
  2258. .map((id) => pendingItems.find((i) => i.id === id))
  2259. .filter((x): x is PrintQueueItem => !!x),
  2260. ...remaining.slice(insertAt),
  2261. ];
  2262. const updates = reordered.map((item, index) => ({
  2263. id: item.id,
  2264. position: index + 1,
  2265. }));
  2266. reorderMutation.mutate(updates);
  2267. };
  2268. // Group pending items by batch_id. Items with batch_id null render as
  2269. // standalone rows; items sharing a batch_id render as a collapsible
  2270. // group keyed by that id. Items inside a group keep their original
  2271. // relative order from pendingItems.
  2272. const groupedRows = useMemo<QueueRow[]>(() => {
  2273. const rows: QueueRow[] = [];
  2274. const seenBatches = new Set<number>();
  2275. for (const item of pendingItems) {
  2276. if (item.batch_id != null) {
  2277. if (seenBatches.has(item.batch_id)) continue;
  2278. seenBatches.add(item.batch_id);
  2279. const siblings = pendingItems.filter((s) => s.batch_id === item.batch_id);
  2280. rows.push({
  2281. kind: 'batch',
  2282. batchId: item.batch_id,
  2283. batchName: item.batch_name || t('queue.batch.defaultName'),
  2284. items: siblings,
  2285. });
  2286. } else {
  2287. rows.push({ kind: 'item', item });
  2288. }
  2289. }
  2290. return rows;
  2291. }, [pendingItems, t]);
  2292. // Mobile tap-to-reorder (#2667). The desktop drag handle is hidden on
  2293. // phones and touch-drag is unreliable, so pending rows get up/down arrows.
  2294. // Reordering only has a defined meaning in the manual "position" sort with
  2295. // SJF off — any other sort re-orders the list itself, so we don't offer it.
  2296. const canReorderManually =
  2297. hasPermission('queue:reorder') &&
  2298. pendingSortBy === 'position' &&
  2299. !settings?.queue_shortest_first;
  2300. const rowItemIds = (row: QueueRow): number[] =>
  2301. row.kind === 'item' ? [row.item.id] : row.items.map((i) => i.id);
  2302. // Move a block of items to sit immediately before (or after) an anchor item
  2303. // in the global pending order, then persist — the same remove-and-reinsert
  2304. // shape as handleDragEnd, so arrows and drag agree. Anchoring to a real item
  2305. // id keeps it correct in the printer-grouped layout, where a bucket's rows
  2306. // aren't contiguous in the global order.
  2307. const moveBlockRelativeTo = (
  2308. movingIds: number[],
  2309. anchorId: number,
  2310. placeAfter: boolean,
  2311. ) => {
  2312. const remaining = pendingItems.filter((i) => !movingIds.includes(i.id));
  2313. let insertAt = remaining.findIndex((i) => i.id === anchorId);
  2314. if (insertAt === -1) return;
  2315. if (placeAfter) insertAt += 1;
  2316. const movingItems = movingIds
  2317. .map((id) => pendingItems.find((i) => i.id === id))
  2318. .filter((x): x is PrintQueueItem => !!x);
  2319. const reordered = [
  2320. ...remaining.slice(0, insertAt),
  2321. ...movingItems,
  2322. ...remaining.slice(insertAt),
  2323. ];
  2324. reorderMutation.mutate(
  2325. reordered.map((item, index) => ({ id: item.id, position: index + 1 })),
  2326. );
  2327. };
  2328. // Build up/down thunks for the row at `idx` within its displayed sibling
  2329. // list (the flat list, or a single printer bucket). Undefined at a boundary
  2330. // (button rendered disabled) or when manual reorder isn't available.
  2331. const rowMovers = (
  2332. rows: QueueRow[],
  2333. idx: number,
  2334. ): { onMoveUp?: () => void; onMoveDown?: () => void } => {
  2335. if (!canReorderManually) return {};
  2336. const moving = rowItemIds(rows[idx]);
  2337. const onMoveUp =
  2338. idx > 0
  2339. ? () => moveBlockRelativeTo(moving, rowItemIds(rows[idx - 1])[0], false)
  2340. : undefined;
  2341. const onMoveDown =
  2342. idx < rows.length - 1
  2343. ? () => {
  2344. const next = rowItemIds(rows[idx + 1]);
  2345. moveBlockRelativeTo(moving, next[next.length - 1], true);
  2346. }
  2347. : undefined;
  2348. return { onMoveUp, onMoveDown };
  2349. };
  2350. // SortableContext ID list.
  2351. // - Standalone pending items: their numeric id.
  2352. // - Batch parents: the synthetic `batch-<id>` string, always present so the
  2353. // group itself is draggable and acts as a drop target whether collapsed
  2354. // or expanded.
  2355. // - Expanded batch children: their numeric id, so within-batch reorder
  2356. // keeps working. Collapsed children are detached from the DOM and
  2357. // intentionally omitted to keep dnd-kit's collision resolver clean.
  2358. const sortableIds = useMemo<(number | string)[]>(() => {
  2359. const ids: (number | string)[] = [];
  2360. for (const row of groupedRows) {
  2361. if (row.kind === 'item') {
  2362. ids.push(row.item.id);
  2363. } else {
  2364. ids.push(`batch-${row.batchId}`);
  2365. const collapsed = batchCollapsed[row.batchId] ?? true;
  2366. if (!collapsed) {
  2367. for (const child of row.items) ids.push(child.id);
  2368. }
  2369. }
  2370. }
  2371. return ids;
  2372. }, [groupedRows, batchCollapsed]);
  2373. // Items already in a batch can't be grouped; "Group as batch" only shows
  2374. // when 2+ ungrouped items are selected.
  2375. const canGroupSelected = useMemo(() => {
  2376. if (selectedItems.length < 2) return false;
  2377. return selectedItems.every((id) => {
  2378. const item = pendingItems.find((p) => p.id === id);
  2379. return item && item.batch_id == null;
  2380. });
  2381. }, [selectedItems, pendingItems]);
  2382. const toggleBatchCollapsed = (id: number) => {
  2383. setBatchCollapsed((prev) => ({ ...prev, [id]: !(prev[id] ?? true) }));
  2384. };
  2385. // Group by printer view. Items are bucketed by printer_id (null = model
  2386. // assignment or unassigned, keyed by target_model or "unassigned").
  2387. type PrinterBucket = {
  2388. key: string;
  2389. printerId: number | null;
  2390. targetModel: string | null;
  2391. label: string;
  2392. isUnassigned: boolean;
  2393. rows: QueueRow[];
  2394. };
  2395. const printerBuckets = useMemo<PrinterBucket[]>(() => {
  2396. const buckets = new Map<string, PrinterBucket>();
  2397. const bucketForItem = (item: PrintQueueItem): { key: string; label: string; printerId: number | null; targetModel: string | null; isUnassigned: boolean } => {
  2398. if (item.printer_id) {
  2399. return {
  2400. key: `printer:${item.printer_id}`,
  2401. label: item.printer_name || `Printer #${item.printer_id}`,
  2402. printerId: item.printer_id,
  2403. targetModel: null,
  2404. isUnassigned: false,
  2405. };
  2406. }
  2407. // A cross-model item (#671) is waiting on several models. Its own
  2408. // target_model is just the first candidate mirrored onto the row, so
  2409. // bucketing on it would file the job under one printer it might never
  2410. // run on — and the row underneath already says "Any H2D / X1C".
  2411. if ((item.variants?.length ?? 0) > 1) {
  2412. const models = item.variants!.map((v) => v.target_model).join(' / ');
  2413. return {
  2414. key: `models:${models}`,
  2415. label: `${t('queue.filter.any')} ${models}`,
  2416. printerId: null,
  2417. targetModel: null,
  2418. isUnassigned: false,
  2419. };
  2420. }
  2421. if (item.target_model) {
  2422. return {
  2423. key: `model:${item.target_model}`,
  2424. label: `${t('queue.filter.any')} ${item.target_model}`,
  2425. printerId: null,
  2426. targetModel: item.target_model,
  2427. isUnassigned: false,
  2428. };
  2429. }
  2430. return {
  2431. key: 'unassigned',
  2432. label: t('queue.filter.unassigned'),
  2433. printerId: null,
  2434. targetModel: null,
  2435. isUnassigned: true,
  2436. };
  2437. };
  2438. for (const row of groupedRows) {
  2439. const representative = row.kind === 'item' ? row.item : row.items[0];
  2440. if (!representative) continue;
  2441. const meta = bucketForItem(representative);
  2442. if (!buckets.has(meta.key)) {
  2443. buckets.set(meta.key, { ...meta, rows: [] });
  2444. }
  2445. buckets.get(meta.key)!.rows.push(row);
  2446. }
  2447. return Array.from(buckets.values()).sort((a, b) => {
  2448. if (a.isUnassigned && !b.isUnassigned) return 1;
  2449. if (!a.isUnassigned && b.isUnassigned) return -1;
  2450. return a.label.localeCompare(b.label);
  2451. });
  2452. }, [groupedRows, t]);
  2453. // #1818: printers whose queue is gated by a prior failure that's poisoning
  2454. // downstream `require_previous_success` items. We surface a per-printer
  2455. // Resume banner above the active queue so the user can clear the gate +
  2456. // restore the skipped jobs in one click, without re-queuing each one.
  2457. // Detection key: skipped + the scheduler's exact gate string. Other skip
  2458. // reasons (filament deficit, etc.) get their own UX and stay untouched.
  2459. const gateBlockedPrinters = useMemo<
  2460. Array<{ printerId: number; printerName: string; skippedCount: number }>
  2461. >(() => {
  2462. const counts = new Map<number, { name: string; count: number }>();
  2463. queue?.forEach((item) => {
  2464. if (
  2465. item.status === 'skipped' &&
  2466. item.error_message === 'Previous print failed or was aborted' &&
  2467. item.printer_id
  2468. ) {
  2469. const existing = counts.get(item.printer_id);
  2470. if (existing) {
  2471. existing.count += 1;
  2472. } else {
  2473. counts.set(item.printer_id, {
  2474. name: item.printer_name || `Printer #${item.printer_id}`,
  2475. count: 1,
  2476. });
  2477. }
  2478. }
  2479. });
  2480. return Array.from(counts.entries())
  2481. .map(([printerId, { name, count }]) => ({
  2482. printerId,
  2483. printerName: name,
  2484. skippedCount: count,
  2485. }))
  2486. .sort((a, b) => a.printerName.localeCompare(b.printerName));
  2487. }, [queue]);
  2488. // Models whose "any printer" jobs wait because the last print failed on
  2489. // every free printer of the model (the scheduler's MODEL_GATE_WAIT_REASON).
  2490. const gateBlockedModels = useMemo<Array<{ model: string; waitingCount: number }>>(() => {
  2491. const counts = new Map<string, number>();
  2492. queue?.forEach((item) => {
  2493. if (
  2494. item.status === 'pending' &&
  2495. !item.printer_id &&
  2496. item.target_model &&
  2497. item.waiting_reason === MODEL_GATE_WAIT_REASON
  2498. ) {
  2499. counts.set(item.target_model, (counts.get(item.target_model) ?? 0) + 1);
  2500. }
  2501. });
  2502. return Array.from(counts.entries())
  2503. .map(([model, waitingCount]) => ({ model, waitingCount }))
  2504. .sort((a, b) => a.model.localeCompare(b.model));
  2505. }, [queue]);
  2506. const aggregateForRows = (rows: QueueRow[]) => {
  2507. let count = 0;
  2508. let time = 0;
  2509. let weight = 0;
  2510. for (const row of rows) {
  2511. const items = row.kind === 'item' ? [row.item] : row.items;
  2512. for (const item of items) {
  2513. count += 1;
  2514. time += item.print_time_seconds || 0;
  2515. weight += item.filament_used_grams || 0;
  2516. }
  2517. }
  2518. return { count, time, weight };
  2519. };
  2520. return (
  2521. <div className="p-4 md:p-8">
  2522. {/* Header */}
  2523. <div className="flex items-center justify-between mb-6">
  2524. <div>
  2525. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  2526. <ListOrdered className="w-7 h-7 text-bambu-green" />
  2527. {t('queue.title')}
  2528. </h1>
  2529. <p className="text-bambu-gray mt-1">{t('queue.subtitle')}</p>
  2530. </div>
  2531. </div>
  2532. {/* Tab strip — Active queue is the main view; History and Timeline
  2533. live in their own tabs so the queue page stays focused. */}
  2534. <div className="flex gap-1 border-b border-bambu-dark-tertiary mb-6 overflow-x-auto">
  2535. {([
  2536. { id: 'queue' as const, label: t('queue.tabs.queue'), icon: Clock, count: pendingItems.length + activeItems.length },
  2537. { id: 'batches' as const, label: t('queue.tabs.batches'), icon: Package, count: activeBatchCount },
  2538. { id: 'history' as const, label: t('queue.tabs.history'), icon: ListOrdered, count: historyItems.length },
  2539. { id: 'timeline' as const, label: t('queue.tabs.timeline'), icon: GanttChart, count: null as number | null },
  2540. // Slicer Pipelines dashboard (#1425 PR C). Lives here instead of
  2541. // its own sidebar entry so the Print Queue page is the single
  2542. // place an operator looks for "what's running / what ran".
  2543. { id: 'pipelines' as const, label: t('queue.tabs.pipelines'), icon: Workflow, count: null as number | null },
  2544. ]).map(({ id, label, icon: Icon, count }) => (
  2545. <button
  2546. key={id}
  2547. onClick={() => setActiveTab(id)}
  2548. className={`px-4 py-2.5 text-sm flex items-center gap-2 border-b-2 -mb-px transition-colors whitespace-nowrap ${
  2549. activeTab === id
  2550. ? 'text-white border-bambu-green font-medium'
  2551. : 'text-bambu-gray border-transparent hover:text-white'
  2552. }`}
  2553. >
  2554. <Icon className="w-4 h-4" />
  2555. {label}
  2556. {count !== null && count > 0 && (
  2557. <span className={`text-xs px-1.5 py-0.5 rounded-full ${
  2558. activeTab === id ? 'bg-bambu-green/20 text-bambu-green' : 'bg-bambu-dark-tertiary text-bambu-gray'
  2559. }`}>
  2560. {count}
  2561. </span>
  2562. )}
  2563. </button>
  2564. ))}
  2565. </div>
  2566. {/* Summary Stats — about the print queue, not pipelines. */}
  2567. {activeTab !== 'pipelines' && activeTab !== 'batches' && <QueueStatsBar
  2568. activeCount={activeItems.length}
  2569. pendingCount={pendingItems.length}
  2570. totalTime={totalQueueTime}
  2571. totalWeight={totalWeight}
  2572. historyCount={historyItems.length}
  2573. t={t}
  2574. />}
  2575. {/* #1818: Resume-after-failure banner. One row per printer whose queue
  2576. is gated by a prior failed/aborted print. Visible regardless of
  2577. tab/layout so the user can clear the gate without hunting for
  2578. skipped items. Hidden entirely when no gates are active. */}
  2579. {activeTab === 'queue' && gateBlockedPrinters.length > 0 && hasPermission('queue:update_all' as Permission) && (
  2580. <div className="mb-4 space-y-2">
  2581. {gateBlockedPrinters.map(({ printerId, printerName, skippedCount }) => (
  2582. <div
  2583. key={printerId}
  2584. className="flex items-center gap-3 px-4 py-3 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg"
  2585. >
  2586. <AlertCircle className="w-5 h-5 text-orange-600 dark:text-orange-400 flex-shrink-0" />
  2587. <div className="flex-1 min-w-0">
  2588. <div className="text-sm text-orange-800 dark:text-orange-200">
  2589. {t('queue.resumeAfterFailure.banner', {
  2590. printer: printerName,
  2591. count: skippedCount,
  2592. })}
  2593. </div>
  2594. <div className="text-xs text-orange-800/80 dark:text-orange-200/70 mt-0.5">
  2595. {t('queue.resumeAfterFailure.bannerHint')}
  2596. </div>
  2597. </div>
  2598. <button
  2599. onClick={() =>
  2600. setResumeConfirm({ printerId, printerName, skippedCount })
  2601. }
  2602. className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-100 dark:bg-orange-500/20 hover:bg-orange-200 dark:hover:bg-orange-500/30 text-orange-900 dark:text-orange-100 text-sm rounded-md border border-orange-300 dark:border-orange-500/40 transition-colors flex-shrink-0"
  2603. >
  2604. <PlayCircle className="w-4 h-4" />
  2605. {t('queue.resumeAfterFailure.button')}
  2606. </button>
  2607. </div>
  2608. ))}
  2609. </div>
  2610. )}
  2611. {activeTab === 'queue' && gateBlockedModels.length > 0 && hasPermission('queue:update_all' as Permission) && (
  2612. <div className="mb-4 space-y-2">
  2613. {gateBlockedModels.map(({ model, waitingCount }) => (
  2614. <div
  2615. key={model}
  2616. className="flex items-center gap-3 px-4 py-3 bg-orange-50 dark:bg-orange-500/10 border border-orange-300 dark:border-orange-500/30 rounded-lg"
  2617. >
  2618. <AlertCircle className="w-5 h-5 text-orange-600 dark:text-orange-400 flex-shrink-0" />
  2619. <div className="flex-1 min-w-0">
  2620. <div className="text-sm text-orange-800 dark:text-orange-200">
  2621. {t('queue.resumeModelAfterFailure.banner', { model, count: waitingCount })}
  2622. </div>
  2623. <div className="text-xs text-orange-800/80 dark:text-orange-200/70 mt-0.5">
  2624. {t('queue.resumeModelAfterFailure.bannerHint', { model })}
  2625. </div>
  2626. </div>
  2627. <button
  2628. onClick={() => setResumeModelConfirm(model)}
  2629. className="flex items-center gap-1.5 px-3 py-1.5 bg-orange-100 dark:bg-orange-500/20 hover:bg-orange-200 dark:hover:bg-orange-500/30 text-orange-900 dark:text-orange-100 text-sm rounded-md border border-orange-300 dark:border-orange-500/40 transition-colors flex-shrink-0"
  2630. >
  2631. <PlayCircle className="w-4 h-4" />
  2632. {t('queue.resumeAfterFailure.button')}
  2633. </button>
  2634. </div>
  2635. ))}
  2636. </div>
  2637. )}
  2638. {/* Filters — about the print queue items (printer / status / location).
  2639. The Pipelines tab has its own pipeline + status filters inside the
  2640. dashboard, so this row is hidden when that tab is active. */}
  2641. {activeTab !== 'pipelines' && activeTab !== 'batches' && (
  2642. <div className="flex flex-wrap items-center gap-2 sm:gap-4 mb-6">
  2643. <select
  2644. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2645. value={filterPrinter === -1 ? 'unassigned' : (filterPrinter || '')}
  2646. onChange={(e) => {
  2647. const val = e.target.value;
  2648. if (val === 'unassigned') setFilterPrinter(-1);
  2649. else if (val === '') setFilterPrinter(null);
  2650. else setFilterPrinter(Number(val));
  2651. }}
  2652. >
  2653. <option value="">{t('queue.filter.allPrinters')}</option>
  2654. <option value="unassigned">{t('queue.filter.unassigned')}</option>
  2655. {printers?.map((p) => (
  2656. <option key={p.id} value={p.id}>{p.name}</option>
  2657. ))}
  2658. </select>
  2659. <select
  2660. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2661. value={filterStatus}
  2662. onChange={(e) => setFilterStatus(e.target.value)}
  2663. >
  2664. <option value="">{t('queue.filter.allStatus')}</option>
  2665. <option value="pending">{t('queue.status.pending')}</option>
  2666. <option value="printing">{t('queue.status.printing')}</option>
  2667. <option value="completed">{t('queue.status.completed')}</option>
  2668. <option value="failed">{t('queue.status.failed')}</option>
  2669. <option value="skipped">{t('queue.status.skipped')}</option>
  2670. <option value="cancelled">{t('queue.status.cancelled')}</option>
  2671. </select>
  2672. {uniqueLocations.length > 0 && (
  2673. <select
  2674. className="px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none"
  2675. value={filterLocation}
  2676. onChange={(e) => setFilterLocation(e.target.value)}
  2677. >
  2678. <option value="">{t('queue.filter.allLocations')}</option>
  2679. {uniqueLocations.map((loc) => (
  2680. <option key={loc} value={loc}>{loc}</option>
  2681. ))}
  2682. </select>
  2683. )}
  2684. <div className="hidden sm:block flex-1" />
  2685. {activeTab === 'history' && historyItems.length > 0 && (
  2686. <Button
  2687. className="w-full sm:w-auto"
  2688. variant="secondary"
  2689. size="sm"
  2690. onClick={() => setShowClearHistoryConfirm(true)}
  2691. disabled={!hasPermission('queue:delete_all')}
  2692. title={!hasPermission('queue:delete_all') ? t('queue.permissions.noClearHistory') : undefined}
  2693. >
  2694. <Trash2 className="w-4 h-4" />
  2695. {t('queue.clearHistory')}
  2696. </Button>
  2697. )}
  2698. </div>
  2699. )}
  2700. {/* Queue-tab controls: layout toggle (Position / Printer) + SJF.
  2701. Hidden on History/Timeline tabs since they don't apply. */}
  2702. {activeTab === 'queue' && (
  2703. <div className="flex flex-wrap items-center gap-3 mb-6">
  2704. <div className="inline-flex items-center bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-0.5">
  2705. <button
  2706. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  2707. activeLayout === 'position' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  2708. }`}
  2709. onClick={() => setActiveLayout('position')}
  2710. title={t('queue.layout.flatList')}
  2711. >
  2712. <List className="w-3.5 h-3.5" />
  2713. <span className="hidden sm:inline">{t('queue.layout.flatList')}</span>
  2714. </button>
  2715. <button
  2716. className={`px-3 py-1.5 text-xs sm:text-sm rounded-md transition-colors flex items-center gap-1.5 ${
  2717. activeLayout === 'printer' ? 'bg-bambu-dark-tertiary text-white' : 'text-bambu-gray hover:text-white'
  2718. }`}
  2719. onClick={() => setActiveLayout('printer')}
  2720. title={t('queue.layout.groupByPrinter')}
  2721. >
  2722. <Printer className="w-3.5 h-3.5" />
  2723. <span className="hidden sm:inline">{t('queue.layout.byPrinter')}</span>
  2724. </button>
  2725. </div>
  2726. <button
  2727. onClick={() => {
  2728. const newValue = !(settings?.queue_shortest_first ?? false);
  2729. sjfMutation.mutate(newValue);
  2730. }}
  2731. className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
  2732. settings?.queue_shortest_first
  2733. ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
  2734. : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
  2735. }`}
  2736. title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
  2737. >
  2738. <Snail className="w-4 h-4" />
  2739. <span className="hidden sm:inline">{t('queue.sjf.label', 'SJF')}</span>
  2740. <span className={`w-1.5 h-1.5 rounded-full ${settings?.queue_shortest_first ? 'bg-bambu-green' : 'bg-bambu-gray'}`} />
  2741. </button>
  2742. </div>
  2743. )}
  2744. {/* Pipelines tab short-circuits before the queue-empty branch so the
  2745. dashboard renders even when the regular queue is empty. */}
  2746. {activeTab === 'pipelines' ? (
  2747. <PipelineRunsView />
  2748. ) : activeTab === 'batches' ? (
  2749. <BatchOrdersView hasPermission={hasPermission} t={t} focusBatchId={focusBatchId} />
  2750. ) : isLoading ? (
  2751. <div className="text-center py-12 text-bambu-gray">{t('common.loading')}</div>
  2752. ) : queue?.length === 0 ? (
  2753. <Card className="p-12 text-center border-dashed">
  2754. <Calendar className="w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50" />
  2755. <h3 className="text-xl font-medium text-white mb-2">{t('queue.empty.title')}</h3>
  2756. <p className="text-bambu-gray max-w-md mx-auto">
  2757. {t('queue.empty.description')}
  2758. </p>
  2759. </Card>
  2760. ) : activeTab === 'timeline' ? (
  2761. <QueueTimelineView
  2762. queueItems={queue || []}
  2763. printers={printers || []}
  2764. printerStatuses={printerStatusMap}
  2765. sjfEnabled={settings?.queue_shortest_first ?? false}
  2766. onItemClick={(item) => {
  2767. if (['completed', 'failed', 'skipped', 'cancelled'].includes(item.status)) {
  2768. setRequeueItem(item);
  2769. } else if (item.status === 'pending') {
  2770. setEditItem(item);
  2771. } else if (item.status === 'printing') {
  2772. setConfirmAction({ type: 'stop', item });
  2773. }
  2774. }}
  2775. t={t}
  2776. />
  2777. ) : activeTab === 'history' ? (
  2778. <HistorySection
  2779. items={historyItems}
  2780. collapsed={false}
  2781. visibleCount={historyVisibleCount}
  2782. onShowMore={() => setHistoryVisibleCount((c) => c + HISTORY_PAGE_SIZE)}
  2783. sortBy={historySortBy}
  2784. sortAsc={historySortAsc}
  2785. onSortByChange={setHistorySortBy}
  2786. onSortAscToggle={() => setHistorySortAsc(!historySortAsc)}
  2787. onRemove={(item) => setConfirmAction({ type: 'remove', item })}
  2788. onRequeue={setRequeueItem}
  2789. timeFormat={timeFormat}
  2790. batchCollapsed={batchCollapsed}
  2791. toggleBatchCollapsed={toggleBatchCollapsed}
  2792. hasPermission={hasPermission}
  2793. canModify={canModify}
  2794. t={t}
  2795. />
  2796. ) : (
  2797. <div className="space-y-6 sm:space-y-8">
  2798. {/* Active Prints */}
  2799. {activeItems.length > 0 && (
  2800. <div>
  2801. <h2 className="text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2">
  2802. <div className="w-2 h-2 rounded-full bg-blue-400 animate-pulse" />
  2803. {t('queue.sections.currentlyPrinting')}
  2804. </h2>
  2805. <div className="space-y-2 sm:space-y-3">
  2806. {activeItems.map((item) => (
  2807. <SortableQueueItem
  2808. key={item.id}
  2809. item={item}
  2810. onEdit={() => {}}
  2811. onCancel={() => {}}
  2812. onRemove={() => {}}
  2813. onStop={() => setConfirmAction({ type: 'stop', item })}
  2814. onRequeue={() => {}}
  2815. onStart={() => {}}
  2816. timeFormat={timeFormat}
  2817. hasPermission={hasPermission}
  2818. canModify={canModify}
  2819. printerState={item.printer_id ? printerStateMap[item.printer_id] : null}
  2820. t={t}
  2821. />
  2822. ))}
  2823. </div>
  2824. </div>
  2825. )}
  2826. {/* Pending Queue */}
  2827. {pendingItems.length > 0 && (
  2828. <div>
  2829. <div className="flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4">
  2830. <h2 className="text-base sm:text-lg font-semibold text-white flex items-center gap-2">
  2831. <Clock className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 dark:text-yellow-400" />
  2832. {t('queue.sections.queued')}
  2833. <span className="text-xs sm:text-sm font-normal text-bambu-gray">
  2834. ({t('queue.itemCount', { count: pendingItems.length })})
  2835. </span>
  2836. <span className="hidden sm:inline text-xs text-bambu-gray ml-2" title={t('queue.reorderHint')}>
  2837. {t('queue.dragToReorder')}
  2838. </span>
  2839. </h2>
  2840. <div className="flex items-center gap-2">
  2841. <select
  2842. className="px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"
  2843. value={pendingSortBy}
  2844. onChange={(e) => setPendingSortBy(e.target.value as 'position' | 'name' | 'printer' | 'time')}
  2845. >
  2846. <option value="position">{t('queue.sort.byPosition')}</option>
  2847. <option value="name">{t('queue.sort.byName')}</option>
  2848. <option value="printer">{t('queue.sort.byPrinter')}</option>
  2849. <option value="time">{t('queue.sort.bySchedule')}</option>
  2850. </select>
  2851. <Button
  2852. variant="ghost"
  2853. size="sm"
  2854. onClick={() => setPendingSortAsc(!pendingSortAsc)}
  2855. title={pendingSortAsc ? t('common.ascending') : t('common.descending')}
  2856. className="px-2"
  2857. >
  2858. {pendingSortAsc ? <ArrowUp className="w-4 h-4" /> : <ArrowDown className="w-4 h-4" />}
  2859. </Button>
  2860. </div>
  2861. </div>
  2862. {/* Bulk action toolbar (now with "Group as batch") */}
  2863. <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg">
  2864. <Button
  2865. variant="ghost"
  2866. size="sm"
  2867. onClick={handleSelectAll}
  2868. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm"
  2869. >
  2870. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? (
  2871. <CheckSquare className="w-4 h-4 text-bambu-green" />
  2872. ) : (
  2873. <Square className="w-4 h-4" />
  2874. )}
  2875. {selectedItems.length === pendingItems.length && pendingItems.length > 0 ? t('queue.bulkEdit.deselectAll') : t('queue.bulkEdit.selectAll')}
  2876. </Button>
  2877. {selectedItems.length > 0 && (
  2878. <>
  2879. <span className="text-xs sm:text-sm text-bambu-gray">
  2880. {t('queue.bulkEdit.selected', { count: selectedItems.length })}
  2881. </span>
  2882. <div className="hidden sm:block h-4 w-px bg-bambu-dark-tertiary" />
  2883. {canGroupSelected && (
  2884. <Button
  2885. variant="ghost"
  2886. size="sm"
  2887. onClick={() => setGroupBatchModal(true)}
  2888. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-cyan-700 dark:text-cyan-300 hover:text-cyan-900 dark:hover:text-cyan-200"
  2889. title={t('queue.batch.groupAsBatch')}
  2890. >
  2891. <Package className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2892. <span className="hidden sm:inline">{t('queue.batch.groupAsBatch')}</span>
  2893. </Button>
  2894. )}
  2895. <Button
  2896. variant="ghost"
  2897. size="sm"
  2898. onClick={() => setShowBulkEditModal(true)}
  2899. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light"
  2900. disabled={!hasAnyPermission('queue:update_own', 'queue:update_all')}
  2901. title={!hasAnyPermission('queue:update_own', 'queue:update_all') ? t('queue.permissions.noEditItems') : t('queue.bulkEdit.editSelected')}
  2902. >
  2903. <Pencil className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2904. <span className="hidden sm:inline">{t('queue.bulkEdit.editSelected')}</span>
  2905. </Button>
  2906. <Button
  2907. variant="ghost"
  2908. size="sm"
  2909. onClick={() => bulkCancelMutation.mutate(selectedItems)}
  2910. className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300"
  2911. disabled={bulkCancelMutation.isPending || !hasAnyPermission('queue:delete_own', 'queue:delete_all')}
  2912. title={!hasAnyPermission('queue:delete_own', 'queue:delete_all') ? t('queue.permissions.noCancelItems') : t('queue.bulkEdit.cancelSelected')}
  2913. >
  2914. <X className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
  2915. <span className="hidden sm:inline">{t('queue.bulkEdit.cancelSelected')}</span>
  2916. </Button>
  2917. </>
  2918. )}
  2919. </div>
  2920. <DndContext
  2921. sensors={sensors}
  2922. collisionDetection={closestCenter}
  2923. onDragStart={handleDragStart}
  2924. onDragEnd={handleDragEnd}
  2925. >
  2926. <SortableContext
  2927. items={sortableIds}
  2928. strategy={verticalListSortingStrategy}
  2929. >
  2930. {activeLayout === 'position' ? (
  2931. <div className="space-y-2 sm:space-y-3">
  2932. {groupedRows.map((row, idx) => (
  2933. <QueueRowRender
  2934. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2935. row={row}
  2936. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2937. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2938. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2939. setEditItem={setEditItem}
  2940. setConfirmAction={setConfirmAction}
  2941. startMutation={startMutation}
  2942. selectedItems={selectedItems}
  2943. handleToggleSelect={handleToggleSelect}
  2944. timeFormat={timeFormat}
  2945. hasPermission={hasPermission}
  2946. canModify={canModify}
  2947. t={t}
  2948. etaEligibleIds={etaEligibleIds}
  2949. etaNow={etaNow}
  2950. aggregateForRows={aggregateForRows}
  2951. {...rowMovers(groupedRows, idx)}
  2952. onMoveBlock={canReorderManually ? moveBlockRelativeTo : undefined}
  2953. />
  2954. ))}
  2955. </div>
  2956. ) : (
  2957. <div className="space-y-4">
  2958. {printerBuckets.map((bucket) => {
  2959. const agg = aggregateForRows(bucket.rows);
  2960. return (
  2961. <div key={bucket.key}>
  2962. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-t-lg">
  2963. <Printer className={`w-4 h-4 ${bucket.isUnassigned ? 'text-orange-600 dark:text-orange-400' : bucket.targetModel ? 'text-blue-600 dark:text-blue-400' : 'text-bambu-green'}`} />
  2964. <span className="font-semibold text-white text-sm">{bucket.label}</span>
  2965. <span className="text-xs text-bambu-gray flex flex-wrap gap-x-3">
  2966. <span>{t('queue.itemCount', { count: agg.count })}</span>
  2967. {agg.time > 0 && <span>{formatDuration(agg.time)}</span>}
  2968. {agg.weight > 0 && <span>{formatWeight(agg.weight)}</span>}
  2969. </span>
  2970. </div>
  2971. <div className="bg-bambu-dark/40 border border-t-0 border-bambu-dark-tertiary rounded-b-lg p-2 space-y-2">
  2972. {bucket.rows.map((row, idx) => (
  2973. <QueueRowRender
  2974. key={row.kind === 'item' ? `item-${row.item.id}` : `batch-${row.batchId}`}
  2975. row={row}
  2976. collapsed={row.kind === 'batch' ? (batchCollapsed[row.batchId] ?? true) : false}
  2977. onToggleBatch={row.kind === 'batch' ? () => toggleBatchCollapsed(row.batchId) : undefined}
  2978. onUngroup={row.kind === 'batch' ? () => setUngroupBatchId(row.batchId) : undefined}
  2979. setEditItem={setEditItem}
  2980. setConfirmAction={setConfirmAction}
  2981. startMutation={startMutation}
  2982. selectedItems={selectedItems}
  2983. handleToggleSelect={handleToggleSelect}
  2984. timeFormat={timeFormat}
  2985. hasPermission={hasPermission}
  2986. canModify={canModify}
  2987. t={t}
  2988. etaEligibleIds={etaEligibleIds}
  2989. etaNow={etaNow}
  2990. aggregateForRows={aggregateForRows}
  2991. {...rowMovers(bucket.rows, idx)}
  2992. onMoveBlock={canReorderManually ? moveBlockRelativeTo : undefined}
  2993. />
  2994. ))}
  2995. </div>
  2996. </div>
  2997. );
  2998. })}
  2999. </div>
  3000. )}
  3001. </SortableContext>
  3002. <DragOverlay>
  3003. {(() => {
  3004. if (activeDragId === null) return null;
  3005. // Batch drag — show the group ghost with copy count.
  3006. if (typeof activeDragId === 'string' && activeDragId.startsWith('batch-')) {
  3007. const batchId = Number(activeDragId.slice('batch-'.length));
  3008. const siblings = pendingItems.filter((i) => i.batch_id === batchId);
  3009. if (siblings.length === 0) return null;
  3010. const name = siblings[0].batch_name || t('queue.batch.defaultName');
  3011. return (
  3012. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  3013. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  3014. <span className="text-sm text-white font-medium">
  3015. {t('queue.dragGhost.batch', {
  3016. defaultValue: '{{name}} ({{count}} copies)',
  3017. name,
  3018. count: siblings.length,
  3019. })}
  3020. </span>
  3021. </div>
  3022. );
  3023. }
  3024. // Multi-row drag — show the N-item ghost.
  3025. if (typeof activeDragId === 'number' && selectedItems.includes(activeDragId) && selectedItems.length > 1) {
  3026. return (
  3027. <div className="flex items-center gap-3 px-3 py-2 bg-bambu-dark-secondary border-2 border-cyan-400 rounded-lg shadow-2xl">
  3028. <Package className="w-4 h-4 text-cyan-700 dark:text-cyan-300" />
  3029. <span className="text-sm text-white font-medium">
  3030. {t('queue.dragGhost.multiCount', { count: selectedItems.length })}
  3031. </span>
  3032. </div>
  3033. );
  3034. }
  3035. return null;
  3036. })()}
  3037. </DragOverlay>
  3038. </DndContext>
  3039. </div>
  3040. )}
  3041. </div>
  3042. )}
  3043. {/* Edit Modal */}
  3044. {editItem && (
  3045. <PrintModal
  3046. mode="edit-queue-item"
  3047. archiveId={editItem.archive_id ?? undefined}
  3048. libraryFileId={editItem.library_file_id ?? undefined}
  3049. archiveName={queueItemDisplayName(editItem, (n) => t('common.plusNMore', { count: n }))}
  3050. queueItem={editItem}
  3051. onClose={() => setEditItem(null)}
  3052. />
  3053. )}
  3054. {/* Re-queue Modal */}
  3055. {requeueItem && (
  3056. <PrintModal
  3057. mode="create"
  3058. archiveId={requeueItem.archive_id ?? undefined}
  3059. libraryFileId={requeueItem.library_file_id ?? undefined}
  3060. archiveName={queueItemDisplayName(requeueItem, (n) => t('common.plusNMore', { count: n }))}
  3061. onClose={() => setRequeueItem(null)}
  3062. />
  3063. )}
  3064. {/* Confirm Action Modal */}
  3065. {filamentShortConfirm && (
  3066. <ConfirmModal
  3067. title={t('queue.filamentShort.confirmTitle')}
  3068. message={
  3069. t('queue.filamentShort.confirmIntro') + '\n\n' +
  3070. filamentShortConfirm.deficit
  3071. .map((d) =>
  3072. t('queue.filamentShort.lineItem', {
  3073. slot: d.slot_id,
  3074. required: Math.round(d.required_grams),
  3075. remaining:
  3076. d.remaining_grams == null
  3077. ? t('queue.filamentShort.unknown')
  3078. : Math.round(d.remaining_grams),
  3079. }),
  3080. )
  3081. .join('\n')
  3082. }
  3083. confirmText={t('queue.filamentShort.printAnyway')}
  3084. variant="warning"
  3085. onConfirm={() => {
  3086. startMutation.mutate({ id: filamentShortConfirm.itemId, skipFilamentCheck: true });
  3087. }}
  3088. onCancel={() => setFilamentShortConfirm(null)}
  3089. />
  3090. )}
  3091. {filamentMissingConfirm && (
  3092. <ConfirmModal
  3093. title={t('queue.filamentMissing.confirmTitle')}
  3094. message={t('queue.filamentMissing.confirmIntro') + '\n\n' + filamentMissingConfirm.missing.join('\n')}
  3095. confirmText={t('queue.filamentShort.printAnyway')}
  3096. variant="warning"
  3097. onConfirm={() => {
  3098. startMutation.mutate({ id: filamentMissingConfirm.itemId, skipFilamentCheck: true });
  3099. }}
  3100. onCancel={() => setFilamentMissingConfirm(null)}
  3101. />
  3102. )}
  3103. {confirmAction && (
  3104. <ConfirmModal
  3105. title={
  3106. confirmAction.type === 'cancel' ? t('queue.confirm.cancelTitle') :
  3107. confirmAction.type === 'stop' ? t('queue.confirm.stopTitle') :
  3108. t('queue.confirm.removeTitle')
  3109. }
  3110. message={
  3111. confirmAction.type === 'cancel'
  3112. ? t('queue.confirm.cancelMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  3113. : confirmAction.type === 'stop'
  3114. ? t('queue.confirm.stopMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisPrint') })
  3115. : t('queue.confirm.removeMessage', { name: confirmAction.item.archive_name || confirmAction.item.library_file_name || t('queue.confirm.thisItem') })
  3116. }
  3117. confirmText={
  3118. confirmAction.type === 'cancel' ? t('queue.confirm.cancelButton') :
  3119. confirmAction.type === 'stop' ? t('queue.confirm.stopButton') :
  3120. t('common.remove')
  3121. }
  3122. variant="danger"
  3123. onConfirm={() => {
  3124. if (confirmAction.type === 'cancel') {
  3125. cancelMutation.mutate(confirmAction.item.id);
  3126. } else if (confirmAction.type === 'stop') {
  3127. stopMutation.mutate(confirmAction.item.id);
  3128. } else {
  3129. removeMutation.mutate(confirmAction.item.id);
  3130. }
  3131. setConfirmAction(null);
  3132. }}
  3133. onCancel={() => setConfirmAction(null)}
  3134. />
  3135. )}
  3136. {/* #1818: Resume-after-failure confirm */}
  3137. {resumeConfirm && (
  3138. <ConfirmModal
  3139. title={t('queue.resumeAfterFailure.confirmTitle')}
  3140. message={t('queue.resumeAfterFailure.confirmMessage', {
  3141. printer: resumeConfirm.printerName,
  3142. count: resumeConfirm.skippedCount,
  3143. })}
  3144. confirmText={t('queue.resumeAfterFailure.button')}
  3145. variant="warning"
  3146. onConfirm={() => resumeAfterFailureMutation.mutate(resumeConfirm.printerId)}
  3147. onCancel={() => setResumeConfirm(null)}
  3148. />
  3149. )}
  3150. {resumeModelConfirm && (
  3151. <ConfirmModal
  3152. title={t('queue.resumeAfterFailure.confirmTitle')}
  3153. message={t('queue.resumeModelAfterFailure.confirmMessage', { model: resumeModelConfirm })}
  3154. confirmText={t('queue.resumeAfterFailure.button')}
  3155. variant="warning"
  3156. onConfirm={() => resumeModelMutation.mutate(resumeModelConfirm)}
  3157. onCancel={() => setResumeModelConfirm(null)}
  3158. />
  3159. )}
  3160. {/* Clear History Confirm Modal */}
  3161. {showClearHistoryConfirm && (
  3162. <ConfirmModal
  3163. title={t('queue.confirm.clearHistoryTitle')}
  3164. message={t('queue.confirm.clearHistoryMessage', { count: historyItems.length })}
  3165. confirmText={t('queue.clearHistory')}
  3166. variant="danger"
  3167. onConfirm={() => {
  3168. clearHistoryMutation.mutate();
  3169. setShowClearHistoryConfirm(false);
  3170. }}
  3171. onCancel={() => setShowClearHistoryConfirm(false)}
  3172. />
  3173. )}
  3174. {/* Bulk Edit Modal */}
  3175. {showBulkEditModal && (
  3176. <BulkEditModal
  3177. selectedCount={selectedItems.length}
  3178. printers={printers?.map(p => ({ id: p.id, name: p.name, nozzle_count: p.nozzle_count })) || []}
  3179. onSave={(data) => {
  3180. if (Object.keys(data).length > 0) {
  3181. bulkUpdateMutation.mutate({ item_ids: selectedItems, ...data });
  3182. }
  3183. }}
  3184. onClose={() => setShowBulkEditModal(false)}
  3185. isSaving={bulkUpdateMutation.isPending}
  3186. canControlPrinter={hasPermission('printers:control')}
  3187. hasGcodeSnippets={hasGcodeSnippets(settings)}
  3188. t={t}
  3189. />
  3190. )}
  3191. {/* Group as batch modal — name prompt */}
  3192. {groupBatchModal && (
  3193. <GroupBatchModal
  3194. itemCount={selectedItems.length}
  3195. isSaving={createBatchMutation.isPending}
  3196. defaultName={(() => {
  3197. // Suggest a name derived from the first selected item's source.
  3198. const first = pendingItems.find((i) => selectedItems.includes(i.id));
  3199. const raw = first?.archive_name || first?.library_file_name || '';
  3200. const cleaned = raw.replace(/\.gcode\.3mf$/i, '').replace(/\.3mf$/i, '');
  3201. return cleaned ? `${cleaned}` : t('queue.batch.defaultName');
  3202. })()}
  3203. onSave={(name) => createBatchMutation.mutate({ name, item_ids: selectedItems })}
  3204. onClose={() => setGroupBatchModal(false)}
  3205. t={t}
  3206. />
  3207. )}
  3208. {/* Ungroup batch confirm */}
  3209. {ungroupBatchId !== null && (
  3210. <ConfirmModal
  3211. title={t('queue.batch.ungroupConfirmTitle')}
  3212. message={t('queue.batch.ungroupConfirmMessage')}
  3213. confirmText={t('queue.batch.ungroup')}
  3214. variant="warning"
  3215. onConfirm={() => ungroupBatchMutation.mutate(ungroupBatchId)}
  3216. onCancel={() => setUngroupBatchId(null)}
  3217. />
  3218. )}
  3219. </div>
  3220. );
  3221. }
  3222. interface GroupBatchModalProps {
  3223. itemCount: number;
  3224. defaultName: string;
  3225. isSaving: boolean;
  3226. onSave: (name: string) => void;
  3227. onClose: () => void;
  3228. t: (key: string, options?: Record<string, unknown>) => string;
  3229. }
  3230. function GroupBatchModal({ itemCount, defaultName, isSaving, onSave, onClose, t }: GroupBatchModalProps) {
  3231. const [name, setName] = useState(defaultName);
  3232. return (
  3233. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
  3234. <div className="bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-6 w-full max-w-md">
  3235. <h3 className="text-lg font-semibold text-white mb-2 flex items-center gap-2">
  3236. <Package className="w-5 h-5 text-cyan-700 dark:text-cyan-300" />
  3237. {t('queue.batch.groupAsBatch')}
  3238. </h3>
  3239. <p className="text-sm text-bambu-gray mb-4">
  3240. {t('queue.batch.groupAsBatchDescription', { count: itemCount })}
  3241. </p>
  3242. <label className="block text-sm font-medium text-white mb-2">
  3243. {t('queue.batch.nameLabel')}
  3244. </label>
  3245. <input
  3246. type="text"
  3247. autoFocus
  3248. value={name}
  3249. onChange={(e) => setName(e.target.value)}
  3250. placeholder={t('queue.batch.namePlaceholder')}
  3251. maxLength={120}
  3252. 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 mb-5"
  3253. />
  3254. <div className="flex justify-end gap-2">
  3255. <Button variant="ghost" size="sm" onClick={onClose} disabled={isSaving}>
  3256. {t('common.cancel')}
  3257. </Button>
  3258. <Button
  3259. variant="primary"
  3260. size="sm"
  3261. onClick={() => {
  3262. const trimmed = name.trim();
  3263. if (trimmed) onSave(trimmed);
  3264. }}
  3265. disabled={isSaving || !name.trim()}
  3266. >
  3267. {isSaving ? t('common.saving') : t('queue.batch.create')}
  3268. </Button>
  3269. </div>
  3270. </div>
  3271. </div>
  3272. );
  3273. }