FileManagerPage.tsx 124 KB

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