QueuePage.tsx 121 KB

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