FileManagerPage.tsx 181 KB

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