FileManagerPage.tsx 188 KB

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