FileManagerPage.tsx 186 KB

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