FileManagerPage.tsx 147 KB

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