FileManagerPage.tsx 134 KB

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