FileManagerPage.tsx 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776
  1. import { useState, useRef, useCallback, useMemo, useEffect } from 'react';
  2. import { Link, useNavigate, useSearchParams } from 'react-router-dom';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import {
  6. FolderOpen,
  7. Loader2,
  8. Plus,
  9. Upload,
  10. Trash2,
  11. Download,
  12. MoreVertical,
  13. ChevronRight,
  14. FolderPlus,
  15. FileBox,
  16. Clock,
  17. CalendarClock,
  18. HardDrive,
  19. File,
  20. MoveRight,
  21. CheckSquare,
  22. Square,
  23. LayoutGrid,
  24. List,
  25. Search,
  26. SortAsc,
  27. SortDesc,
  28. AlertTriangle,
  29. Filter,
  30. X,
  31. Link2,
  32. Unlink,
  33. Archive as ArchiveIcon,
  34. Briefcase,
  35. Cog,
  36. Play,
  37. Printer,
  38. Pencil,
  39. Image,
  40. User,
  41. Box,
  42. RefreshCw,
  43. Lock,
  44. FolderSymlink,
  45. Tag as TagIcon,
  46. } from 'lucide-react';
  47. import { api } from '../api/client';
  48. import type {
  49. LibraryFolderTree,
  50. LibraryFileListItem,
  51. LibraryFolderCreate,
  52. LibraryFolderUpdate,
  53. ExternalFolderCreate,
  54. AppSettings,
  55. Archive,
  56. Permission,
  57. } from '../api/client';
  58. import { Button } from '../components/Button';
  59. import { ConfirmModal } from '../components/ConfirmModal';
  60. import { PrintModal } from '../components/PrintModal';
  61. import { ModelViewerModal } from '../components/ModelViewerModal';
  62. import { SliceModal } from '../components/SliceModal';
  63. import { RunWithPipelineModal } from '../components/RunWithPipelineModal';
  64. import { BulkTagsPickerModal } from '../components/BulkTagsPickerModal';
  65. import { FileUploadModal } from '../components/FileUploadModal';
  66. import { FolderReadmePanel } from '../components/FolderReadmePanel';
  67. import { LibraryTagsModal } from '../components/LibraryTagsModal';
  68. import { PurgeOldFilesModal } from '../components/PurgeOldFilesModal';
  69. import { useToast } from '../contexts/ToastContext';
  70. import { useIsMobile } from '../hooks/useIsMobile';
  71. import { usePageFileDrop } from '../hooks/usePageFileDrop';
  72. import { useAuth } from '../contexts/AuthContext';
  73. import { formatDuration, parseUTCDate, formatDate } from '../utils/date';
  74. import { formatFileSize } from '../utils/file';
  75. type SortField = 'name' | 'date' | 'size' | 'type' | 'prints';
  76. type SortDirection = 'asc' | 'desc';
  77. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  78. // New Folder Modal
  79. interface NewFolderModalProps {
  80. parentId: number | null;
  81. onClose: () => void;
  82. onSave: (data: LibraryFolderCreate) => void;
  83. isLoading: boolean;
  84. t: TFunction;
  85. }
  86. function NewFolderModal({ parentId, onClose, onSave, isLoading, t }: NewFolderModalProps) {
  87. const [name, setName] = useState('');
  88. const handleSubmit = (e: React.FormEvent) => {
  89. e.preventDefault();
  90. onSave({ name: name.trim(), parent_id: parentId });
  91. };
  92. return (
  93. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  94. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
  95. <div className="p-4 border-b border-bambu-dark-tertiary">
  96. <h2 className="text-lg font-semibold text-white">{t('fileManager.newFolder')}</h2>
  97. </div>
  98. <form onSubmit={handleSubmit} className="p-4 space-y-4">
  99. <div>
  100. <label className="block text-sm font-medium text-white mb-1">
  101. {t('fileManager.folderName')}
  102. </label>
  103. <input
  104. type="text"
  105. value={name}
  106. onChange={(e) => setName(e.target.value)}
  107. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  108. placeholder={t('fileManager.folderNamePlaceholder')}
  109. autoFocus
  110. required
  111. />
  112. </div>
  113. <div className="flex justify-end gap-2 pt-2">
  114. <Button type="button" variant="secondary" onClick={onClose}>
  115. {t('common.cancel')}
  116. </Button>
  117. <Button type="submit" disabled={!name.trim() || isLoading}>
  118. {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.create')}
  119. </Button>
  120. </div>
  121. </form>
  122. </div>
  123. </div>
  124. );
  125. }
  126. // External Folder Modal
  127. interface ExternalFolderModalProps {
  128. onClose: () => void;
  129. onSave: (data: ExternalFolderCreate) => void;
  130. isLoading: boolean;
  131. t: TFunction;
  132. }
  133. function ExternalFolderModal({ onClose, onSave, isLoading, t }: ExternalFolderModalProps) {
  134. const [name, setName] = useState('');
  135. const [path, setPath] = useState('');
  136. const [readonly, setReadonly] = useState(true);
  137. const [showHidden, setShowHidden] = useState(false);
  138. const handleSubmit = (e: React.FormEvent) => {
  139. e.preventDefault();
  140. onSave({
  141. name: name.trim(),
  142. external_path: path.trim(),
  143. readonly,
  144. show_hidden: showHidden,
  145. });
  146. };
  147. return (
  148. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  149. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary">
  150. <div className="p-4 border-b border-bambu-dark-tertiary">
  151. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  152. <FolderSymlink className="w-5 h-5 text-bambu-green" />
  153. {t('fileManager.linkExternalFolder')}
  154. </h2>
  155. <p className="text-sm text-bambu-gray mt-1">{t('fileManager.linkExternalFolderDescription')}</p>
  156. </div>
  157. <form onSubmit={handleSubmit} className="p-4 space-y-4">
  158. <div>
  159. <label className="block text-sm font-medium text-white mb-1">
  160. {t('fileManager.folderName')}
  161. </label>
  162. <input
  163. type="text"
  164. value={name}
  165. onChange={(e) => setName(e.target.value)}
  166. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  167. placeholder={t('fileManager.externalFolderNamePlaceholder')}
  168. autoFocus
  169. required
  170. />
  171. </div>
  172. <div>
  173. <label className="block text-sm font-medium text-white mb-1">
  174. {t('fileManager.externalPath')}
  175. </label>
  176. <input
  177. type="text"
  178. value={path}
  179. onChange={(e) => setPath(e.target.value)}
  180. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green font-mono text-sm"
  181. placeholder="/mnt/nas/3d-prints"
  182. required
  183. />
  184. <p className="text-xs text-bambu-gray mt-1">{t('fileManager.externalPathHelp')}</p>
  185. </div>
  186. <div className="space-y-2">
  187. <label className="flex items-center gap-2 cursor-pointer">
  188. <input
  189. type="checkbox"
  190. checked={readonly}
  191. onChange={(e) => setReadonly(e.target.checked)}
  192. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  193. />
  194. <span className="text-sm text-white">{t('fileManager.readOnly')}</span>
  195. <span className="text-xs text-bambu-gray">({t('fileManager.readOnlyHelp')})</span>
  196. </label>
  197. <label className="flex items-center gap-2 cursor-pointer">
  198. <input
  199. type="checkbox"
  200. checked={showHidden}
  201. onChange={(e) => setShowHidden(e.target.checked)}
  202. className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
  203. />
  204. <span className="text-sm text-white">{t('fileManager.showHiddenFiles')}</span>
  205. </label>
  206. </div>
  207. <div className="flex justify-end gap-2 pt-2">
  208. <Button type="button" variant="secondary" onClick={onClose}>
  209. {t('common.cancel')}
  210. </Button>
  211. <Button type="submit" disabled={!name.trim() || !path.trim() || isLoading}>
  212. {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('fileManager.linkFolder')}
  213. </Button>
  214. </div>
  215. </form>
  216. </div>
  217. </div>
  218. );
  219. }
  220. // FAT32/exFAT-illegal chars rejected by Bambu Studio (#1540). Mirrors the
  221. // backend validator in backend/app/utils/filename.py — keep in sync.
  222. const INVALID_FILENAME_CHARS = '<>:"/\\|?*';
  223. function findInvalidFilenameChar(name: string): string | null {
  224. for (const ch of name) {
  225. if (INVALID_FILENAME_CHARS.includes(ch)) return ch;
  226. if (ch.charCodeAt(0) < 0x20) return ch;
  227. }
  228. return null;
  229. }
  230. // Rename Modal
  231. interface RenameModalProps {
  232. type: 'file' | 'folder';
  233. currentName: string;
  234. onClose: () => void;
  235. onSave: (newName: string) => void;
  236. isLoading: boolean;
  237. t: TFunction;
  238. }
  239. function RenameModal({ type, currentName, onClose, onSave, isLoading, t }: RenameModalProps) {
  240. // For files, separate the extension so users can only edit the base name
  241. // Handle compound extensions like .gcode.3mf
  242. const fileExtension = type === 'file' ? (currentName.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1] ?? '') : '';
  243. const baseName = type === 'file' && fileExtension ? currentName.slice(0, -fileExtension.length) : currentName;
  244. const [name, setName] = useState(baseName);
  245. const invalidChar = type === 'file' ? findInvalidFilenameChar(name) : null;
  246. const filenameError = invalidChar
  247. ? t('fileManager.invalidFilenameChar', { char: invalidChar })
  248. : null;
  249. const handleSubmit = (e: React.FormEvent) => {
  250. e.preventDefault();
  251. if (filenameError) return;
  252. const fullName = type === 'file' ? name.trim() + fileExtension : name.trim();
  253. if (name.trim() && fullName !== currentName) {
  254. onSave(fullName);
  255. }
  256. };
  257. return (
  258. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  259. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
  260. <div className="p-4 border-b border-bambu-dark-tertiary">
  261. <h2 className="text-lg font-semibold text-white">{type === 'file' ? t('fileManager.renameFile') : t('fileManager.renameFolder')}</h2>
  262. </div>
  263. <form onSubmit={handleSubmit} className="p-4 space-y-4">
  264. <div>
  265. <label className="block text-sm font-medium text-white mb-1">
  266. {t('common.name')}
  267. </label>
  268. <div className={`flex items-center bg-bambu-dark border rounded focus-within:border-bambu-green ${filenameError ? 'border-red-500' : 'border-bambu-dark-tertiary'}`}>
  269. <input
  270. type="text"
  271. value={name}
  272. onChange={(e) => setName(e.target.value)}
  273. className="flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0"
  274. autoFocus
  275. required
  276. />
  277. {fileExtension && (
  278. <span className="pr-3 text-bambu-gray text-sm select-none whitespace-nowrap">{fileExtension}</span>
  279. )}
  280. </div>
  281. {filenameError && (
  282. <p className="mt-1 text-xs text-red-700 dark:text-red-400">{filenameError}</p>
  283. )}
  284. </div>
  285. <div className="flex justify-end gap-2 pt-2">
  286. <Button type="button" variant="secondary" onClick={onClose}>
  287. {t('common.cancel')}
  288. </Button>
  289. <Button type="submit" disabled={!name.trim() || name.trim() === baseName || !!filenameError || isLoading}>
  290. {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.rename')}
  291. </Button>
  292. </div>
  293. </form>
  294. </div>
  295. </div>
  296. );
  297. }
  298. // Move Files Modal
  299. interface MoveFilesModalProps {
  300. folders: LibraryFolderTree[];
  301. selectedFiles: number[];
  302. currentFolderId: number | null;
  303. onClose: () => void;
  304. onMove: (folderId: number | null) => void;
  305. isLoading: boolean;
  306. t: TFunction;
  307. }
  308. function MoveFilesModal({ folders, selectedFiles, currentFolderId, onClose, onMove, isLoading, t }: MoveFilesModalProps) {
  309. const [targetFolder, setTargetFolder] = useState<number | null>(null);
  310. const flattenFolders = (items: LibraryFolderTree[], depth = 0): { id: number | null; name: string; depth: number }[] => {
  311. const result: { id: number | null; name: string; depth: number }[] = [];
  312. for (const item of items) {
  313. result.push({ id: item.id, name: item.name, depth });
  314. if (item.children.length > 0) {
  315. result.push(...flattenFolders(item.children, depth + 1));
  316. }
  317. }
  318. return result;
  319. };
  320. const flatFolders = [{ id: null, name: t('fileManager.rootNoFolder'), depth: 0 }, ...flattenFolders(folders)];
  321. return (
  322. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  323. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
  324. <div className="p-4 border-b border-bambu-dark-tertiary">
  325. <h2 className="text-lg font-semibold text-white">{t('fileManager.moveFiles', { count: selectedFiles.length })}</h2>
  326. </div>
  327. <div className="p-4 space-y-4">
  328. <div className="max-h-64 overflow-y-auto space-y-1">
  329. {flatFolders.map((folder) => (
  330. <button
  331. key={folder.id ?? 'root'}
  332. onClick={() => setTargetFolder(folder.id)}
  333. disabled={folder.id === currentFolderId}
  334. className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
  335. targetFolder === folder.id
  336. ? 'bg-bambu-green/20 text-bambu-green'
  337. : folder.id === currentFolderId
  338. ? 'opacity-50 cursor-not-allowed text-bambu-gray'
  339. : 'hover:bg-bambu-dark text-white'
  340. }`}
  341. style={{ paddingLeft: `${12 + folder.depth * 16}px` }}
  342. >
  343. <FolderOpen className="w-4 h-4" />
  344. {folder.name}
  345. {folder.id === currentFolderId && <span className="text-xs text-bambu-gray ml-auto">({t('fileManager.current')})</span>}
  346. </button>
  347. ))}
  348. </div>
  349. <div className="flex justify-end gap-2 pt-2">
  350. <Button type="button" variant="secondary" onClick={onClose}>
  351. {t('common.cancel')}
  352. </Button>
  353. <Button onClick={() => onMove(targetFolder)} disabled={isLoading}>
  354. {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.move')}
  355. </Button>
  356. </div>
  357. </div>
  358. </div>
  359. </div>
  360. );
  361. }
  362. // Link Folder Modal
  363. interface LinkFolderModalProps {
  364. folder: LibraryFolderTree;
  365. onClose: () => void;
  366. onLink: (update: LibraryFolderUpdate) => void;
  367. isLoading: boolean;
  368. t: TFunction;
  369. }
  370. function LinkFolderModal({ folder, onClose, onLink, isLoading, t }: LinkFolderModalProps) {
  371. const [linkType, setLinkType] = useState<'project' | 'archive'>('project');
  372. const [selectedId, setSelectedId] = useState<number | null>(
  373. folder.project_id || folder.archive_id || null
  374. );
  375. // Initialize linkType based on existing link
  376. useState(() => {
  377. if (folder.archive_id) setLinkType('archive');
  378. });
  379. const { data: projects } = useQuery({
  380. queryKey: ['projects'],
  381. queryFn: () => api.getProjects(),
  382. select: (rows) => [...rows].sort((a, b) => a.name.localeCompare(b.name)),
  383. });
  384. const { data: archives } = useQuery({
  385. queryKey: ['archives-for-link'],
  386. queryFn: () => api.getArchives(undefined, undefined, 100),
  387. });
  388. const handleSave = () => {
  389. if (linkType === 'project') {
  390. onLink({
  391. project_id: selectedId,
  392. archive_id: 0, // Unlink archive
  393. });
  394. } else {
  395. onLink({
  396. project_id: 0, // Unlink project
  397. archive_id: selectedId,
  398. });
  399. }
  400. };
  401. const handleUnlink = () => {
  402. onLink({
  403. project_id: 0,
  404. archive_id: 0,
  405. });
  406. };
  407. const isLinked = folder.project_id || folder.archive_id;
  408. return (
  409. <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
  410. <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary">
  411. <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
  412. <h2 className="text-lg font-semibold text-white flex items-center gap-2">
  413. <Link2 className="w-5 h-5 text-bambu-green" />
  414. {t('fileManager.linkFolder')}
  415. </h2>
  416. <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
  417. <X className="w-5 h-5 text-bambu-gray" />
  418. </button>
  419. </div>
  420. <div className="p-4 space-y-4">
  421. <p className="text-sm text-bambu-gray">
  422. {t('fileManager.linkFolderDescription', { name: folder.name })}
  423. </p>
  424. {/* Link type selector */}
  425. <div className="flex gap-2">
  426. <button
  427. onClick={() => { setLinkType('project'); setSelectedId(null); }}
  428. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
  429. linkType === 'project'
  430. ? 'border-bambu-green bg-bambu-green/10 text-bambu-green'
  431. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  432. }`}
  433. >
  434. <Briefcase className="w-4 h-4" />
  435. {t('fileManager.project')}
  436. </button>
  437. <button
  438. onClick={() => { setLinkType('archive'); setSelectedId(null); }}
  439. className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
  440. linkType === 'archive'
  441. ? 'border-bambu-green bg-bambu-green/10 text-bambu-green'
  442. : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white'
  443. }`}
  444. >
  445. <ArchiveIcon className="w-4 h-4" />
  446. {t('fileManager.archive')}
  447. </button>
  448. </div>
  449. {/* Selection list */}
  450. <div className="max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2">
  451. {linkType === 'project' ? (
  452. projects && projects.length > 0 ? (
  453. projects.map((project) => (
  454. <button
  455. key={project.id}
  456. onClick={() => setSelectedId(project.id)}
  457. className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
  458. selectedId === project.id
  459. ? 'bg-bambu-green/20 text-bambu-green'
  460. : 'hover:bg-bambu-dark-tertiary text-white'
  461. }`}
  462. >
  463. <div
  464. className="w-3 h-3 rounded-full flex-shrink-0"
  465. style={{ backgroundColor: project.color || '#00ae42' }}
  466. />
  467. <span className="truncate">{project.name}</span>
  468. </button>
  469. ))
  470. ) : (
  471. <p className="text-sm text-bambu-gray text-center py-4">{t('fileManager.noProjectsFound')}</p>
  472. )
  473. ) : (
  474. archives && archives.length > 0 ? (
  475. archives.map((archive: Archive) => (
  476. <button
  477. key={archive.id}
  478. onClick={() => setSelectedId(archive.id)}
  479. className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
  480. selectedId === archive.id
  481. ? 'bg-bambu-green/20 text-bambu-green'
  482. : 'hover:bg-bambu-dark-tertiary text-white'
  483. }`}
  484. >
  485. <FileBox className="w-4 h-4 text-bambu-gray flex-shrink-0" />
  486. <span className="truncate">{archive.print_name || archive.filename}</span>
  487. </button>
  488. ))
  489. ) : (
  490. <p className="text-sm text-bambu-gray text-center py-4">{t('fileManager.noArchivesFound')}</p>
  491. )
  492. )}
  493. </div>
  494. </div>
  495. <div className="p-4 border-t border-bambu-dark-tertiary flex justify-between">
  496. {isLinked && (
  497. <Button variant="danger" onClick={handleUnlink} disabled={isLoading}>
  498. <Unlink className="w-4 h-4 mr-2" />
  499. {t('fileManager.unlink')}
  500. </Button>
  501. )}
  502. <div className={`flex gap-2 ${!isLinked ? 'ml-auto' : ''}`}>
  503. <Button variant="secondary" onClick={onClose}>
  504. {t('common.cancel')}
  505. </Button>
  506. <Button onClick={handleSave} disabled={!selectedId || isLoading}>
  507. {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('fileManager.link')}
  508. </Button>
  509. </div>
  510. </div>
  511. </div>
  512. </div>
  513. );
  514. }
  515. // Folder Tree Item
  516. interface FolderTreeItemProps {
  517. folder: LibraryFolderTree;
  518. selectedFolderId: number | null;
  519. onSelect: (id: number | null) => void;
  520. onDelete: (id: number) => void;
  521. onLink: (folder: LibraryFolderTree) => void;
  522. onRename: (folder: LibraryFolderTree) => void;
  523. depth?: number;
  524. wrapNames?: boolean;
  525. defaultExpanded?: boolean;
  526. hasPermission: (permission: Permission) => boolean;
  527. t: TFunction;
  528. }
  529. function FolderTreeItem({ folder, selectedFolderId, onSelect, onDelete, onLink, onRename, depth = 0, wrapNames = false, defaultExpanded = true, hasPermission, t }: FolderTreeItemProps) {
  530. const [expanded, setExpanded] = useState(defaultExpanded);
  531. const [showActions, setShowActions] = useState(false);
  532. const hasChildren = folder.children.length > 0;
  533. const isLinked = folder.project_id || folder.archive_id;
  534. const isExternal = folder.is_external;
  535. return (
  536. <div>
  537. <div
  538. className={`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${
  539. selectedFolderId === folder.id
  540. ? 'bg-bambu-green/20 text-bambu-green'
  541. : 'hover:bg-bambu-dark text-white'
  542. }`}
  543. style={{ paddingLeft: `${8 + depth * 12}px` }}
  544. onClick={() => onSelect(folder.id)}
  545. >
  546. {hasChildren ? (
  547. <button
  548. onClick={(e) => {
  549. e.stopPropagation();
  550. setExpanded(!expanded);
  551. }}
  552. className="p-0.5 hover:bg-bambu-dark-tertiary rounded"
  553. >
  554. <ChevronRight className={`w-3.5 h-3.5 transition-transform ${expanded ? 'rotate-90' : ''}`} />
  555. </button>
  556. ) : (
  557. <div className="w-4.5" />
  558. )}
  559. {isExternal ? (
  560. <FolderSymlink className="w-4 h-4 text-purple-600 dark:text-purple-400 flex-shrink-0" />
  561. ) : (
  562. <FolderOpen className="w-4 h-4 text-bambu-green flex-shrink-0" />
  563. )}
  564. <span className={`text-sm flex-1 min-w-0 ${wrapNames ? 'break-all' : 'truncate'}`} title={folder.name}>{folder.name}</span>
  565. {/* Link indicator - clickable to change link */}
  566. {isLinked && (
  567. <button
  568. onClick={(e) => { e.stopPropagation(); onLink(folder); }}
  569. className="flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400 hover:bg-blue-200 dark:hover:bg-blue-500/30 transition-colors"
  570. title={`${folder.project_name ? `Project: ${folder.project_name}` : `Archive: ${folder.archive_name}`} (click to change)`}
  571. >
  572. <Link2 className="w-3 h-3" />
  573. {folder.project_name ? (
  574. <Briefcase className="w-3 h-3" />
  575. ) : (
  576. <ArchiveIcon className="w-3 h-3" />
  577. )}
  578. </button>
  579. )}
  580. {/* Read-only indicator for external folders */}
  581. {isExternal && folder.external_readonly && (
  582. <span title={t('fileManager.readOnly')}>
  583. <Lock className="w-3 h-3 text-amber-600 dark:text-amber-400 flex-shrink-0" />
  584. </span>
  585. )}
  586. {folder.file_count > 0 && (
  587. <span className="flex-shrink-0 text-xs text-bambu-gray">{folder.file_count}</span>
  588. )}
  589. {/* Quick link button - always visible for unlinked folders */}
  590. {!isLinked && !isExternal && (
  591. <button
  592. onClick={(e) => { e.stopPropagation(); onLink(folder); }}
  593. className="flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary"
  594. title={t('fileManager.linkToProjectOrArchive')}
  595. >
  596. <Link2 className="w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green" />
  597. </button>
  598. )}
  599. <div className={`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${wrapNames ? '' : 'opacity-0 group-hover:opacity-100'}`} onClick={(e) => e.stopPropagation()}>
  600. <div className="relative">
  601. <button
  602. onClick={() => setShowActions(!showActions)}
  603. className="p-1 rounded hover:bg-bambu-dark-tertiary"
  604. >
  605. <MoreVertical className="w-3.5 h-3.5 text-bambu-gray" />
  606. </button>
  607. {showActions && (
  608. <>
  609. <div className="fixed inset-0 z-10" onClick={() => setShowActions(false)} />
  610. <div className="absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]">
  611. <button
  612. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  613. hasPermission('library:update_all') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  614. }`}
  615. onClick={() => { if (hasPermission('library:update_all')) { onRename(folder); setShowActions(false); } }}
  616. disabled={!hasPermission('library:update_all')}
  617. title={!hasPermission('library:update_all') ? t('fileManager.noPermissionRenameFolder') : undefined}
  618. >
  619. <Pencil className="w-3.5 h-3.5" />
  620. {t('common.rename')}
  621. </button>
  622. <button
  623. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  624. hasPermission('library:update_all') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  625. }`}
  626. onClick={() => { if (hasPermission('library:update_all')) { onLink(folder); setShowActions(false); } }}
  627. disabled={!hasPermission('library:update_all')}
  628. title={!hasPermission('library:update_all') ? t('fileManager.noPermissionLinkFolder') : undefined}
  629. >
  630. <Link2 className="w-3.5 h-3.5" />
  631. {isLinked ? t('fileManager.changeLink') : t('fileManager.linkTo')}
  632. </button>
  633. <button
  634. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  635. hasPermission('library:delete_all') ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  636. }`}
  637. onClick={() => { if (hasPermission('library:delete_all')) { onDelete(folder.id); setShowActions(false); } }}
  638. disabled={!hasPermission('library:delete_all')}
  639. title={!hasPermission('library:delete_all') ? t('fileManager.noPermissionDeleteFolder') : undefined}
  640. >
  641. <Trash2 className="w-3.5 h-3.5" />
  642. {t('common.delete')}
  643. </button>
  644. </div>
  645. </>
  646. )}
  647. </div>
  648. </div>
  649. </div>
  650. {hasChildren && expanded && (
  651. <div>
  652. {folder.children.map((child) => (
  653. <FolderTreeItem
  654. key={child.id}
  655. folder={child}
  656. selectedFolderId={selectedFolderId}
  657. onSelect={onSelect}
  658. onDelete={onDelete}
  659. onLink={onLink}
  660. onRename={onRename}
  661. depth={depth + 1}
  662. wrapNames={wrapNames}
  663. defaultExpanded={defaultExpanded}
  664. hasPermission={hasPermission}
  665. t={t}
  666. />
  667. ))}
  668. </div>
  669. )}
  670. </div>
  671. );
  672. }
  673. // Helper to check if a file is sliced (printable)
  674. function isSlicedFilename(filename: string): boolean {
  675. const lower = filename.toLowerCase();
  676. return lower.endsWith('.gcode') || lower.endsWith('.gcode.3mf');
  677. }
  678. // Files that can be fed to the slicer sidecar (model geometry inputs).
  679. // Excludes .gcode.* (already sliced) and any other non-model formats.
  680. function isSliceableFilename(filename: string): boolean {
  681. const lower = filename.toLowerCase();
  682. if (lower.endsWith('.gcode') || lower.endsWith('.gcode.3mf')) return false;
  683. return lower.endsWith('.stl') || lower.endsWith('.3mf') || lower.endsWith('.step') || lower.endsWith('.stp');
  684. }
  685. // File Card
  686. interface FileCardProps {
  687. file: LibraryFileListItem;
  688. isSelected: boolean;
  689. isMobile: boolean;
  690. onSelect: (id: number) => void;
  691. onDelete: (id: number) => void;
  692. onDownload: (id: number) => void;
  693. onPrint?: (file: LibraryFileListItem) => void;
  694. onSlice?: (file: LibraryFileListItem) => void;
  695. onRunPipeline?: (file: LibraryFileListItem) => void;
  696. useSlicerApi?: boolean;
  697. onPreview3d?: (file: LibraryFileListItem) => void;
  698. onRename?: (file: LibraryFileListItem) => void;
  699. onGenerateThumbnail?: (file: LibraryFileListItem) => void;
  700. onTagClick?: (tagId: number) => void;
  701. thumbnailVersion?: number;
  702. hasPermission: (permission: Permission) => boolean;
  703. canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
  704. authEnabled: boolean;
  705. showModified: boolean;
  706. t: TFunction;
  707. }
  708. function FileCard({ file, isSelected, isMobile, onSelect, onDelete, onDownload, onPrint, onSlice, onRunPipeline, useSlicerApi, onPreview3d, onRename, onGenerateThumbnail, onTagClick, thumbnailVersion, hasPermission, canModify, authEnabled, showModified, t }: FileCardProps) {
  709. const [showActions, setShowActions] = useState(false);
  710. return (
  711. <div
  712. className={`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${
  713. isSelected
  714. ? 'border-bambu-green ring-1 ring-bambu-green'
  715. : 'border-bambu-dark-tertiary hover:border-bambu-green/50'
  716. }`}
  717. onClick={() => onSelect(file.id)}
  718. >
  719. {/* Thumbnail */}
  720. <div className="aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden">
  721. {file.thumbnail_path ? (
  722. <img
  723. src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersion ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersion}`) : ''}`}
  724. alt={file.filename}
  725. className="w-full h-full object-cover"
  726. />
  727. ) : (
  728. <FileBox className="w-12 h-12 text-bambu-gray/30" />
  729. )}
  730. {/* File type badge */}
  731. <div className={`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${
  732. file.file_type === '3mf' ? 'bg-bambu-green/90 text-white'
  733. // Sliced output — share the gcode blue so users see at a glance
  734. // that the file is already sliced and ready to print (#1543).
  735. : file.file_type === 'gcode' || file.file_type === 'gcode.3mf' ? 'bg-blue-500/90 text-white'
  736. : file.file_type === 'stl' ? 'bg-purple-500/90 text-white'
  737. : 'bg-bambu-gray/90 text-white'
  738. }`}>
  739. {file.file_type.toUpperCase()}
  740. </div>
  741. </div>
  742. {/* Info */}
  743. <div className="p-3">
  744. <h3 className="text-sm font-medium text-white truncate" title={file.print_name || file.filename}>
  745. {file.print_name || file.filename}
  746. </h3>
  747. <div className="flex items-center gap-3 mt-1 text-xs text-bambu-gray">
  748. <span>{formatFileSize(file.file_size)}</span>
  749. {file.print_time_seconds && (
  750. <span className="flex items-center gap-1">
  751. <Clock className="w-3 h-3" />
  752. {formatDuration(file.print_time_seconds)}
  753. </span>
  754. )}
  755. </div>
  756. {file.sliced_for_model && (
  757. <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1">
  758. <Printer className="w-3 h-3" />
  759. {file.sliced_for_model}
  760. </div>
  761. )}
  762. {file.print_count > 0 && (
  763. <div className="mt-1 text-xs text-bambu-green">
  764. {t('fileManager.printedCount', { count: file.print_count })}
  765. </div>
  766. )}
  767. {authEnabled && file.created_by_username && (
  768. <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1">
  769. <User className="w-3 h-3" />
  770. {file.created_by_username}
  771. </div>
  772. )}
  773. {/* #2680: last-modified date, toggled from the toolbar. Uses the real
  774. on-disk mtime when known, else the DB created_at. */}
  775. {showModified && (
  776. <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1" title={t('fileManager.lastModified')}>
  777. <CalendarClock className="w-3 h-3" />
  778. {formatDate(file.fs_modified_at ?? file.created_at)}
  779. </div>
  780. )}
  781. {(file.tags?.length ?? 0) > 0 && (
  782. <div className="mt-2 flex flex-wrap gap-1" onClick={(e) => e.stopPropagation()}>
  783. {file.tags!.map((tg) => (
  784. <button
  785. key={tg.id}
  786. type="button"
  787. onClick={() => onTagClick?.(tg.id)}
  788. className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20 transition-colors max-w-full"
  789. title={tg.name}
  790. >
  791. <TagIcon className="w-2.5 h-2.5 flex-shrink-0" />
  792. <span className="truncate">{tg.name}</span>
  793. </button>
  794. ))}
  795. </div>
  796. )}
  797. </div>
  798. {/* Actions - always visible on mobile, hover on desktop */}
  799. <div className={`absolute bottom-2 right-2 transition-opacity ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`} onClick={(e) => e.stopPropagation()}>
  800. <button
  801. onClick={() => setShowActions(!showActions)}
  802. className="p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary"
  803. >
  804. <MoreVertical className="w-4 h-4 text-bambu-gray" />
  805. </button>
  806. {showActions && (
  807. <>
  808. <div className="fixed inset-0 z-10" onClick={() => setShowActions(false)} />
  809. <div className="absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]">
  810. {onPrint && isSlicedFilename(file.filename) && (
  811. <button
  812. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  813. hasPermission('queue:create') ? 'text-bambu-green hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  814. }`}
  815. onClick={() => { if (hasPermission('queue:create')) { onPrint(file); setShowActions(false); } }}
  816. disabled={!hasPermission('queue:create')}
  817. title={!hasPermission('queue:create') ? t('fileManager.noPermissionAddToQueue') : undefined}
  818. >
  819. <Printer className="w-3.5 h-3.5" />
  820. {t('common.print')}
  821. </button>
  822. )}
  823. {onSlice && useSlicerApi && isSliceableFilename(file.filename) && (
  824. <button
  825. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  826. hasPermission('library:upload') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  827. }`}
  828. onClick={() => { if (hasPermission('library:upload')) { onSlice(file); setShowActions(false); } }}
  829. disabled={!hasPermission('library:upload')}
  830. title={!hasPermission('library:upload') ? t('fileManager.noPermissionSlice') : undefined}
  831. >
  832. <Cog className="w-3.5 h-3.5" />
  833. {t('slice.action')}
  834. </button>
  835. )}
  836. {onRunPipeline && useSlicerApi && isSliceableFilename(file.filename) && (
  837. <button
  838. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  839. hasPermission('pipelines:run') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  840. }`}
  841. onClick={() => { if (hasPermission('pipelines:run')) { onRunPipeline(file); setShowActions(false); } }}
  842. disabled={!hasPermission('pipelines:run')}
  843. title={!hasPermission('pipelines:run') ? t('library.runWithPipeline.noPermission') : undefined}
  844. >
  845. <Play className="w-3.5 h-3.5" />
  846. {t('library.runWithPipeline.actionLabel')}
  847. </button>
  848. )}
  849. {onPreview3d && (file.file_type === '3mf' || file.file_type === 'gcode' || file.file_type === 'stl' || file.file_type === 'gcode.3mf') && (
  850. <button
  851. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  852. hasPermission('library:read') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  853. }`}
  854. onClick={() => { if (hasPermission('library:read')) { onPreview3d(file); setShowActions(false); } }}
  855. disabled={!hasPermission('library:read')}
  856. title={!hasPermission('library:read') ? 'You do not have permission to preview files' : undefined}
  857. >
  858. <Box className="w-3.5 h-3.5" />
  859. 3D Preview
  860. </button>
  861. )}
  862. <button
  863. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  864. hasPermission('library:read') ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  865. }`}
  866. onClick={() => { if (hasPermission('library:read')) { onDownload(file.id); setShowActions(false); } }}
  867. disabled={!hasPermission('library:read')}
  868. title={!hasPermission('library:read') ? t('fileManager.noPermissionDownload') : undefined}
  869. >
  870. <Download className="w-3.5 h-3.5" />
  871. {t('common.download')}
  872. </button>
  873. {onRename && (
  874. <button
  875. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  876. canModify('library', 'update', file.created_by_id) ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  877. }`}
  878. onClick={() => { if (canModify('library', 'update', file.created_by_id)) { onRename(file); setShowActions(false); } }}
  879. disabled={!canModify('library', 'update', file.created_by_id)}
  880. title={!canModify('library', 'update', file.created_by_id) ? t('fileManager.noPermissionRenameFile') : undefined}
  881. >
  882. <Pencil className="w-3.5 h-3.5" />
  883. {t('common.rename')}
  884. </button>
  885. )}
  886. {onGenerateThumbnail && file.file_type === 'stl' && (
  887. <button
  888. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  889. canModify('library', 'update', file.created_by_id) ? 'text-white hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  890. }`}
  891. onClick={() => { if (canModify('library', 'update', file.created_by_id)) { onGenerateThumbnail(file); setShowActions(false); } }}
  892. disabled={!canModify('library', 'update', file.created_by_id)}
  893. title={!canModify('library', 'update', file.created_by_id) ? t('fileManager.noPermissionGenerateThumbnail') : undefined}
  894. >
  895. <Image className="w-3.5 h-3.5" />
  896. {t('fileManager.generateThumbnail')}
  897. </button>
  898. )}
  899. <button
  900. className={`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${
  901. canModify('library', 'delete', file.created_by_id) ? 'text-red-700 dark:text-red-400 hover:bg-bambu-dark' : 'text-bambu-gray cursor-not-allowed'
  902. }`}
  903. onClick={() => { if (canModify('library', 'delete', file.created_by_id)) { onDelete(file.id); setShowActions(false); } }}
  904. disabled={!canModify('library', 'delete', file.created_by_id)}
  905. title={!canModify('library', 'delete', file.created_by_id) ? t('fileManager.noPermissionDeleteFile') : undefined}
  906. >
  907. <Trash2 className="w-3.5 h-3.5" />
  908. {t('common.delete')}
  909. </button>
  910. </div>
  911. </>
  912. )}
  913. </div>
  914. {/* Selection checkbox - always visible on mobile, hover on desktop */}
  915. <div className={`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${
  916. isSelected
  917. ? 'bg-bambu-green border-bambu-green'
  918. : `border-white/30 bg-black/30 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`
  919. }`}>
  920. {isSelected && <div className="w-2 h-2 bg-white rounded-sm" />}
  921. </div>
  922. </div>
  923. );
  924. }
  925. export function FileManagerPage() {
  926. const { t } = useTranslation();
  927. const queryClient = useQueryClient();
  928. const { showToast } = useToast();
  929. const { hasPermission, hasAnyPermission, canModify, authEnabled } = useAuth();
  930. const [searchParams] = useSearchParams();
  931. const navigate = useNavigate();
  932. // Read folder ID from URL query parameter
  933. const folderIdFromUrl = searchParams.get('folder');
  934. const initialFolderId = folderIdFromUrl ? parseInt(folderIdFromUrl, 10) : null;
  935. // State
  936. const [selectedFolderId, setSelectedFolderId] = useState<number | null>(initialFolderId);
  937. // Which top-level pseudo-view the sidebar shows when no specific folder is
  938. // selected: "internal" = files in Bambuddy's managed storage, "external" =
  939. // combined view across every linked external folder (#1621). Per-folder
  940. // selection bypasses this (selectedFolderId !== null disables the filter).
  941. const [topLevelView, setTopLevelView] = useState<'internal' | 'external'>('internal');
  942. const [selectedFiles, setSelectedFiles] = useState<number[]>([]);
  943. const [showNewFolderModal, setShowNewFolderModal] = useState(false);
  944. const [showExternalFolderModal, setShowExternalFolderModal] = useState(false);
  945. const [showMoveModal, setShowMoveModal] = useState(false);
  946. const [showUploadModal, setShowUploadModal] = useState(false);
  947. const [droppedFiles, setDroppedFiles] = useState<File[]>([]);
  948. const [showPurgeModal, setShowPurgeModal] = useState(false);
  949. // Tag UI state (#1268). selectedTagIds is the AND-style filter applied to
  950. // the listing; setting it bypasses folder scoping on the server so
  951. // "every toy" works regardless of which folder is currently selected.
  952. const [showTagsModal, setShowTagsModal] = useState(false);
  953. const [showBulkTagsModal, setShowBulkTagsModal] = useState(false);
  954. const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
  955. const [linkFolder, setLinkFolder] = useState<LibraryFolderTree | null>(null);
  956. const [deleteConfirm, setDeleteConfirm] = useState<{ type: 'file' | 'folder' | 'bulk'; id: number; count?: number } | null>(null);
  957. const [printFile, setPrintFile] = useState<LibraryFileListItem | null>(null);
  958. const [sliceFile, setSliceFile] = useState<LibraryFileListItem | null>(null);
  959. // Slicer Pipelines (#1425 PR B) — file gets "Run with pipeline" action.
  960. const [runPipelineFile, setRunPipelineFile] = useState<LibraryFileListItem | null>(null);
  961. const [renameItem, setRenameItem] = useState<{ type: 'file' | 'folder'; id: number; name: string } | null>(null);
  962. const [thumbnailVersions, setThumbnailVersions] = useState<Record<number, number>>({});
  963. const [viewerFile, setViewerFile] = useState<LibraryFileListItem | null>(null);
  964. const [viewMode, setViewMode] = useState<'grid' | 'list'>(() => {
  965. return (localStorage.getItem('library-view-mode') as 'grid' | 'list') || 'grid';
  966. });
  967. const [wrapFolderNames, setWrapFolderNames] = useState(() => {
  968. return localStorage.getItem('library-wrap-folders') === 'true';
  969. });
  970. const [collapseFoldersByDefault, setCollapseFoldersByDefault] = useState(() => {
  971. return localStorage.getItem('library-collapse-folders') === 'true';
  972. });
  973. // Folder tree sort (#1770). 'name' = alphabetical (the prior behaviour);
  974. // 'activity' = most recent file activity inside the folder first. Persisted
  975. // independently from the file-side sort so each can be tuned to taste.
  976. const [folderSortField, setFolderSortField] = useState<'name' | 'activity'>(() => {
  977. const saved = localStorage.getItem('library-folder-sort-field');
  978. return saved === 'activity' ? 'activity' : 'name';
  979. });
  980. const [folderSortDirection, setFolderSortDirection] = useState<'asc' | 'desc'>(() => {
  981. const saved = localStorage.getItem('library-folder-sort-direction');
  982. return saved === 'desc' ? 'desc' : 'asc';
  983. });
  984. // Resizable sidebar state
  985. const [sidebarWidth, setSidebarWidth] = useState(() => {
  986. const saved = localStorage.getItem('library-sidebar-width');
  987. return saved ? parseInt(saved, 10) : 256; // Default w-64 = 256px
  988. });
  989. const [isResizing, setIsResizing] = useState(false);
  990. const sidebarRef = useRef<HTMLDivElement>(null);
  991. // Handle sidebar resize
  992. useEffect(() => {
  993. if (!isResizing) return;
  994. // Prevent text selection during resize
  995. document.body.style.userSelect = 'none';
  996. document.body.style.cursor = 'col-resize';
  997. const handleMouseMove = (e: MouseEvent) => {
  998. if (!sidebarRef.current) return;
  999. const containerRect = sidebarRef.current.parentElement?.getBoundingClientRect();
  1000. if (!containerRect) return;
  1001. // Calculate new width based on mouse position relative to container
  1002. const newWidth = e.clientX - containerRect.left;
  1003. // Clamp between 200px and 500px
  1004. const clampedWidth = Math.min(500, Math.max(200, newWidth));
  1005. setSidebarWidth(clampedWidth);
  1006. };
  1007. const handleMouseUp = () => {
  1008. setIsResizing(false);
  1009. document.body.style.userSelect = '';
  1010. document.body.style.cursor = '';
  1011. // Save to localStorage
  1012. localStorage.setItem('library-sidebar-width', String(sidebarWidth));
  1013. };
  1014. document.addEventListener('mousemove', handleMouseMove);
  1015. document.addEventListener('mouseup', handleMouseUp);
  1016. return () => {
  1017. document.removeEventListener('mousemove', handleMouseMove);
  1018. document.removeEventListener('mouseup', handleMouseUp);
  1019. document.body.style.userSelect = '';
  1020. document.body.style.cursor = '';
  1021. };
  1022. }, [isResizing, sidebarWidth]);
  1023. // Filter and sort state (persist sort preferences to localStorage)
  1024. const [searchQuery, setSearchQuery] = useState('');
  1025. const [filterType, setFilterType] = useState<string>('all');
  1026. const [filterUsername, setFilterUsername] = useState('');
  1027. const [sortField, setSortField] = useState<SortField>(() => {
  1028. const saved = localStorage.getItem('library-sort-field');
  1029. return (saved as SortField) || 'name';
  1030. });
  1031. const [sortDirection, setSortDirection] = useState<SortDirection>(() => {
  1032. const saved = localStorage.getItem('library-sort-direction');
  1033. return (saved as SortDirection) || 'asc';
  1034. });
  1035. // Show/hide the last-modified date on each file card (#2680). Persisted.
  1036. const [showModified, setShowModified] = useState<boolean>(
  1037. () => localStorage.getItem('library-show-modified') === 'true'
  1038. );
  1039. // Mobile detection for touch-friendly UI
  1040. const isMobile = useIsMobile();
  1041. // Update selectedFolderId when URL parameter changes (e.g., navigating from Project or Archive page)
  1042. useEffect(() => {
  1043. const folderParam = searchParams.get('folder');
  1044. if (folderParam) {
  1045. const newFolderId = parseInt(folderParam, 10);
  1046. setSelectedFolderId(newFolderId);
  1047. }
  1048. }, [searchParams]);
  1049. // Queries
  1050. const { data: settings } = useQuery({
  1051. queryKey: ['settings'],
  1052. queryFn: () => api.getSettings() as Promise<AppSettings>,
  1053. });
  1054. const { data: folders, isLoading: foldersLoading } = useQuery({
  1055. queryKey: ['library-folders'],
  1056. queryFn: () => api.getLibraryFolders(),
  1057. });
  1058. // Recursive folder tree sort (#1770). Applies the same comparator to the
  1059. // top-level list AND to each level of `children`, so sort order is uniform
  1060. // at every depth of nesting. When sorting by activity, the comparator falls
  1061. // back to a created-at fallback for folders with no files (`latest_activity_at`
  1062. // is null) so they stay grouped at the end / start of the bucket instead of
  1063. // randomly interspersed.
  1064. const sortedFolders = useMemo(() => {
  1065. if (!folders) return folders;
  1066. const sortLevel = (items: LibraryFolderTree[]): LibraryFolderTree[] => {
  1067. const sorted = [...items].sort((a, b) => {
  1068. let comparison = 0;
  1069. if (folderSortField === 'name') {
  1070. comparison = a.name.localeCompare(b.name);
  1071. } else {
  1072. // activity: newest first on 'desc', oldest first on 'asc'.
  1073. // Folders with no activity timestamp sort to the end regardless
  1074. // of direction so an empty folder doesn't elbow a recently-used one.
  1075. const aTs = a.latest_activity_at ? new Date(a.latest_activity_at).getTime() : null;
  1076. const bTs = b.latest_activity_at ? new Date(b.latest_activity_at).getTime() : null;
  1077. if (aTs === null && bTs === null) {
  1078. comparison = a.name.localeCompare(b.name);
  1079. } else if (aTs === null) {
  1080. return 1;
  1081. } else if (bTs === null) {
  1082. return -1;
  1083. } else {
  1084. comparison = aTs - bTs;
  1085. }
  1086. }
  1087. return folderSortDirection === 'asc' ? comparison : -comparison;
  1088. });
  1089. return sorted.map((f) => ({ ...f, children: sortLevel(f.children) }));
  1090. };
  1091. return sortLevel(folders);
  1092. }, [folders, folderSortField, folderSortDirection]);
  1093. // Trash count for the header badge (#1008). Empty/error are silently treated
  1094. // as zero so a broken trash endpoint doesn't break the File Manager.
  1095. const { data: trashCount } = useQuery({
  1096. queryKey: ['library-trash-count'],
  1097. queryFn: async () => {
  1098. try {
  1099. const res = await api.listLibraryTrash(1, 0);
  1100. return res.total;
  1101. } catch {
  1102. return 0;
  1103. }
  1104. },
  1105. staleTime: 30_000,
  1106. });
  1107. // #1268: when a folder is selected and the user has typed a search query,
  1108. // ask the server to expand the result to every descendant folder so the
  1109. // client-side filter can match files in subfolders too. Without this the
  1110. // listing is just the immediate children and "robot.3mf" two levels deep
  1111. // is invisible from the parent. Only kicks in for folder-scoped views —
  1112. // root and the internal/external pseudo-nodes already return the union.
  1113. const searchExpandsSubfolders = selectedFolderId !== null && searchQuery.trim().length > 0;
  1114. // The tag filter overrides folder scoping server-side (#1268 design call),
  1115. // so the FE query key includes it as a peer of folder/topLevelView. Sorted
  1116. // so the cache hits regardless of the order tags were toggled.
  1117. const tagFilterKey = useMemo(() => [...selectedTagIds].sort((a, b) => a - b), [selectedTagIds]);
  1118. // Tag catalog — needed to resolve names for the active-filter chip bar.
  1119. // Cheap query, shared with LibraryTagsModal / BulkTagsPickerModal via the
  1120. // same queryKey so they all invalidate together on tag CRUD.
  1121. const { data: tagCatalog = [] } = useQuery({
  1122. queryKey: ['library-tags'],
  1123. queryFn: api.getLibraryTags,
  1124. });
  1125. const tagsById = useMemo(() => {
  1126. const map = new Map<number, string>();
  1127. for (const t of tagCatalog) map.set(t.id, t.name);
  1128. return map;
  1129. }, [tagCatalog]);
  1130. // Prune the active filter when a tag is removed from the catalog so the
  1131. // listing never stalls on a phantom id. Skipped while the catalog query is
  1132. // still settling (empty array on first paint) — otherwise the user's filter
  1133. // gets cleared the moment the page mounts.
  1134. useEffect(() => {
  1135. if (tagCatalog.length === 0) return;
  1136. setSelectedTagIds((prev) => {
  1137. const next = prev.filter((id) => tagsById.has(id));
  1138. return next.length === prev.length ? prev : next;
  1139. });
  1140. }, [tagCatalog.length, tagsById]);
  1141. const toggleTagFilter = useCallback((tagId: number) => {
  1142. setSelectedTagIds((prev) =>
  1143. prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId],
  1144. );
  1145. }, []);
  1146. const { data: files, isLoading: filesLoading } = useQuery({
  1147. queryKey: ['library-files', selectedFolderId, topLevelView, searchExpandsSubfolders, tagFilterKey],
  1148. // When a specific folder is selected we list its contents directly; when
  1149. // no folder is selected the topLevelView pseudo-node decides whether the
  1150. // server scopes the result to internal-managed-storage files or to the
  1151. // union of every external folder (#1621). include_root stays false so the
  1152. // listing still descends into subfolders (regression guard from #1499).
  1153. queryFn: () =>
  1154. api.getLibraryFiles(
  1155. selectedFolderId,
  1156. false,
  1157. undefined,
  1158. selectedFolderId === null ? topLevelView : undefined,
  1159. searchExpandsSubfolders,
  1160. tagFilterKey,
  1161. ),
  1162. });
  1163. const { data: stats } = useQuery({
  1164. queryKey: ['library-stats'],
  1165. queryFn: () => api.getLibraryStats(),
  1166. });
  1167. // Get users for the username filter autocomplete
  1168. const { data: users } = useQuery({
  1169. queryKey: ['users'],
  1170. queryFn: () => api.getUsers(),
  1171. });
  1172. // Get unique file types for filter dropdown
  1173. const fileTypes = useMemo(() => {
  1174. if (!files) return [];
  1175. const types = new Set(files.map((f) => f.file_type));
  1176. return Array.from(types).sort();
  1177. }, [files]);
  1178. // Filter and sort files
  1179. const filteredAndSortedFiles = useMemo(() => {
  1180. if (!files) return [];
  1181. let result = [...files];
  1182. // Apply search filter
  1183. if (searchQuery.trim()) {
  1184. const query = searchQuery.toLowerCase();
  1185. result = result.filter(
  1186. (f) =>
  1187. f.filename.toLowerCase().includes(query) ||
  1188. (f.print_name && f.print_name.toLowerCase().includes(query))
  1189. );
  1190. }
  1191. // Apply type filter
  1192. if (filterType !== 'all') {
  1193. result = result.filter((f) => f.file_type === filterType);
  1194. }
  1195. // Apply username filter
  1196. if (filterUsername.trim()) {
  1197. const query = filterUsername.toLowerCase();
  1198. result = result.filter(
  1199. (f) => f.created_by_username && f.created_by_username.toLowerCase().includes(query)
  1200. );
  1201. }
  1202. // Apply sorting
  1203. result.sort((a, b) => {
  1204. let comparison = 0;
  1205. switch (sortField) {
  1206. case 'name':
  1207. comparison = (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
  1208. break;
  1209. case 'date':
  1210. // #2680: sort by real on-disk mtime (matches `ls -t`), falling back to
  1211. // the DB created_at for managed uploads that have no filesystem mtime.
  1212. comparison =
  1213. (parseUTCDate(a.fs_modified_at ?? a.created_at)?.getTime() ?? 0) -
  1214. (parseUTCDate(b.fs_modified_at ?? b.created_at)?.getTime() ?? 0);
  1215. break;
  1216. case 'size':
  1217. comparison = a.file_size - b.file_size;
  1218. break;
  1219. case 'type':
  1220. comparison = a.file_type.localeCompare(b.file_type);
  1221. break;
  1222. case 'prints':
  1223. comparison = a.print_count - b.print_count;
  1224. break;
  1225. }
  1226. return sortDirection === 'asc' ? comparison : -comparison;
  1227. });
  1228. return result;
  1229. }, [files, searchQuery, filterType, filterUsername, sortField, sortDirection]);
  1230. // Check if disk space is low
  1231. const isDiskSpaceLow = useMemo(() => {
  1232. if (!stats || !settings) return false;
  1233. const thresholdBytes = (settings.library_disk_warning_gb || 5) * 1024 * 1024 * 1024;
  1234. return stats.disk_free_bytes < thresholdBytes;
  1235. }, [stats, settings]);
  1236. // Mutations
  1237. const createFolderMutation = useMutation({
  1238. mutationFn: (data: LibraryFolderCreate) => api.createLibraryFolder(data),
  1239. onSuccess: () => {
  1240. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1241. setShowNewFolderModal(false);
  1242. showToast(t('fileManager.toast.folderCreated'), 'success');
  1243. },
  1244. onError: (error: Error) => showToast(error.message, 'error'),
  1245. });
  1246. const createExternalFolderMutation = useMutation({
  1247. mutationFn: async (data: ExternalFolderCreate) => {
  1248. const folder = await api.createExternalFolder(data);
  1249. // Auto-scan after creation
  1250. await api.scanExternalFolder(folder.id);
  1251. return folder;
  1252. },
  1253. onSuccess: (folder) => {
  1254. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1255. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1256. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1257. setShowExternalFolderModal(false);
  1258. setSelectedFolderId(folder.id);
  1259. showToast(t('fileManager.toast.externalFolderLinked'), 'success');
  1260. },
  1261. onError: (error: Error) => showToast(error.message, 'error'),
  1262. });
  1263. const scanExternalFolderMutation = useMutation({
  1264. mutationFn: (folderId: number) => api.scanExternalFolder(folderId),
  1265. onSuccess: (result) => {
  1266. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1267. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1268. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1269. showToast(t('fileManager.toast.folderScanned', { added: result.added, removed: result.removed }), 'success');
  1270. },
  1271. onError: (error: Error) => showToast(error.message, 'error'),
  1272. });
  1273. const deleteFolderMutation = useMutation({
  1274. mutationFn: (id: number) => api.deleteLibraryFolder(id),
  1275. onSuccess: () => {
  1276. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1277. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1278. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1279. if (selectedFolderId === deleteConfirm?.id) {
  1280. setSelectedFolderId(null);
  1281. }
  1282. setDeleteConfirm(null);
  1283. showToast(t('fileManager.toast.folderDeleted'), 'success');
  1284. },
  1285. onError: (error: Error) => {
  1286. setDeleteConfirm(null);
  1287. showToast(error.message, 'error');
  1288. },
  1289. });
  1290. const deleteFileMutation = useMutation({
  1291. mutationFn: (id: number) => api.deleteLibraryFile(id),
  1292. onSuccess: () => {
  1293. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1294. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1295. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1296. queryClient.invalidateQueries({ queryKey: ['library-trash-count'] });
  1297. setSelectedFiles((prev) => prev.filter((id) => id !== deleteConfirm?.id));
  1298. setDeleteConfirm(null);
  1299. showToast(t('fileManager.toast.fileDeleted'), 'success');
  1300. },
  1301. onError: (error: Error) => {
  1302. setDeleteConfirm(null);
  1303. showToast(error.message, 'error');
  1304. },
  1305. });
  1306. const bulkDeleteMutation = useMutation({
  1307. mutationFn: (fileIds: number[]) => api.bulkDeleteLibrary(fileIds, []),
  1308. onSuccess: (_, fileIds) => {
  1309. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1310. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1311. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1312. queryClient.invalidateQueries({ queryKey: ['library-trash-count'] });
  1313. showToast(t('fileManager.toast.filesDeleted', { count: fileIds.length }), 'success');
  1314. setSelectedFiles([]);
  1315. setDeleteConfirm(null);
  1316. },
  1317. onError: (error: Error) => {
  1318. setDeleteConfirm(null);
  1319. showToast(error.message, 'error');
  1320. },
  1321. });
  1322. const moveFilesMutation = useMutation({
  1323. mutationFn: ({ fileIds, folderId }: { fileIds: number[]; folderId: number | null }) =>
  1324. api.moveLibraryFiles(fileIds, folderId),
  1325. onSuccess: () => {
  1326. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1327. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1328. setSelectedFiles([]);
  1329. setShowMoveModal(false);
  1330. showToast(t('fileManager.toast.filesMoved'), 'success');
  1331. },
  1332. onError: (error: Error) => showToast(error.message, 'error'),
  1333. });
  1334. const updateFolderMutation = useMutation({
  1335. mutationFn: ({ id, data }: { id: number; data: LibraryFolderUpdate }) =>
  1336. api.updateLibraryFolder(id, data),
  1337. onSuccess: (_, variables) => {
  1338. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1339. // Invalidate project/archive folder queries so other pages see the update
  1340. queryClient.invalidateQueries({ queryKey: ['project-folders'] });
  1341. queryClient.invalidateQueries({ queryKey: ['archive-folders'] });
  1342. setLinkFolder(null);
  1343. const isUnlink = variables.data.project_id === 0 && variables.data.archive_id === 0;
  1344. showToast(isUnlink ? t('fileManager.toast.folderUnlinked') : t('fileManager.toast.folderLinked'), 'success');
  1345. },
  1346. onError: (error: Error) => showToast(error.message, 'error'),
  1347. });
  1348. const renameFileMutation = useMutation({
  1349. mutationFn: ({ id, filename }: { id: number; filename: string }) =>
  1350. api.updateLibraryFile(id, { filename }),
  1351. onSuccess: () => {
  1352. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1353. setRenameItem(null);
  1354. showToast(t('fileManager.toast.fileRenamed'), 'success');
  1355. },
  1356. onError: (error: Error) => {
  1357. setRenameItem(null);
  1358. showToast(error.message, 'error');
  1359. },
  1360. });
  1361. const renameFolderMutation = useMutation({
  1362. mutationFn: ({ id, name }: { id: number; name: string }) =>
  1363. api.updateLibraryFolder(id, { name }),
  1364. onSuccess: () => {
  1365. // Invalidate both folders and files - files may display folder info
  1366. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1367. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1368. setRenameItem(null);
  1369. showToast(t('fileManager.toast.folderRenamed'), 'success');
  1370. },
  1371. onError: (error: Error) => {
  1372. setRenameItem(null);
  1373. showToast(error.message, 'error');
  1374. },
  1375. });
  1376. const batchThumbnailMutation = useMutation({
  1377. mutationFn: () => api.batchGenerateStlThumbnails({ all_missing: true }),
  1378. onSuccess: (result) => {
  1379. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1380. // Update thumbnail versions for cache busting
  1381. if (result.succeeded > 0) {
  1382. const now = Date.now();
  1383. const newVersions: Record<number, number> = {};
  1384. result.results.forEach((r) => {
  1385. if (r.success) {
  1386. newVersions[r.file_id] = now;
  1387. }
  1388. });
  1389. setThumbnailVersions((prev) => ({ ...prev, ...newVersions }));
  1390. }
  1391. if (result.succeeded > 0 && result.failed === 0) {
  1392. showToast(t('fileManager.toast.thumbnailsGenerated', { count: result.succeeded }), 'success');
  1393. } else if (result.succeeded > 0 && result.failed > 0) {
  1394. showToast(t('fileManager.toast.thumbnailsGeneratedPartial', { succeeded: result.succeeded, failed: result.failed }), 'success');
  1395. } else if (result.processed === 0) {
  1396. showToast(t('fileManager.toast.noStlMissingThumbnails'), 'info');
  1397. } else {
  1398. showToast(t('fileManager.toast.failedToGenerateThumbnails', { error: result.results[0]?.error || 'Unknown error' }), 'error');
  1399. }
  1400. },
  1401. onError: (error: Error) => showToast(error.message, 'error'),
  1402. });
  1403. const singleThumbnailMutation = useMutation({
  1404. mutationFn: (fileId: number) => api.batchGenerateStlThumbnails({ file_ids: [fileId] }),
  1405. onSuccess: (result) => {
  1406. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1407. // Update thumbnail version for cache busting
  1408. if (result.succeeded > 0) {
  1409. const fileId = result.results[0]?.file_id;
  1410. if (fileId) {
  1411. setThumbnailVersions((prev) => ({ ...prev, [fileId]: Date.now() }));
  1412. }
  1413. showToast(t('fileManager.toast.thumbnailGenerated'), 'success');
  1414. } else {
  1415. showToast(t('fileManager.toast.failedToGenerateThumbnail', { error: result.results[0]?.error || 'Unknown error' }), 'error');
  1416. }
  1417. },
  1418. onError: (error: Error) => showToast(error.message, 'error'),
  1419. });
  1420. // Helper to check if a file is sliced (printable)
  1421. const isSlicedFile = useCallback((filename: string) => {
  1422. const lower = filename.toLowerCase();
  1423. return lower.endsWith('.gcode') || lower.includes('.gcode.');
  1424. }, []);
  1425. // Get sliced files from selection
  1426. const selectedSlicedFiles = useMemo(() => {
  1427. if (!files) return [];
  1428. return files.filter(f => selectedFiles.includes(f.id) && isSlicedFile(f.filename));
  1429. }, [files, selectedFiles, isSlicedFile]);
  1430. // Handlers
  1431. const handleFileSelect = useCallback((id: number) => {
  1432. // Always toggle selection (multi-select by default)
  1433. setSelectedFiles((prev) => {
  1434. return prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id];
  1435. });
  1436. }, []);
  1437. const handleSelectAll = useCallback(() => {
  1438. if (filteredAndSortedFiles.length > 0) {
  1439. setSelectedFiles(filteredAndSortedFiles.map((f) => f.id));
  1440. }
  1441. }, [filteredAndSortedFiles]);
  1442. const handleDeselectAll = useCallback(() => {
  1443. setSelectedFiles([]);
  1444. }, []);
  1445. const handleUploadComplete = () => {
  1446. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  1447. queryClient.invalidateQueries({ queryKey: ['library-folders'] });
  1448. queryClient.invalidateQueries({ queryKey: ['library-stats'] });
  1449. };
  1450. // Page-wide drag-and-drop upload (#1510). Disabled when the user lacks
  1451. // library:upload so a non-uploader can't accidentally show the overlay,
  1452. // and also disabled while the upload modal itself is open so drags into
  1453. // the modal's own drop zone don't bubble up and flash the page overlay
  1454. // behind it.
  1455. const canUpload = hasPermission('library:upload');
  1456. const { isDraggingOver, dragHandlers } = usePageFileDrop({
  1457. disabled: !canUpload || showUploadModal,
  1458. onFiles: (files) => {
  1459. setDroppedFiles(files);
  1460. setShowUploadModal(true);
  1461. },
  1462. });
  1463. const handleDownload = (id: number) => {
  1464. api.downloadLibraryFile(id).catch((err) => {
  1465. console.error('Library file download failed:', err);
  1466. });
  1467. };
  1468. const handleDeleteConfirm = () => {
  1469. if (!deleteConfirm) return;
  1470. if (deleteConfirm.type === 'file') {
  1471. deleteFileMutation.mutate(deleteConfirm.id);
  1472. } else if (deleteConfirm.type === 'folder') {
  1473. deleteFolderMutation.mutate(deleteConfirm.id);
  1474. } else if (deleteConfirm.type === 'bulk') {
  1475. bulkDeleteMutation.mutate(selectedFiles);
  1476. }
  1477. };
  1478. const isDeleting = deleteFolderMutation.isPending || deleteFileMutation.isPending || bulkDeleteMutation.isPending;
  1479. const handleViewModeChange = (mode: 'grid' | 'list') => {
  1480. setViewMode(mode);
  1481. localStorage.setItem('library-view-mode', mode);
  1482. };
  1483. const isLoading = foldersLoading || filesLoading;
  1484. // Find the selected folder in the tree to check external status
  1485. const selectedFolder = useMemo(() => {
  1486. if (!selectedFolderId || !folders) return null;
  1487. const findFolder = (items: LibraryFolderTree[]): LibraryFolderTree | null => {
  1488. for (const item of items) {
  1489. if (item.id === selectedFolderId) return item;
  1490. const found = findFolder(item.children);
  1491. if (found) return found;
  1492. }
  1493. return null;
  1494. };
  1495. return findFolder(folders);
  1496. }, [selectedFolderId, folders]);
  1497. return (
  1498. <div
  1499. className="p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col relative"
  1500. {...dragHandlers}
  1501. >
  1502. {/* Drag & Drop Overlay — page-wide file upload (#1510) */}
  1503. {isDraggingOver && (
  1504. <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
  1505. <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
  1506. <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
  1507. <p className="text-2xl font-semibold text-white mb-2">{t('fileManager.dropFilesHere')}</p>
  1508. <p className="text-bambu-gray">{t('fileManager.releaseToUpload')}</p>
  1509. </div>
  1510. </div>
  1511. )}
  1512. {/* Header */}
  1513. <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
  1514. <div>
  1515. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1516. <FolderOpen className="w-7 h-7 text-bambu-green" />
  1517. {t('fileManager.title')}
  1518. </h1>
  1519. <p className="text-bambu-gray mt-1">
  1520. {t('fileManager.subtitle')}
  1521. </p>
  1522. </div>
  1523. <div className="flex items-center gap-2">
  1524. {/* View mode toggle */}
  1525. <div className="flex items-center bg-bambu-dark rounded-lg p-1">
  1526. <button
  1527. onClick={() => handleViewModeChange('grid')}
  1528. className={`p-1.5 rounded transition-colors ${
  1529. viewMode === 'grid' ? 'bg-bambu-dark-secondary text-white' : 'text-bambu-gray hover:text-white'
  1530. }`}
  1531. title={t('fileManager.gridView')}
  1532. >
  1533. <LayoutGrid className="w-4 h-4" />
  1534. </button>
  1535. <button
  1536. onClick={() => handleViewModeChange('list')}
  1537. className={`p-1.5 rounded transition-colors ${
  1538. viewMode === 'list' ? 'bg-bambu-dark-secondary text-white' : 'text-bambu-gray hover:text-white'
  1539. }`}
  1540. title={t('fileManager.listView')}
  1541. >
  1542. <List className="w-4 h-4" />
  1543. </button>
  1544. </div>
  1545. <Button
  1546. variant="secondary"
  1547. onClick={() => batchThumbnailMutation.mutate()}
  1548. disabled={batchThumbnailMutation.isPending || !hasAnyPermission('library:update_own', 'library:update_all')}
  1549. title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.noPermissionGenerateThumbnail') : t('fileManager.generateThumbnailsForMissing')}
  1550. >
  1551. {batchThumbnailMutation.isPending ? (
  1552. <Loader2 className="w-4 h-4 mr-2 animate-spin" />
  1553. ) : (
  1554. <Image className="w-4 h-4 mr-2" />
  1555. )}
  1556. {t('fileManager.generateThumbnails')}
  1557. </Button>
  1558. <Button
  1559. variant="secondary"
  1560. onClick={() => setShowExternalFolderModal(true)}
  1561. disabled={!hasPermission('library:upload')}
  1562. title={!hasPermission('library:upload') ? t('fileManager.noPermissionCreateFolder') : t('fileManager.linkExternalFolder')}
  1563. >
  1564. <FolderSymlink className="w-4 h-4 mr-2" />
  1565. {t('fileManager.linkExternal')}
  1566. </Button>
  1567. <Button
  1568. variant="secondary"
  1569. onClick={() => setShowNewFolderModal(true)}
  1570. disabled={!hasPermission('library:upload')}
  1571. title={!hasPermission('library:upload') ? t('fileManager.noPermissionCreateFolder') : undefined}
  1572. >
  1573. <FolderPlus className="w-4 h-4 mr-2" />
  1574. {t('fileManager.newFolder')}
  1575. </Button>
  1576. <Button
  1577. variant="secondary"
  1578. onClick={() => setShowTagsModal(true)}
  1579. title={t('fileManager.tags.manageTitle')}
  1580. >
  1581. <TagIcon className="w-4 h-4 mr-2" />
  1582. {t('fileManager.tags.manage')}
  1583. </Button>
  1584. {hasPermission('library:purge') && (
  1585. <Button
  1586. variant="secondary"
  1587. onClick={() => setShowPurgeModal(true)}
  1588. title={t('libraryPurge.headerTooltip')}
  1589. >
  1590. <Trash2 className="w-4 h-4 mr-2" />
  1591. {t('libraryPurge.headerButton')}
  1592. </Button>
  1593. )}
  1594. {(hasAnyPermission('library:delete_own', 'library:delete_all')) && (
  1595. <Link
  1596. to="/files/trash"
  1597. className="inline-flex items-center px-3 py-1.5 text-sm rounded bg-bambu-dark-secondary text-bambu-gray hover:text-white hover:bg-bambu-dark transition-colors"
  1598. title={t('libraryTrash.headerTooltip')}
  1599. >
  1600. <Trash2 className="w-4 h-4 mr-2" />
  1601. {t('libraryTrash.headerButton')}
  1602. {typeof trashCount === 'number' && trashCount > 0 && (
  1603. <span className="ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green">
  1604. {trashCount}
  1605. </span>
  1606. )}
  1607. </Link>
  1608. )}
  1609. <Button
  1610. onClick={() => setShowUploadModal(true)}
  1611. disabled={!hasPermission('library:upload')}
  1612. title={!hasPermission('library:upload') ? t('fileManager.noPermissionUpload') : undefined}
  1613. >
  1614. <Upload className="w-4 h-4 mr-2" />
  1615. {t('common.upload')}
  1616. </Button>
  1617. </div>
  1618. </div>
  1619. {/* Disk space warning */}
  1620. {isDiskSpaceLow && stats && settings && (
  1621. <div className="flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg">
  1622. <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0" />
  1623. <div className="flex-1">
  1624. <p className="text-sm text-amber-500 font-medium">{t('fileManager.lowDiskSpaceWarning')}</p>
  1625. <p className="text-xs text-amber-500/80">
  1626. {t('fileManager.lowDiskSpaceDetails', { free: formatFileSize(stats.disk_free_bytes), total: formatFileSize(stats.disk_total_bytes), threshold: settings.library_disk_warning_gb })}
  1627. </p>
  1628. </div>
  1629. </div>
  1630. )}
  1631. {/* Stats bar */}
  1632. {stats && (
  1633. <div className="flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary">
  1634. <div className="flex items-center gap-2 text-sm">
  1635. <File className="w-4 h-4 text-bambu-green" />
  1636. <span className="text-bambu-gray">{t('fileManager.files')}:</span>
  1637. <span className="text-white font-medium">{stats.total_files}</span>
  1638. </div>
  1639. <div className="flex items-center gap-2 text-sm">
  1640. <FolderOpen className="w-4 h-4 text-blue-600 dark:text-blue-400" />
  1641. <span className="text-bambu-gray">{t('fileManager.folders')}:</span>
  1642. <span className="text-white font-medium">{stats.total_folders}</span>
  1643. </div>
  1644. <div className="flex items-center gap-2 text-sm">
  1645. <HardDrive className="w-4 h-4 text-amber-600 dark:text-amber-400" />
  1646. <span className="text-bambu-gray">{t('fileManager.size')}:</span>
  1647. <span className="text-white font-medium">{formatFileSize(stats.total_size_bytes)}</span>
  1648. </div>
  1649. <div className="flex items-center gap-2 text-sm sm:ml-auto">
  1650. <span className="text-bambu-gray">{t('fileManager.free')}:</span>
  1651. <span className={`font-medium ${isDiskSpaceLow ? 'text-amber-500' : 'text-white'}`}>
  1652. {formatFileSize(stats.disk_free_bytes)}
  1653. </span>
  1654. </div>
  1655. </div>
  1656. )}
  1657. {/* Main content */}
  1658. <div className="flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0">
  1659. {/* Mobile folder selector */}
  1660. <div className="lg:hidden">
  1661. <select
  1662. value={selectedFolderId !== null ? String(selectedFolderId) : `__top:${topLevelView}`}
  1663. onChange={(e) => {
  1664. const v = e.target.value;
  1665. if (v.startsWith('__top:')) {
  1666. setSelectedFolderId(null);
  1667. setTopLevelView(v.slice('__top:'.length) as 'internal' | 'external');
  1668. } else {
  1669. setSelectedFolderId(parseInt(v, 10));
  1670. }
  1671. }}
  1672. className="w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green"
  1673. >
  1674. <option value="__top:internal">📁 {t('fileManager.allFiles')}</option>
  1675. {folders?.some((f) => f.is_external) && (
  1676. <option value="__top:external">🔗 {t('fileManager.allExternal')}</option>
  1677. )}
  1678. {sortedFolders && (() => {
  1679. // Flatten folder tree for mobile selector
  1680. const flattenFolders = (items: LibraryFolderTree[], depth = 0): { id: number; name: string; fileCount: number; depth: number }[] => {
  1681. const result: { id: number; name: string; fileCount: number; depth: number }[] = [];
  1682. for (const item of items) {
  1683. result.push({ id: item.id, name: item.name, fileCount: item.file_count, depth });
  1684. if (item.children.length > 0) {
  1685. result.push(...flattenFolders(item.children, depth + 1));
  1686. }
  1687. }
  1688. return result;
  1689. };
  1690. return flattenFolders(sortedFolders).map((folder) => (
  1691. <option key={folder.id} value={folder.id}>
  1692. {'│ '.repeat(folder.depth)}📂 {folder.name} {folder.fileCount > 0 ? `(${folder.fileCount})` : ''}
  1693. </option>
  1694. ));
  1695. })()}
  1696. </select>
  1697. </div>
  1698. {/* Folder sidebar - resizable, hidden on mobile */}
  1699. <div
  1700. ref={sidebarRef}
  1701. className="hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative"
  1702. style={{ width: `${sidebarWidth}px` }}
  1703. >
  1704. {/* Resize handle - drag to resize, double-click to reset */}
  1705. <div
  1706. className={`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${
  1707. isResizing ? 'bg-bambu-green' : 'hover:bg-bambu-green/50'
  1708. }`}
  1709. onMouseDown={(e) => {
  1710. e.preventDefault();
  1711. setIsResizing(true);
  1712. }}
  1713. onDoubleClick={() => {
  1714. setSidebarWidth(256); // Reset to default w-64
  1715. localStorage.setItem('library-sidebar-width', '256');
  1716. }}
  1717. title={t('fileManager.dragToResizeTooltip')}
  1718. >
  1719. {/* Grip dots */}
  1720. <div className={`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${isResizing ? 'opacity-100' : ''}`}>
  1721. <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
  1722. <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
  1723. <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
  1724. </div>
  1725. </div>
  1726. <div className="p-3 border-b border-bambu-dark-tertiary flex items-center justify-between">
  1727. <h2 className="text-sm font-medium text-white">{t('fileManager.folders')}</h2>
  1728. <div className="flex items-center gap-1">
  1729. {/* Folder tree sort (#1770). Dropdown drives the comparator;
  1730. direction button flips asc/desc. Both persist to localStorage
  1731. on change so the choice survives reloads. */}
  1732. <select
  1733. value={folderSortField}
  1734. onChange={(e) => {
  1735. const v = e.target.value === 'activity' ? 'activity' : 'name';
  1736. setFolderSortField(v);
  1737. localStorage.setItem('library-folder-sort-field', v);
  1738. }}
  1739. className="text-xs px-1 py-0.5 rounded bg-bambu-dark border border-bambu-dark-tertiary text-bambu-gray focus:outline-none focus:border-bambu-green"
  1740. title={t('fileManager.folderSort')}
  1741. aria-label={t('fileManager.folderSort')}
  1742. >
  1743. <option value="name">{t('fileManager.folderSortByName')}</option>
  1744. <option value="activity">{t('fileManager.folderSortByActivity')}</option>
  1745. </select>
  1746. <button
  1747. onClick={() => {
  1748. const newValue = folderSortDirection === 'asc' ? 'desc' : 'asc';
  1749. setFolderSortDirection(newValue);
  1750. localStorage.setItem('library-folder-sort-direction', newValue);
  1751. }}
  1752. className="text-bambu-gray hover:text-white hover:bg-bambu-dark p-1 rounded transition-colors"
  1753. title={folderSortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
  1754. aria-label={folderSortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
  1755. >
  1756. {folderSortDirection === 'asc' ? <SortAsc className="w-3.5 h-3.5" /> : <SortDesc className="w-3.5 h-3.5" />}
  1757. </button>
  1758. <button
  1759. onClick={() => {
  1760. const newValue = !collapseFoldersByDefault;
  1761. setCollapseFoldersByDefault(newValue);
  1762. localStorage.setItem('library-collapse-folders', String(newValue));
  1763. }}
  1764. className={`text-xs px-1.5 py-0.5 rounded transition-colors ${
  1765. collapseFoldersByDefault
  1766. ? 'bg-bambu-green/20 text-bambu-green'
  1767. : 'text-bambu-gray hover:text-white hover:bg-bambu-dark'
  1768. }`}
  1769. title={collapseFoldersByDefault ? t('fileManager.expandFoldersByDefault') : t('fileManager.collapseFoldersByDefault')}
  1770. >
  1771. {t('fileManager.collapse')}
  1772. </button>
  1773. <button
  1774. onClick={() => {
  1775. const newValue = !wrapFolderNames;
  1776. setWrapFolderNames(newValue);
  1777. localStorage.setItem('library-wrap-folders', String(newValue));
  1778. }}
  1779. className={`text-xs px-1.5 py-0.5 rounded transition-colors ${
  1780. wrapFolderNames
  1781. ? 'bg-bambu-green/20 text-bambu-green'
  1782. : 'text-bambu-gray hover:text-white hover:bg-bambu-dark'
  1783. }`}
  1784. title={wrapFolderNames ? t('fileManager.disableTextWrapping') : t('fileManager.enableTextWrapping')}
  1785. >
  1786. {t('fileManager.wrap')}
  1787. </button>
  1788. </div>
  1789. </div>
  1790. <div className="flex-1 overflow-y-auto p-2">
  1791. {/* All Files = the user's own uploaded / managed-storage files
  1792. only. External folders are surfaced separately below to keep
  1793. a linked NAS from drowning the user's own uploads (#1621). */}
  1794. <div
  1795. className={`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${
  1796. selectedFolderId === null && topLevelView === 'internal'
  1797. ? 'bg-bambu-green/20 text-bambu-green'
  1798. : 'hover:bg-bambu-dark text-white'
  1799. }`}
  1800. onClick={() => {
  1801. setSelectedFolderId(null);
  1802. setTopLevelView('internal');
  1803. }}
  1804. >
  1805. <FileBox className="w-4 h-4" />
  1806. <span className="text-sm">{t('fileManager.allFiles')}</span>
  1807. </div>
  1808. {/* External (combined) — only shown when at least one external
  1809. folder is linked. Single folder users don't need a combined
  1810. view; clicking the individual folder is just as fast. */}
  1811. {folders?.some((f) => f.is_external) && (
  1812. <div
  1813. className={`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${
  1814. selectedFolderId === null && topLevelView === 'external'
  1815. ? 'bg-bambu-green/20 text-bambu-green'
  1816. : 'hover:bg-bambu-dark text-white'
  1817. }`}
  1818. onClick={() => {
  1819. setSelectedFolderId(null);
  1820. setTopLevelView('external');
  1821. }}
  1822. >
  1823. <FolderSymlink className="w-4 h-4 text-purple-600 dark:text-purple-400" />
  1824. <span className="text-sm">{t('fileManager.allExternal')}</span>
  1825. </div>
  1826. )}
  1827. {/* Folder tree — re-key on the collapse toggle so flipping it
  1828. remounts every FolderTreeItem, which re-reads defaultExpanded
  1829. and makes the preference take effect immediately. */}
  1830. {sortedFolders?.map((folder) => (
  1831. <FolderTreeItem
  1832. key={`${folder.id}-${collapseFoldersByDefault ? 'c' : 'e'}`}
  1833. folder={folder}
  1834. selectedFolderId={selectedFolderId}
  1835. onSelect={setSelectedFolderId}
  1836. onDelete={(id) => setDeleteConfirm({ type: 'folder', id })}
  1837. onLink={setLinkFolder}
  1838. onRename={(f) => setRenameItem({ type: 'folder', id: f.id, name: f.name })}
  1839. wrapNames={wrapFolderNames}
  1840. defaultExpanded={!collapseFoldersByDefault}
  1841. hasPermission={hasPermission}
  1842. t={t}
  1843. />
  1844. ))}
  1845. </div>
  1846. </div>
  1847. {/* Files area + README rail (#2520 item 2). On wide screens the
  1848. README docks as a collapsible right-hand column (rendered after
  1849. the files column, below) so it no longer steals vertical space
  1850. from the file list; on narrow screens it stacks above the list
  1851. via `order-first` and the page itself scrolls. */}
  1852. <div className="flex-1 flex flex-col lg:flex-row min-w-0 min-h-0 gap-4 lg:gap-6">
  1853. <div className="flex-1 flex flex-col min-w-0 min-h-0">
  1854. {/* Tag filter rail (#1268). Lists every catalog tag as a togglable
  1855. chip — active chips are filled green and show an X, inactive
  1856. chips are outlined and toggle ON when clicked. Clicking an active
  1857. chip removes it from the filter. Hidden entirely when the
  1858. catalog is empty so brand-new installs don't see a stray rail. */}
  1859. {tagCatalog.length > 0 && (
  1860. <div className="mb-3 flex flex-wrap items-center gap-2 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary">
  1861. <span className="text-xs text-bambu-gray font-medium shrink-0">
  1862. {t('fileManager.tags.filterLabel')}
  1863. </span>
  1864. {tagCatalog.map((tg) => {
  1865. const active = selectedTagIds.includes(tg.id);
  1866. return (
  1867. <button
  1868. key={tg.id}
  1869. type="button"
  1870. onClick={() => toggleTagFilter(tg.id)}
  1871. className={
  1872. active
  1873. ? 'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-bambu-green/20 text-bambu-green border border-bambu-green/40 hover:bg-bambu-green/30 transition-colors'
  1874. : 'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-bambu-dark text-bambu-gray border border-bambu-dark-tertiary hover:text-white hover:border-bambu-green/40 transition-colors'
  1875. }
  1876. title={tg.name}
  1877. >
  1878. <TagIcon className="w-3 h-3" />
  1879. <span>{tg.name}</span>
  1880. {active && <X className="w-3 h-3" />}
  1881. </button>
  1882. );
  1883. })}
  1884. {selectedTagIds.length > 0 && (
  1885. <button
  1886. type="button"
  1887. onClick={() => setSelectedTagIds([])}
  1888. className="ml-auto text-xs text-bambu-gray hover:text-white shrink-0"
  1889. >
  1890. {t('fileManager.tags.clearAll')}
  1891. </button>
  1892. )}
  1893. </div>
  1894. )}
  1895. {/* External folder info bar */}
  1896. {selectedFolder?.is_external && (
  1897. <div className="flex items-center gap-3 mb-4 p-3 bg-purple-50 dark:bg-purple-500/10 border border-purple-300 dark:border-purple-500/30 rounded-lg">
  1898. <FolderSymlink className="w-5 h-5 text-purple-600 dark:text-purple-400 flex-shrink-0" />
  1899. <div className="flex-1 min-w-0">
  1900. <div className="flex items-center gap-2">
  1901. <span className="text-sm font-medium text-purple-700 dark:text-purple-300">{t('fileManager.externalFolder')}</span>
  1902. {selectedFolder.external_readonly && (
  1903. <span className="text-xs px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400 flex items-center gap-1">
  1904. <Lock className="w-3 h-3" />
  1905. {t('fileManager.readOnly')}
  1906. </span>
  1907. )}
  1908. </div>
  1909. <p className="text-xs text-bambu-gray truncate font-mono" title={selectedFolder.external_path || ''}>
  1910. {selectedFolder.external_path}
  1911. </p>
  1912. </div>
  1913. <Button
  1914. variant="secondary"
  1915. size="sm"
  1916. onClick={() => selectedFolderId && scanExternalFolderMutation.mutate(selectedFolderId)}
  1917. disabled={scanExternalFolderMutation.isPending}
  1918. title={t('fileManager.scanFolder')}
  1919. >
  1920. {scanExternalFolderMutation.isPending ? (
  1921. <Loader2 className="w-4 h-4 animate-spin" />
  1922. ) : (
  1923. <RefreshCw className="w-4 h-4" />
  1924. )}
  1925. <span className="ml-1.5">{t('fileManager.scanFolder')}</span>
  1926. </Button>
  1927. </div>
  1928. )}
  1929. {/* Search, Filter, Sort toolbar - sticky on mobile for easier access */}
  1930. {files && files.length > 0 && (
  1931. <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static">
  1932. {/* Search */}
  1933. <div className="relative w-full sm:w-auto sm:flex-1 sm:max-w-xs">
  1934. <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
  1935. <input
  1936. type="text"
  1937. placeholder={t('fileManager.searchFiles')}
  1938. value={searchQuery}
  1939. onChange={(e) => setSearchQuery(e.target.value)}
  1940. className="w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"
  1941. />
  1942. {searchExpandsSubfolders && (
  1943. <span
  1944. className="absolute -bottom-4 left-0 text-[10px] text-bambu-gray whitespace-nowrap"
  1945. title={t('fileManager.searchSubfoldersHint')}
  1946. >
  1947. {t('fileManager.searchSubfoldersHint')}
  1948. </span>
  1949. )}
  1950. </div>
  1951. {/* Type filter */}
  1952. <div className="flex items-center gap-2">
  1953. <Filter className="w-4 h-4 text-bambu-gray hidden sm:block" />
  1954. <select
  1955. value={filterType}
  1956. onChange={(e) => setFilterType(e.target.value)}
  1957. className="bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green"
  1958. >
  1959. <option value="all">{t('fileManager.allTypes')}</option>
  1960. {fileTypes.map((type) => (
  1961. <option key={type} value={type}>
  1962. {type.toUpperCase()}
  1963. </option>
  1964. ))}
  1965. </select>
  1966. </div>
  1967. {/* Username filter with autocomplete - only show when auth is enabled */}
  1968. {authEnabled && (
  1969. <div className="relative">
  1970. <input
  1971. type="text"
  1972. placeholder={t('fileManager.filterByUser', { defaultValue: 'Filter by user' })}
  1973. value={filterUsername}
  1974. onChange={(e) => setFilterUsername(e.target.value)}
  1975. list="usernames-list"
  1976. className={`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${filterUsername ? 'pr-7' : ''}`}
  1977. style={filterUsername ? { WebkitAppearance: 'none', MozAppearance: 'textfield' } : undefined}
  1978. />
  1979. {filterUsername && (
  1980. <button
  1981. onClick={() => setFilterUsername('')}
  1982. className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10"
  1983. >
  1984. <X className="w-3 h-3" />
  1985. </button>
  1986. )}
  1987. <datalist id="usernames-list">
  1988. {users?.map((user) => (
  1989. <option key={user.id} value={user.username} />
  1990. ))}
  1991. </datalist>
  1992. </div>
  1993. )}
  1994. {/* Sort */}
  1995. <div className="flex items-center gap-2">
  1996. <select
  1997. value={sortField}
  1998. onChange={(e) => {
  1999. const newField = e.target.value as SortField;
  2000. setSortField(newField);
  2001. localStorage.setItem('library-sort-field', newField);
  2002. }}
  2003. className="bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green"
  2004. >
  2005. <option value="name">{t('common.name')}</option>
  2006. <option value="date">{t('common.date')}</option>
  2007. <option value="size">{t('fileManager.size')}</option>
  2008. <option value="type">{t('common.type')}</option>
  2009. <option value="prints">{t('fileManager.prints')}</option>
  2010. </select>
  2011. <button
  2012. onClick={() => setSortDirection((d) => {
  2013. const newDir = d === 'asc' ? 'desc' : 'asc';
  2014. localStorage.setItem('library-sort-direction', newDir);
  2015. return newDir;
  2016. })}
  2017. className="p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors"
  2018. title={sortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
  2019. >
  2020. {sortDirection === 'asc' ? (
  2021. <SortAsc className="w-4 h-4 text-white" />
  2022. ) : (
  2023. <SortDesc className="w-4 h-4 text-white" />
  2024. )}
  2025. </button>
  2026. <button
  2027. onClick={() => setShowModified((v) => {
  2028. const next = !v;
  2029. localStorage.setItem('library-show-modified', String(next));
  2030. return next;
  2031. })}
  2032. className={`p-1.5 rounded bg-bambu-dark border transition-colors ${
  2033. showModified ? 'border-bambu-green text-bambu-green' : 'border-bambu-dark-tertiary text-white hover:border-bambu-green'
  2034. }`}
  2035. title={showModified ? t('fileManager.hideModified') : t('fileManager.showModified')}
  2036. aria-pressed={showModified}
  2037. >
  2038. <CalendarClock className="w-4 h-4" />
  2039. </button>
  2040. </div>
  2041. {/* Results count */}
  2042. {(searchQuery || filterType !== 'all' || filterUsername) && (
  2043. <span className="text-sm text-bambu-gray hidden sm:inline">
  2044. {t('fileManager.resultsCount', { showing: filteredAndSortedFiles.length, total: files.length })}
  2045. </span>
  2046. )}
  2047. </div>
  2048. )}
  2049. {/* Selection toolbar - sticky on mobile below search bar */}
  2050. {filteredAndSortedFiles.length > 0 && (
  2051. <div className="flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static">
  2052. {/* Select all / Deselect all */}
  2053. {selectedFiles.length === filteredAndSortedFiles.length && selectedFiles.length > 0 ? (
  2054. <Button
  2055. variant="secondary"
  2056. size="sm"
  2057. onClick={handleDeselectAll}
  2058. >
  2059. <Square className="w-4 h-4 sm:mr-1" />
  2060. <span className="hidden sm:inline">{t('fileManager.deselectAll')}</span>
  2061. </Button>
  2062. ) : (
  2063. <Button
  2064. variant="secondary"
  2065. size="sm"
  2066. onClick={handleSelectAll}
  2067. >
  2068. <CheckSquare className="w-4 h-4 sm:mr-1" />
  2069. <span className="hidden sm:inline">{t('fileManager.selectAll')}</span>
  2070. </Button>
  2071. )}
  2072. {selectedFiles.length > 0 && (
  2073. <>
  2074. <span className="text-sm text-bambu-gray ml-2">
  2075. {t('fileManager.selected', { count: selectedFiles.length })}
  2076. </span>
  2077. <div className="hidden sm:block flex-1" />
  2078. <div className="w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0">
  2079. {selectedSlicedFiles.length === 1 && (
  2080. <Button
  2081. variant="primary"
  2082. size="sm"
  2083. onClick={() => setPrintFile(selectedSlicedFiles[0])}
  2084. disabled={!hasPermission('queue:create')}
  2085. title={!hasPermission('queue:create') ? t('fileManager.noPermissionAddToQueue') : undefined}
  2086. >
  2087. <Printer className="w-4 h-4 sm:mr-1" />
  2088. <span className="hidden sm:inline">{t('common.print')}</span>
  2089. </Button>
  2090. )}
  2091. <Button
  2092. variant="secondary"
  2093. size="sm"
  2094. onClick={() => setShowMoveModal(true)}
  2095. disabled={!hasAnyPermission('library:update_own', 'library:update_all')}
  2096. title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.noPermissionMoveFiles') : undefined}
  2097. >
  2098. <MoveRight className="w-4 h-4 sm:mr-1" />
  2099. <span className="hidden sm:inline">{t('common.move')}</span>
  2100. </Button>
  2101. <Button
  2102. variant="secondary"
  2103. size="sm"
  2104. onClick={() => setShowBulkTagsModal(true)}
  2105. disabled={!hasAnyPermission('library:update_own', 'library:update_all')}
  2106. title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.tags.noPermission') : t('fileManager.tags.bulkTooltip')}
  2107. >
  2108. <TagIcon className="w-4 h-4 sm:mr-1" />
  2109. <span className="hidden sm:inline">{t('fileManager.tags.tagAction')}</span>
  2110. </Button>
  2111. <Button
  2112. variant="danger"
  2113. size="sm"
  2114. onClick={() => {
  2115. if (selectedFiles.length === 1) {
  2116. setDeleteConfirm({ type: 'file', id: selectedFiles[0] });
  2117. } else {
  2118. setDeleteConfirm({ type: 'bulk', id: 0, count: selectedFiles.length });
  2119. }
  2120. }}
  2121. disabled={!hasAnyPermission('library:delete_own', 'library:delete_all')}
  2122. title={!hasAnyPermission('library:delete_own', 'library:delete_all') ? t('fileManager.noPermissionDeleteFiles') : undefined}
  2123. >
  2124. <Trash2 className="w-4 h-4 sm:mr-1" />
  2125. <span className="hidden sm:inline">{t('common.delete')}</span>
  2126. </Button>
  2127. <Button
  2128. variant="secondary"
  2129. size="sm"
  2130. onClick={handleDeselectAll}
  2131. >
  2132. <X className="w-4 h-4 sm:mr-1" />
  2133. <span className="hidden sm:inline">{t('common.clear')}</span>
  2134. </Button>
  2135. </div>
  2136. </>
  2137. )}
  2138. </div>
  2139. )}
  2140. {/* File grid/list */}
  2141. {isLoading ? (
  2142. <div className="flex-1 flex items-center justify-center">
  2143. <div className="flex flex-col items-center gap-3">
  2144. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  2145. <p className="text-sm text-bambu-gray">{t('fileManager.loadingFiles')}</p>
  2146. </div>
  2147. </div>
  2148. ) : files?.length === 0 ? (
  2149. <div className="flex-1 flex flex-col items-center justify-center">
  2150. <div className="p-4 bg-bambu-dark rounded-2xl mb-4">
  2151. <FileBox className="w-12 h-12 text-bambu-gray/50" />
  2152. </div>
  2153. <h3 className="text-lg font-medium text-white mb-2">
  2154. {selectedFolderId !== null
  2155. ? t('fileManager.folderIsEmpty')
  2156. : topLevelView === 'external'
  2157. ? t('fileManager.externalIsEmpty')
  2158. : t('fileManager.noFilesYet')}
  2159. </h3>
  2160. <p className="text-bambu-gray text-center max-w-md mb-6">
  2161. {selectedFolderId !== null
  2162. ? t('fileManager.folderEmptyDescription')
  2163. : topLevelView === 'external'
  2164. ? t('fileManager.externalEmptyDescription')
  2165. : t('fileManager.noFilesDescription')}
  2166. </p>
  2167. <Button
  2168. onClick={() => setShowUploadModal(true)}
  2169. disabled={!hasPermission('library:upload')}
  2170. title={!hasPermission('library:upload') ? t('fileManager.noPermissionUpload') : undefined}
  2171. >
  2172. <Plus className="w-4 h-4 mr-2" />
  2173. {t('fileManager.uploadFiles')}
  2174. </Button>
  2175. </div>
  2176. ) : filteredAndSortedFiles.length === 0 ? (
  2177. <div className="flex-1 flex flex-col items-center justify-center">
  2178. <div className="p-4 bg-bambu-dark rounded-2xl mb-4">
  2179. <Search className="w-12 h-12 text-bambu-gray/50" />
  2180. </div>
  2181. <h3 className="text-lg font-medium text-white mb-2">{t('fileManager.noMatchingFiles')}</h3>
  2182. <p className="text-bambu-gray text-center max-w-md mb-6">
  2183. {t('fileManager.noMatchingFilesDescription')}
  2184. </p>
  2185. <Button variant="secondary" onClick={() => { setSearchQuery(''); setFilterType('all'); }}>
  2186. {t('fileManager.clearFilters')}
  2187. </Button>
  2188. </div>
  2189. ) : viewMode === 'grid' ? (
  2190. <div className="flex-1 lg:overflow-y-auto">
  2191. <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
  2192. {filteredAndSortedFiles.map((file) => (
  2193. <FileCard
  2194. key={file.id}
  2195. file={file}
  2196. isSelected={selectedFiles.includes(file.id)}
  2197. isMobile={isMobile}
  2198. t={t}
  2199. onSelect={handleFileSelect}
  2200. onDelete={(id) => setDeleteConfirm({ type: 'file', id })}
  2201. onDownload={handleDownload}
  2202. onPrint={setPrintFile}
  2203. onSlice={setSliceFile}
  2204. onRunPipeline={setRunPipelineFile}
  2205. useSlicerApi={settings?.use_slicer_api ?? false}
  2206. onPreview3d={(f) => {
  2207. // Sliced files (.gcode / .gcode.3mf) open the same
  2208. // full-page gcode viewer the archive card uses, so
  2209. // the two paths feel consistent. STL / source 3MF
  2210. // continue to use the in-app 3D model viewer modal.
  2211. if (isSlicedFilename(f.filename)) {
  2212. navigate(`/gcode-viewer?library_file=${f.id}`);
  2213. } else {
  2214. setViewerFile(f);
  2215. }
  2216. }}
  2217. onRename={(f) => setRenameItem({ type: 'file', id: f.id, name: f.filename })}
  2218. onGenerateThumbnail={(f) => singleThumbnailMutation.mutate(f.id)}
  2219. onTagClick={toggleTagFilter}
  2220. thumbnailVersion={thumbnailVersions[file.id]}
  2221. hasPermission={hasPermission}
  2222. canModify={canModify}
  2223. authEnabled={authEnabled}
  2224. showModified={showModified}
  2225. />
  2226. ))}
  2227. </div>
  2228. </div>
  2229. ) : (
  2230. <div className="flex-1 lg:overflow-y-auto">
  2231. {/* The wrapper has overflow-x-auto so a narrow viewport scrolls
  2232. horizontally instead of clipping the actions column off the
  2233. right edge. The previous `overflow-hidden` was there for the
  2234. rounded corners but also swallowed any content the actions
  2235. column couldn't fit (#1325 follow-up reported in chat). */}
  2236. <div className="bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-x-auto">
  2237. {/* List header - hidden on mobile, show simplified on small screens.
  2238. Trailing actions column is fixed at 220px (sliced 3MF = 7 icons
  2239. ~220px). It used to be `min-content`, but header + body are sibling
  2240. grids that compute `min-content` independently — the header's empty
  2241. trailing div resolved to 0px, leaving body columns shifted left of
  2242. their headers. Fixed width keeps header and body in lockstep. */}
  2243. <div className={`hidden sm:grid ${authEnabled ? 'grid-cols-[auto_1fr_120px_100px_100px_100px_minmax(0,200px)_220px]' : 'grid-cols-[auto_1fr_100px_100px_100px_minmax(0,200px)_220px]'} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`}>
  2244. <div className="w-6" />
  2245. <div>{t('common.name')}</div>
  2246. {authEnabled && <div>{t('fileManager.uploadedBy', { defaultValue: 'Uploaded By' })}</div>}
  2247. <div>{t('common.type')}</div>
  2248. <div>{t('fileManager.size')}</div>
  2249. <div>{t('fileManager.prints')}</div>
  2250. <div>{t('fileManager.tags.title')}</div>
  2251. <div />
  2252. </div>
  2253. {/* List rows */}
  2254. {filteredAndSortedFiles.map((file) => (
  2255. <div
  2256. key={file.id}
  2257. className={`grid ${authEnabled ? 'grid-cols-[auto_1fr_120px_100px_100px_100px_minmax(0,200px)_220px]' : 'grid-cols-[auto_1fr_100px_100px_100px_minmax(0,200px)_220px]'} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${
  2258. selectedFiles.includes(file.id) ? 'bg-bambu-green/10' : ''
  2259. }`}
  2260. onClick={() => handleFileSelect(file.id)}
  2261. >
  2262. {/* Checkbox */}
  2263. <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
  2264. selectedFiles.includes(file.id)
  2265. ? 'bg-bambu-green border-bambu-green'
  2266. : 'border-bambu-gray/50'
  2267. }`}>
  2268. {selectedFiles.includes(file.id) && <div className="w-2 h-2 bg-white rounded-sm" />}
  2269. </div>
  2270. {/* Name with thumbnail */}
  2271. <div className="flex items-center gap-3 min-w-0">
  2272. <div className="relative group/thumb">
  2273. <div className="w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden">
  2274. {file.thumbnail_path ? (
  2275. <img
  2276. src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersions[file.id] ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersions[file.id]}`) : ''}`}
  2277. alt=""
  2278. className="w-full h-full object-cover"
  2279. />
  2280. ) : (
  2281. <div className="w-full h-full flex items-center justify-center">
  2282. <FileBox className="w-5 h-5 text-bambu-gray/50" />
  2283. </div>
  2284. )}
  2285. </div>
  2286. {/* Hover preview */}
  2287. {file.thumbnail_path && (
  2288. <div className="absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block">
  2289. <div className="w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden">
  2290. <img
  2291. src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersions[file.id] ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersions[file.id]}`) : ''}`}
  2292. alt={file.filename}
  2293. className="w-full h-full object-contain"
  2294. />
  2295. </div>
  2296. </div>
  2297. )}
  2298. </div>
  2299. <div className="min-w-0">
  2300. <div className="text-sm text-white truncate">{file.print_name || file.filename}</div>
  2301. {/* #2680: last-modified date under the name, toggled from
  2302. the toolbar. Real on-disk mtime when known, else created_at. */}
  2303. {showModified && (
  2304. <div className="text-xs text-bambu-gray flex items-center gap-1 mt-0.5" title={t('fileManager.lastModified')}>
  2305. <CalendarClock className="w-3 h-3 flex-shrink-0" />
  2306. <span className="truncate">{formatDate(file.fs_modified_at ?? file.created_at)}</span>
  2307. </div>
  2308. )}
  2309. </div>
  2310. </div>
  2311. {/* Uploaded By - only show when auth is enabled */}
  2312. {authEnabled && (
  2313. <div className="text-sm text-bambu-gray flex items-center gap-1">
  2314. {file.created_by_username ? (
  2315. <>
  2316. <User className="w-3 h-3" />
  2317. <span className="truncate">{file.created_by_username}</span>
  2318. </>
  2319. ) : (
  2320. '-'
  2321. )}
  2322. </div>
  2323. )}
  2324. {/* Type */}
  2325. <div>
  2326. <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${
  2327. file.file_type === '3mf' ? 'bg-bambu-green/20 text-bambu-green'
  2328. : (file.file_type === 'gcode' || file.file_type === 'gcode.3mf') ? 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400'
  2329. : file.file_type === 'stl' ? 'bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400'
  2330. : 'bg-bambu-gray/20 text-bambu-gray'
  2331. }`}>
  2332. {file.file_type.toUpperCase()}
  2333. </span>
  2334. </div>
  2335. {/* Size */}
  2336. <div className="text-sm text-bambu-gray">{formatFileSize(file.file_size)}</div>
  2337. {/* Prints */}
  2338. <div className="text-sm text-bambu-gray">{file.print_count > 0 ? `${file.print_count}x` : '-'}</div>
  2339. {/* Tags (#1268) — clickable chips push into the active
  2340. filter; minmax(0,200px) on the column lets the cell
  2341. shrink/wrap on narrow viewports without pushing the
  2342. Actions cell off-screen. */}
  2343. <div className="min-w-0" onClick={(e) => e.stopPropagation()}>
  2344. {!file.tags || file.tags.length === 0 ? (
  2345. <span className="text-xs text-bambu-gray/50">-</span>
  2346. ) : (
  2347. <div className="flex flex-wrap gap-1">
  2348. {file.tags.map((tg) => (
  2349. <button
  2350. key={tg.id}
  2351. type="button"
  2352. onClick={() => toggleTagFilter(tg.id)}
  2353. className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[10px] bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20 transition-colors max-w-full"
  2354. title={tg.name}
  2355. >
  2356. <TagIcon className="w-2.5 h-2.5 flex-shrink-0" />
  2357. <span className="truncate">{tg.name}</span>
  2358. </button>
  2359. ))}
  2360. </div>
  2361. )}
  2362. </div>
  2363. {/* Actions */}
  2364. <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
  2365. {isSlicedFilename(file.filename) && (
  2366. <>
  2367. <button
  2368. onClick={() => hasPermission('queue:create') && setPrintFile(file)}
  2369. className={`p-1.5 rounded transition-colors ${
  2370. hasPermission('queue:create')
  2371. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
  2372. : 'text-bambu-gray/50 cursor-not-allowed'
  2373. }`}
  2374. title={hasPermission('queue:create') ? t('common.print') : t('fileManager.noPermissionAddToQueue')}
  2375. disabled={!hasPermission('queue:create')}
  2376. >
  2377. <Printer className="w-4 h-4" />
  2378. </button>
  2379. </>
  2380. )}
  2381. {(settings?.use_slicer_api ?? false) && isSliceableFilename(file.filename) && (
  2382. <button
  2383. onClick={() => hasPermission('library:upload') && setSliceFile(file)}
  2384. className={`p-1.5 rounded transition-colors ${
  2385. hasPermission('library:upload')
  2386. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
  2387. : 'text-bambu-gray/50 cursor-not-allowed'
  2388. }`}
  2389. title={hasPermission('library:upload') ? t('slice.action') : t('fileManager.noPermissionSlice')}
  2390. disabled={!hasPermission('library:upload')}
  2391. >
  2392. <Cog className="w-4 h-4" />
  2393. </button>
  2394. )}
  2395. {(settings?.use_slicer_api ?? false) && isSliceableFilename(file.filename) && (
  2396. <button
  2397. onClick={() => hasPermission('pipelines:run') && setRunPipelineFile(file)}
  2398. className={`p-1.5 rounded transition-colors ${
  2399. hasPermission('pipelines:run')
  2400. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
  2401. : 'text-bambu-gray/50 cursor-not-allowed'
  2402. }`}
  2403. title={hasPermission('pipelines:run') ? t('library.runWithPipeline.actionLabel', 'Run with pipeline') : t('library.runWithPipeline.noPermission', 'You do not have permission to run pipelines')}
  2404. disabled={!hasPermission('pipelines:run')}
  2405. >
  2406. <Play className="w-4 h-4" />
  2407. </button>
  2408. )}
  2409. {(file.file_type === '3mf' || file.file_type === 'gcode' || file.file_type === 'gcode.3mf' || file.file_type === 'stl') && (
  2410. <button
  2411. onClick={() => {
  2412. if (!hasPermission('library:read')) return;
  2413. if (isSlicedFilename(file.filename)) {
  2414. navigate(`/gcode-viewer?library_file=${file.id}`);
  2415. } else {
  2416. setViewerFile(file);
  2417. }
  2418. }}
  2419. className={`p-1.5 rounded transition-colors ${
  2420. hasPermission('library:read')
  2421. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
  2422. : 'text-bambu-gray/50 cursor-not-allowed'
  2423. }`}
  2424. title={hasPermission('library:read') ? '3D Preview' : 'You do not have permission to preview files'}
  2425. disabled={!hasPermission('library:read')}
  2426. >
  2427. <Box className="w-4 h-4" />
  2428. </button>
  2429. )}
  2430. <button
  2431. onClick={() => hasPermission('library:read') && handleDownload(file.id)}
  2432. className={`p-1.5 rounded transition-colors ${
  2433. hasPermission('library:read')
  2434. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-white'
  2435. : 'text-bambu-gray/50 cursor-not-allowed'
  2436. }`}
  2437. title={hasPermission('library:read') ? t('common.download') : t('fileManager.noPermissionDownload')}
  2438. disabled={!hasPermission('library:read')}
  2439. >
  2440. <Download className="w-4 h-4" />
  2441. </button>
  2442. <button
  2443. onClick={() => canModify('library', 'update', file.created_by_id) && setRenameItem({ type: 'file', id: file.id, name: file.filename })}
  2444. className={`p-1.5 rounded transition-colors ${
  2445. canModify('library', 'update', file.created_by_id)
  2446. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-white'
  2447. : 'text-bambu-gray/50 cursor-not-allowed'
  2448. }`}
  2449. title={canModify('library', 'update', file.created_by_id) ? t('common.rename') : t('fileManager.noPermissionRenameFile')}
  2450. disabled={!canModify('library', 'update', file.created_by_id)}
  2451. >
  2452. <Pencil className="w-4 h-4" />
  2453. </button>
  2454. {file.file_type === 'stl' && (
  2455. <button
  2456. onClick={() => canModify('library', 'update', file.created_by_id) && singleThumbnailMutation.mutate(file.id)}
  2457. className={`p-1.5 rounded transition-colors ${
  2458. canModify('library', 'update', file.created_by_id)
  2459. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
  2460. : 'text-bambu-gray/50 cursor-not-allowed'
  2461. }`}
  2462. title={canModify('library', 'update', file.created_by_id) ? t('fileManager.generateThumbnail') : t('fileManager.noPermissionGenerateThumbnail')}
  2463. disabled={singleThumbnailMutation.isPending || !canModify('library', 'update', file.created_by_id)}
  2464. >
  2465. <Image className="w-4 h-4" />
  2466. </button>
  2467. )}
  2468. <button
  2469. onClick={() => canModify('library', 'delete', file.created_by_id) && setDeleteConfirm({ type: 'file', id: file.id })}
  2470. className={`p-1.5 rounded transition-colors ${
  2471. canModify('library', 'delete', file.created_by_id)
  2472. ? 'hover:bg-bambu-dark text-bambu-gray hover:text-red-700 dark:hover:text-red-400'
  2473. : 'text-bambu-gray/50 cursor-not-allowed'
  2474. }`}
  2475. title={canModify('library', 'delete', file.created_by_id) ? t('common.delete') : t('fileManager.noPermissionDeleteFile')}
  2476. disabled={!canModify('library', 'delete', file.created_by_id)}
  2477. >
  2478. <Trash2 className="w-4 h-4" />
  2479. </button>
  2480. </div>
  2481. </div>
  2482. ))}
  2483. </div>
  2484. </div>
  2485. )}
  2486. </div>
  2487. {/* README rail — collapsible right column on lg+, stacks on top
  2488. on mobile. See the files-area wrapper comment above (#2520). */}
  2489. {selectedFolderId !== null && <FolderReadmePanel folderId={selectedFolderId} />}
  2490. </div>
  2491. </div>
  2492. {/* Modals */}
  2493. {showNewFolderModal && (
  2494. <NewFolderModal
  2495. parentId={selectedFolderId}
  2496. onClose={() => setShowNewFolderModal(false)}
  2497. onSave={(data) => createFolderMutation.mutate(data)}
  2498. isLoading={createFolderMutation.isPending}
  2499. t={t}
  2500. />
  2501. )}
  2502. {showExternalFolderModal && (
  2503. <ExternalFolderModal
  2504. onClose={() => setShowExternalFolderModal(false)}
  2505. onSave={(data) => createExternalFolderMutation.mutate(data)}
  2506. isLoading={createExternalFolderMutation.isPending}
  2507. t={t}
  2508. />
  2509. )}
  2510. {showMoveModal && folders && (
  2511. <MoveFilesModal
  2512. folders={folders}
  2513. selectedFiles={selectedFiles}
  2514. currentFolderId={selectedFolderId}
  2515. onClose={() => setShowMoveModal(false)}
  2516. onMove={(folderId) => moveFilesMutation.mutate({ fileIds: selectedFiles, folderId })}
  2517. isLoading={moveFilesMutation.isPending}
  2518. t={t}
  2519. />
  2520. )}
  2521. {showUploadModal && (
  2522. <FileUploadModal
  2523. folderId={selectedFolderId}
  2524. onClose={() => {
  2525. setShowUploadModal(false);
  2526. setDroppedFiles([]);
  2527. }}
  2528. onUploadComplete={handleUploadComplete}
  2529. initialFiles={droppedFiles.length > 0 ? droppedFiles : undefined}
  2530. />
  2531. )}
  2532. {showPurgeModal && (
  2533. <PurgeOldFilesModal onClose={() => setShowPurgeModal(false)} />
  2534. )}
  2535. <LibraryTagsModal
  2536. open={showTagsModal}
  2537. onClose={() => setShowTagsModal(false)}
  2538. onPickTag={(tagId) => {
  2539. if (!selectedTagIds.includes(tagId)) {
  2540. setSelectedTagIds((prev) => [...prev, tagId]);
  2541. }
  2542. }}
  2543. />
  2544. <BulkTagsPickerModal
  2545. open={showBulkTagsModal}
  2546. fileIds={selectedFiles}
  2547. onClose={() => setShowBulkTagsModal(false)}
  2548. />
  2549. {linkFolder && (
  2550. <LinkFolderModal
  2551. folder={linkFolder}
  2552. onClose={() => setLinkFolder(null)}
  2553. onLink={(data) => updateFolderMutation.mutate({ id: linkFolder.id, data })}
  2554. isLoading={updateFolderMutation.isPending}
  2555. t={t}
  2556. />
  2557. )}
  2558. {deleteConfirm && (
  2559. <ConfirmModal
  2560. title={
  2561. deleteConfirm.type === 'folder'
  2562. ? t('fileManager.deleteFolder')
  2563. : deleteConfirm.type === 'bulk'
  2564. ? t('fileManager.deleteFilesCount', { count: deleteConfirm.count })
  2565. : t('fileManager.deleteFile')
  2566. }
  2567. message={
  2568. deleteConfirm.type === 'folder'
  2569. ? t('fileManager.deleteFolderConfirm')
  2570. : deleteConfirm.type === 'bulk'
  2571. ? t('fileManager.deleteFilesConfirm', { count: deleteConfirm.count })
  2572. : t('fileManager.deleteFileConfirm')
  2573. }
  2574. confirmText={t('common.delete')}
  2575. variant="danger"
  2576. isLoading={isDeleting}
  2577. loadingText={t('fileManager.deleting')}
  2578. onConfirm={handleDeleteConfirm}
  2579. onCancel={() => setDeleteConfirm(null)}
  2580. />
  2581. )}
  2582. {printFile && (
  2583. <PrintModal
  2584. mode="create"
  2585. libraryFileId={printFile.id}
  2586. archiveName={printFile.print_name || printFile.filename}
  2587. onClose={() => setPrintFile(null)}
  2588. onSuccess={() => {
  2589. setPrintFile(null);
  2590. setSelectedFiles([]);
  2591. queryClient.invalidateQueries({ queryKey: ['library-files'] });
  2592. queryClient.invalidateQueries({ queryKey: ['queue'] });
  2593. queryClient.invalidateQueries({ queryKey: ['archives'] });
  2594. }}
  2595. />
  2596. )}
  2597. {sliceFile && (
  2598. <SliceModal
  2599. source={{ kind: 'libraryFile', id: sliceFile.id, filename: sliceFile.filename }}
  2600. onClose={() => setSliceFile(null)}
  2601. />
  2602. )}
  2603. {runPipelineFile && (
  2604. <RunWithPipelineModal
  2605. source={{ kind: 'libraryFile', id: runPipelineFile.id, filename: runPipelineFile.filename }}
  2606. onClose={() => setRunPipelineFile(null)}
  2607. />
  2608. )}
  2609. {viewerFile && (
  2610. <ModelViewerModal
  2611. libraryFileId={viewerFile.id}
  2612. title={viewerFile.print_name || viewerFile.filename}
  2613. fileType={viewerFile.file_type}
  2614. onClose={() => setViewerFile(null)}
  2615. onSliceWithBambuddy={
  2616. // Only offer in-app slicing on files the SliceModal can actually
  2617. // handle (matches the file-row Cog visibility check at :2127).
  2618. isSliceableFilename(viewerFile.filename) && hasPermission('library:upload')
  2619. ? () => {
  2620. const f = viewerFile;
  2621. setViewerFile(null);
  2622. setSliceFile(f);
  2623. }
  2624. : undefined
  2625. }
  2626. />
  2627. )}
  2628. {renameItem && (
  2629. <RenameModal
  2630. type={renameItem.type}
  2631. currentName={renameItem.name}
  2632. onClose={() => setRenameItem(null)}
  2633. onSave={(newName) => {
  2634. if (renameItem.type === 'file') {
  2635. renameFileMutation.mutate({ id: renameItem.id, filename: newName });
  2636. } else {
  2637. renameFolderMutation.mutate({ id: renameItem.id, name: newName });
  2638. }
  2639. }}
  2640. isLoading={renameFileMutation.isPending || renameFolderMutation.isPending}
  2641. t={t}
  2642. />
  2643. )}
  2644. </div>
  2645. );
  2646. }