QueuePage.tsx 129 KB

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