FileManagerPage.tsx 132 KB

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