| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180 |
- import { useState, useRef, useCallback, useMemo, useEffect, lazy, Suspense } from 'react';
- import { Link, useNavigate, useSearchParams } from 'react-router-dom';
- import { useQuery, useQueries, useMutation, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
- import { useTranslation } from 'react-i18next';
- import {
- FolderOpen,
- Loader2,
- Plus,
- Upload,
- Trash2,
- Download,
- ExternalLink,
- MoreVertical,
- ChevronRight,
- FolderPlus,
- FileBox,
- Clock,
- CalendarClock,
- HardDrive,
- File,
- MoveRight,
- CheckSquare,
- Square,
- Layers,
- LayoutGrid,
- List,
- Search,
- SortAsc,
- SortDesc,
- AlertTriangle,
- Filter,
- X,
- Link2,
- Unlink,
- Archive as ArchiveIcon,
- Briefcase,
- Cog,
- Play,
- Printer,
- Pencil,
- Image,
- User,
- Box,
- RefreshCw,
- Lock,
- FolderSymlink,
- Tag as TagIcon,
- FileText,
- FileSpreadsheet,
- Info,
- Globe,
- Users,
- StickyNote,
- Camera,
- Eye,
- Combine,
- Columns,
- ChevronRight as ChevronRightIcon,
- } from 'lucide-react';
- import { api } from '../api/client';
- import type {
- LibraryFolderTree,
- LibraryFileListItem,
- LibraryFolderCreate,
- LibraryFolderUpdate,
- ExternalFolderCreate,
- Archive,
- Permission,
- } from '../api/client';
- import { Button } from '../components/Button';
- import { ConfirmModal } from '../components/ConfirmModal';
- import { ContextMenu, type ContextMenuItem } from '../components/ContextMenu';
- import { PrintModal } from '../components/PrintModal';
- import { ModelViewerModal } from '../components/ModelViewerModal';
- import { SliceModal } from '../components/SliceModal';
- import { CombineFilesModal } from '../components/CombineFilesModal';
- import { RunWithPipelineModal } from '../components/RunWithPipelineModal';
- import { BulkTagsPickerModal } from '../components/BulkTagsPickerModal';
- import { FileUploadModal } from '../components/FileUploadModal';
- import { FolderReadmePanel } from '../components/FolderReadmePanel';
- import { LibraryTagsModal } from '../components/LibraryTagsModal';
- import { LibraryFileDetailsModal } from '../components/LibraryFileDetailsModal';
- import { PurgeOldFilesModal } from '../components/PurgeOldFilesModal';
- import { useToast } from '../contexts/ToastContext';
- import { usePageFileDrop } from '../hooks/usePageFileDrop';
- import { useAuth } from '../contexts/AuthContext';
- import { formatDuration, parseUTCDate, formatDate } from '../utils/date';
- import { formatFileSize } from '../utils/file';
- import { assignableProjects } from '../utils/projectTree';
- import { openInSlicer, resolveDesktopSlicer, type SlicerType } from '../utils/slicer';
- import { isSlicedLibraryFile, isSliceableLibraryFile } from '../utils/libraryFiles';
- import { useUiSettings } from '../hooks/useUiSettings';
- type SortField = 'name' | 'date' | 'size' | 'type' | 'prints';
- type SortDirection = 'asc' | 'desc';
- type TFunction = (key: string, options?: Record<string, unknown>) => string;
- // Document previews (#2976) are code-split: pdf.js and the spreadsheet
- // parsers only load when a preview is actually opened.
- const PdfPreviewModal = lazy(() =>
- import('../components/PdfPreviewModal').then((m) => ({ default: m.PdfPreviewModal }))
- );
- const SpreadsheetPreviewModal = lazy(() =>
- import('../components/SpreadsheetPreviewModal').then((m) => ({ default: m.SpreadsheetPreviewModal }))
- );
- const ImagePreviewModal = lazy(() =>
- import('../components/ImagePreviewModal').then((m) => ({ default: m.ImagePreviewModal }))
- );
- function isSpreadsheetType(fileType: string): boolean {
- return fileType === 'csv' || fileType === 'xlsx' || fileType === 'ods';
- }
- function isStepType(fileType: string): boolean {
- return fileType === 'step' || fileType === 'stp';
- }
- // Mirrors IMAGE_EXTENSIONS in routes/library.py — the types the server both
- // stores and renders a thumbnail for, and so the ones that get an image icon.
- const IMAGE_TYPES = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tiff', 'tif']);
- // The subset ImagePreviewModal can actually show: it hands the bytes to an
- // <img>, and outside Safari no browser decodes TIFF. Offering the preview
- // would download up to 50 MB only to report "cannot be previewed", so TIFF
- // keeps its server-rendered thumbnail and no preview (#2976).
- const PREVIEWABLE_IMAGE_TYPES = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp']);
- function isImageType(fileType: string): boolean {
- return IMAGE_TYPES.has(fileType.toLowerCase());
- }
- function isPreviewableImageType(fileType: string): boolean {
- return PREVIEWABLE_IMAGE_TYPES.has(fileType.toLowerCase());
- }
- // The icon a file without a thumbnail shows. Shared by the grid card, the list
- // row and the columns view so the three never disagree about a type.
- function FileTypePlaceholderIcon({ fileType, className }: { fileType: string; className: string }) {
- const Icon =
- fileType === 'pdf'
- ? FileText
- : isSpreadsheetType(fileType)
- ? FileSpreadsheet
- : isImageType(fileType)
- ? Image
- : FileBox;
- return <Icon className={className} />;
- }
- /**
- * The columns view's per-level file queries, plus every file they hold — the
- * files a tick in an earlier column can point at (#3020). Module-level, so its
- * reference is stable and useQueries hands back the same value until a query
- * actually changes.
- */
- function combineColumnFileQueries(results: UseQueryResult<LibraryFileListItem[]>[]) {
- return { results, files: results.flatMap((result) => result.data ?? []) };
- }
- // Which files have a preview at all: what a double-click opens, and what the
- // toolbar's Preview button appears for (#2976). Sliced files go to the
- // full-page gcode viewer, everything else to a modal.
- function isPreviewableLibraryFile(file: LibraryFileListItem): boolean {
- const type = file.file_type;
- return (
- isSlicedLibraryFile(file) ||
- type === '3mf' ||
- type === 'stl' ||
- isStepType(type) ||
- type === 'pdf' ||
- isSpreadsheetType(type) ||
- isPreviewableImageType(type)
- );
- }
- // Spread onto a card/row subtree that is not "the row": its own controls must
- // neither toggle the selection nor open the preview. `dblclick` is a separate
- // native event from `click`, so stopping the click alone still lets the second
- // click of a double-click reach the row's onDoubleClick (#2976).
- const stopRowActivation = {
- onClick: (e: React.MouseEvent) => e.stopPropagation(),
- onDoubleClick: (e: React.MouseEvent) => e.stopPropagation(),
- };
- // Whether the preview is the 3D one, which has its own menu label.
- function isModelPreview(file: LibraryFileListItem): boolean {
- return isSlicedLibraryFile(file) || file.file_type === '3mf' || file.file_type === 'stl' || isStepType(file.file_type);
- }
- function documentPreviewIcon(fileType: string) {
- if (fileType === 'pdf') return <FileText className="w-4 h-4" />;
- if (isSpreadsheetType(fileType)) return <FileSpreadsheet className="w-4 h-4" />;
- return <Image className="w-4 h-4" />;
- }
- // Types the server renders a thumbnail for on request, STL through trimesh
- // and PDF through PDFium (#2976), so the per-file "Generate thumbnail" action
- // applies to them. Mirrors the file types batch_generate_stl_thumbnails in
- // routes/library.py selects.
- function hasServerThumbnail(fileType: string): boolean {
- return fileType === 'stl' || fileType === 'pdf';
- }
- // Type badge colours shared by the list row and the columns view. Sliced
- // output shares the gcode blue so users see at a glance that the file is
- // already sliced and ready to print (#1543).
- function fileTypeBadgeClass(fileType: string): string {
- if (fileType === '3mf') return 'bg-bambu-green/20 text-bambu-green';
- if (fileType === 'gcode' || fileType === 'gcode.3mf') return 'bg-blue-100 dark:bg-blue-500/20 text-blue-700 dark:text-blue-400';
- if (fileType === 'stl') return 'bg-purple-100 dark:bg-purple-500/20 text-purple-700 dark:text-purple-400';
- if (isStepType(fileType)) return 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-400';
- if (fileType === 'pdf') return 'bg-red-100 dark:bg-red-500/20 text-red-700 dark:text-red-400';
- if (isSpreadsheetType(fileType)) return 'bg-teal-100 dark:bg-teal-500/20 text-teal-700 dark:text-teal-400';
- return 'bg-bambu-gray/20 text-bambu-gray';
- }
- // Search / type / user filtering plus the sort, shared by the main listing and
- // by each Miller column's file list so a column never sorts differently from
- // the pane beside it. `query` matches the filename and the embedded print name.
- function filterAndSortFiles(
- files: LibraryFileListItem[],
- opts: {
- query?: string;
- filterType: string;
- filterUsername: string;
- sortField: SortField;
- sortDirection: SortDirection;
- },
- ): LibraryFileListItem[] {
- let result = [...files];
- const query = opts.query?.trim().toLowerCase();
- if (query) {
- result = result.filter(
- (f) =>
- f.filename.toLowerCase().includes(query) ||
- (f.print_name && f.print_name.toLowerCase().includes(query))
- );
- }
- if (opts.filterType !== 'all') {
- result = result.filter((f) => f.file_type === opts.filterType);
- }
- const userQuery = opts.filterUsername.trim().toLowerCase();
- if (userQuery) {
- result = result.filter(
- (f) => f.created_by_username && f.created_by_username.toLowerCase().includes(userQuery)
- );
- }
- result.sort((a, b) => {
- let comparison = 0;
- switch (opts.sortField) {
- case 'name':
- comparison = (a.print_name || a.filename).localeCompare(b.print_name || b.filename);
- break;
- case 'date':
- // #2680: sort by real on-disk mtime (matches `ls -t`), falling back to
- // the DB created_at for managed uploads that have no filesystem mtime.
- comparison =
- (parseUTCDate(a.fs_modified_at ?? a.created_at)?.getTime() ?? 0) -
- (parseUTCDate(b.fs_modified_at ?? b.created_at)?.getTime() ?? 0);
- break;
- case 'size':
- comparison = a.file_size - b.file_size;
- break;
- case 'type':
- comparison = a.file_type.localeCompare(b.file_type);
- break;
- case 'prints':
- comparison = a.print_count - b.print_count;
- break;
- }
- return opts.sortDirection === 'asc' ? comparison : -comparison;
- });
- return result;
- }
- // Keep the filename useful when fixed columns consume the available width,
- // and give the header spacer and row checkbox one shared track so every later
- // column stays aligned. min-w-min lets each auth variant size itself to its
- // intrinsic grid width inside the overflow-x-auto wrapper (#3105). Tags get a
- // floor too: with a 0 minimum they took the squeeze the filename used to take,
- // hitting 0px right where the wrapper starts scrolling.
- const fileListGridColumns = (authEnabled: boolean) => authEnabled
- ? 'grid-cols-[24px_minmax(240px,1fr)_120px_100px_100px_100px_minmax(96px,200px)_220px]'
- : 'grid-cols-[24px_minmax(240px,1fr)_100px_100px_100px_minmax(96px,200px)_220px]';
- const fileListGridMinWidth = 'min-w-min';
- // New Folder Modal
- interface NewFolderModalProps {
- parentId: number | null;
- onClose: () => void;
- onSave: (data: LibraryFolderCreate) => void;
- isLoading: boolean;
- t: TFunction;
- }
- function NewFolderModal({ parentId, onClose, onSave, isLoading, t }: NewFolderModalProps) {
- const [name, setName] = useState('');
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- onSave({ name: name.trim(), parent_id: parentId });
- };
- return (
- <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
- <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
- <div className="p-4 border-b border-bambu-dark-tertiary">
- <h2 className="text-lg font-semibold text-white">{t('fileManager.newFolder')}</h2>
- </div>
- <form onSubmit={handleSubmit} className="p-4 space-y-4">
- <div>
- <label className="block text-sm font-medium text-white mb-1">
- {t('fileManager.folderName')}
- </label>
- <input
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- 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"
- placeholder={t('fileManager.folderNamePlaceholder')}
- autoFocus
- required
- />
- </div>
- <div className="flex justify-end gap-2 pt-2">
- <Button type="button" variant="secondary" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button type="submit" disabled={!name.trim() || isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.create')}
- </Button>
- </div>
- </form>
- </div>
- </div>
- );
- }
- // External Folder Modal
- interface ExternalFolderModalProps {
- onClose: () => void;
- onSave: (data: ExternalFolderCreate) => void;
- isLoading: boolean;
- t: TFunction;
- }
- function ExternalFolderModal({ onClose, onSave, isLoading, t }: ExternalFolderModalProps) {
- const [name, setName] = useState('');
- const [path, setPath] = useState('');
- const [readonly, setReadonly] = useState(true);
- const [showHidden, setShowHidden] = useState(false);
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- onSave({
- name: name.trim(),
- external_path: path.trim(),
- readonly,
- show_hidden: showHidden,
- });
- };
- return (
- <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
- <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary">
- <div className="p-4 border-b border-bambu-dark-tertiary">
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <FolderSymlink className="w-5 h-5 text-bambu-green" />
- {t('fileManager.linkExternalFolder')}
- </h2>
- <p className="text-sm text-bambu-gray mt-1">{t('fileManager.linkExternalFolderDescription')}</p>
- </div>
- <form onSubmit={handleSubmit} className="p-4 space-y-4">
- <div>
- <label className="block text-sm font-medium text-white mb-1">
- {t('fileManager.folderName')}
- </label>
- <input
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- 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"
- placeholder={t('fileManager.externalFolderNamePlaceholder')}
- autoFocus
- required
- />
- </div>
- <div>
- <label className="block text-sm font-medium text-white mb-1">
- {t('fileManager.externalPath')}
- </label>
- <input
- type="text"
- value={path}
- onChange={(e) => setPath(e.target.value)}
- 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"
- placeholder="/mnt/nas/3d-prints"
- required
- />
- <p className="text-xs text-bambu-gray mt-1">{t('fileManager.externalPathHelp')}</p>
- </div>
- <div className="space-y-2">
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={readonly}
- onChange={(e) => setReadonly(e.target.checked)}
- className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
- />
- <span className="text-sm text-white">{t('fileManager.readOnly')}</span>
- <span className="text-xs text-bambu-gray">({t('fileManager.readOnlyHelp')})</span>
- </label>
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={showHidden}
- onChange={(e) => setShowHidden(e.target.checked)}
- className="rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"
- />
- <span className="text-sm text-white">{t('fileManager.showHiddenFiles')}</span>
- </label>
- </div>
- <div className="flex justify-end gap-2 pt-2">
- <Button type="button" variant="secondary" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button type="submit" disabled={!name.trim() || !path.trim() || isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('fileManager.linkFolder')}
- </Button>
- </div>
- </form>
- </div>
- </div>
- );
- }
- // FAT32/exFAT-illegal chars rejected by Bambu Studio (#1540). Mirrors the
- // backend validator in backend/app/utils/filename.py — keep in sync.
- const INVALID_FILENAME_CHARS = '<>:"/\\|?*';
- function findInvalidFilenameChar(name: string): string | null {
- for (const ch of name) {
- if (INVALID_FILENAME_CHARS.includes(ch)) return ch;
- if (ch.charCodeAt(0) < 0x20) return ch;
- }
- return null;
- }
- // Rename Modal
- interface RenameModalProps {
- type: 'file' | 'folder';
- currentName: string;
- onClose: () => void;
- onSave: (newName: string) => void;
- isLoading: boolean;
- t: TFunction;
- }
- function RenameModal({ type, currentName, onClose, onSave, isLoading, t }: RenameModalProps) {
- // For files, separate the extension so users can only edit the base name
- // Handle compound extensions like .gcode.3mf
- const fileExtension = type === 'file' ? (currentName.match(/(\.gcode\.3mf|\.3mf|\.gcode)$/i)?.[1] ?? '') : '';
- const baseName = type === 'file' && fileExtension ? currentName.slice(0, -fileExtension.length) : currentName;
- const [name, setName] = useState(baseName);
- const invalidChar = type === 'file' ? findInvalidFilenameChar(name) : null;
- const filenameError = invalidChar
- ? t('fileManager.invalidFilenameChar', { char: invalidChar })
- : null;
- const handleSubmit = (e: React.FormEvent) => {
- e.preventDefault();
- if (filenameError) return;
- const fullName = type === 'file' ? name.trim() + fileExtension : name.trim();
- if (name.trim() && fullName !== currentName) {
- onSave(fullName);
- }
- };
- return (
- <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
- <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
- <div className="p-4 border-b border-bambu-dark-tertiary">
- <h2 className="text-lg font-semibold text-white">{type === 'file' ? t('fileManager.renameFile') : t('fileManager.renameFolder')}</h2>
- </div>
- <form onSubmit={handleSubmit} className="p-4 space-y-4">
- <div>
- <label className="block text-sm font-medium text-white mb-1">
- {t('common.name')}
- </label>
- <div className={`flex items-center bg-bambu-dark border rounded focus-within:border-bambu-green ${filenameError ? 'border-red-500' : 'border-bambu-dark-tertiary'}`}>
- <input
- type="text"
- value={name}
- onChange={(e) => setName(e.target.value)}
- className="flex-1 bg-transparent px-3 py-2 text-white placeholder-bambu-gray focus:outline-none min-w-0"
- autoFocus
- required
- />
- {fileExtension && (
- <span className="pr-3 text-bambu-gray text-sm select-none whitespace-nowrap">{fileExtension}</span>
- )}
- </div>
- {filenameError && (
- <p className="mt-1 text-xs text-red-700 dark:text-red-400">{filenameError}</p>
- )}
- </div>
- <div className="flex justify-end gap-2 pt-2">
- <Button type="button" variant="secondary" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button type="submit" disabled={!name.trim() || name.trim() === baseName || !!filenameError || isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.rename')}
- </Button>
- </div>
- </form>
- </div>
- </div>
- );
- }
- // Move Files Modal
- interface MoveFilesModalProps {
- folders: LibraryFolderTree[];
- selectedFiles: number[];
- currentFolderId: number | null;
- onClose: () => void;
- onMove: (folderId: number | null) => void;
- isLoading: boolean;
- t: TFunction;
- }
- function MoveFilesModal({ folders, selectedFiles, currentFolderId, onClose, onMove, isLoading, t }: MoveFilesModalProps) {
- const [targetFolder, setTargetFolder] = useState<number | null>(null);
- // can_write: a library:read_own user moves files only into their own and
- // shared folders (#3201); the rest stay listed so the tree keeps its shape.
- type MoveTarget = { id: number | null; name: string; depth: number; canWrite: boolean };
- const flattenFolders = (items: LibraryFolderTree[], depth = 0): MoveTarget[] => {
- const result: MoveTarget[] = [];
- for (const item of items) {
- result.push({ id: item.id, name: item.name, depth, canWrite: item.can_write !== false });
- if (item.children.length > 0) {
- result.push(...flattenFolders(item.children, depth + 1));
- }
- }
- return result;
- };
- const flatFolders: MoveTarget[] = [{ id: null, name: t('fileManager.rootNoFolder'), depth: 0, canWrite: true }, ...flattenFolders(folders)];
- return (
- <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
- <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary">
- <div className="p-4 border-b border-bambu-dark-tertiary">
- <h2 className="text-lg font-semibold text-white">{t('fileManager.moveFiles', { count: selectedFiles.length })}</h2>
- </div>
- <div className="p-4 space-y-4">
- <div className="max-h-64 overflow-y-auto space-y-1">
- {flatFolders.map((folder) => (
- <button
- key={folder.id ?? 'root'}
- onClick={() => setTargetFolder(folder.id)}
- disabled={folder.id === currentFolderId || !folder.canWrite}
- title={!folder.canWrite ? t('fileManager.folderNotWritable') : undefined}
- className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
- targetFolder === folder.id
- ? 'bg-bambu-green/20 text-bambu-green'
- : folder.id === currentFolderId || !folder.canWrite
- ? 'opacity-50 cursor-not-allowed text-bambu-gray'
- : 'hover:bg-bambu-dark text-white'
- }`}
- style={{ paddingLeft: `${12 + folder.depth * 16}px` }}
- >
- <FolderOpen className="w-4 h-4" />
- {folder.name}
- {folder.id === currentFolderId && <span className="text-xs text-bambu-gray ml-auto">({t('fileManager.current')})</span>}
- </button>
- ))}
- </div>
- <div className="flex justify-end gap-2 pt-2">
- <Button type="button" variant="secondary" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button onClick={() => onMove(targetFolder)} disabled={isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('common.move')}
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
- }
- // Link Folder Modal
- interface LinkFolderModalProps {
- folder: LibraryFolderTree;
- onClose: () => void;
- onLink: (update: LibraryFolderUpdate) => void;
- isLoading: boolean;
- t: TFunction;
- }
- function LinkFolderModal({ folder, onClose, onLink, isLoading, t }: LinkFolderModalProps) {
- const [linkType, setLinkType] = useState<'project' | 'archive'>('project');
- const [selectedId, setSelectedId] = useState<number | null>(
- folder.project_id || folder.archive_id || null
- );
- // Initialize linkType based on existing link
- useState(() => {
- if (folder.archive_id) setLinkType('archive');
- });
- // Archived projects are left out, bar the one this folder is already linked
- // to -- dropping that one would leave the folder looking unlinked while the
- // link is still there (#2888).
- const { data: projects } = useQuery({
- queryKey: ['projects'],
- queryFn: () => api.getProjects(),
- select: (rows) =>
- assignableProjects([...rows].sort((a, b) => a.name.localeCompare(b.name)), folder.project_id),
- });
- const { data: archives } = useQuery({
- queryKey: ['archives-for-link'],
- queryFn: () => api.getArchives(undefined, undefined, 100),
- });
- const handleSave = () => {
- if (linkType === 'project') {
- onLink({
- project_id: selectedId,
- archive_id: 0, // Unlink archive
- });
- } else {
- onLink({
- project_id: 0, // Unlink project
- archive_id: selectedId,
- });
- }
- };
- const handleUnlink = () => {
- onLink({
- project_id: 0,
- archive_id: 0,
- });
- };
- const isLinked = folder.project_id || folder.archive_id;
- return (
- <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
- <div className="bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary">
- <div className="p-4 border-b border-bambu-dark-tertiary flex items-center justify-between">
- <h2 className="text-lg font-semibold text-white flex items-center gap-2">
- <Link2 className="w-5 h-5 text-bambu-green" />
- {t('fileManager.linkFolder')}
- </h2>
- <button onClick={onClose} className="p-1 hover:bg-bambu-dark rounded">
- <X className="w-5 h-5 text-bambu-gray" />
- </button>
- </div>
- <div className="p-4 space-y-4">
- <p className="text-sm text-bambu-gray">
- {t('fileManager.linkFolderDescription', { name: folder.name })}
- </p>
- {/* Link type selector */}
- <div className="flex gap-2">
- <button
- onClick={() => { setLinkType('project'); setSelectedId(null); }}
- className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
- linkType === 'project'
- ? 'border-bambu-green bg-bambu-green/10 text-bambu-green'
- : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white'
- }`}
- >
- <Briefcase className="w-4 h-4" />
- {t('fileManager.project')}
- </button>
- <button
- onClick={() => { setLinkType('archive'); setSelectedId(null); }}
- className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${
- linkType === 'archive'
- ? 'border-bambu-green bg-bambu-green/10 text-bambu-green'
- : 'border-bambu-dark-tertiary text-bambu-gray hover:text-white'
- }`}
- >
- <ArchiveIcon className="w-4 h-4" />
- {t('fileManager.archive')}
- </button>
- </div>
- {/* Selection list */}
- <div className="max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2">
- {linkType === 'project' ? (
- projects && projects.length > 0 ? (
- projects.map((project) => (
- <button
- key={project.id}
- onClick={() => setSelectedId(project.id)}
- className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
- selectedId === project.id
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'hover:bg-bambu-dark-tertiary text-white'
- }`}
- >
- <div
- className="w-3 h-3 rounded-full flex-shrink-0"
- style={{ backgroundColor: project.color || '#00ae42' }}
- />
- <span className="truncate">{project.name}</span>
- </button>
- ))
- ) : (
- <p className="text-sm text-bambu-gray text-center py-4">{t('fileManager.noProjectsFound')}</p>
- )
- ) : (
- archives && archives.length > 0 ? (
- archives.map((archive: Archive) => (
- <button
- key={archive.id}
- onClick={() => setSelectedId(archive.id)}
- className={`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${
- selectedId === archive.id
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'hover:bg-bambu-dark-tertiary text-white'
- }`}
- >
- <FileBox className="w-4 h-4 text-bambu-gray flex-shrink-0" />
- <span className="truncate">{archive.print_name || archive.filename}</span>
- </button>
- ))
- ) : (
- <p className="text-sm text-bambu-gray text-center py-4">{t('fileManager.noArchivesFound')}</p>
- )
- )}
- </div>
- </div>
- <div className="p-4 border-t border-bambu-dark-tertiary flex justify-between">
- {isLinked && (
- <Button variant="danger" onClick={handleUnlink} disabled={isLoading}>
- <Unlink className="w-4 h-4 mr-2" />
- {t('fileManager.unlink')}
- </Button>
- )}
- <div className={`flex gap-2 ${!isLinked ? 'ml-auto' : ''}`}>
- <Button variant="secondary" onClick={onClose}>
- {t('common.cancel')}
- </Button>
- <Button onClick={handleSave} disabled={!selectedId || isLoading}>
- {isLoading ? <Loader2 className="w-4 h-4 animate-spin" /> : t('fileManager.link')}
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
- }
- // Folder Tree Item
- interface FolderTreeItemProps {
- folder: LibraryFolderTree;
- selectedFolderId: number | null;
- onSelect: (id: number | null) => void;
- onDelete: (id: number) => void;
- onLink: (folder: LibraryFolderTree) => void;
- onRename: (folder: LibraryFolderTree) => void;
- onToggleShared?: (folder: LibraryFolderTree) => void;
- depth?: number;
- wrapNames?: boolean;
- defaultExpanded?: boolean;
- showModified?: boolean;
- hasPermission: (permission: Permission) => boolean;
- t: TFunction;
- }
- // Folder kebab: Rename / Link / Delete. Shared by the tree sidebar and the
- // columns view so both offer exactly the same entries and permission gates.
- // Rendered through `ContextMenu` (position: fixed, anchored to the button)
- // rather than an absolutely positioned dropdown, because both hosts scroll —
- // a dropdown inside an overflow-y-auto column gets clipped at its edge.
- interface FolderActionsMenuProps {
- folder: LibraryFolderTree;
- onDelete: (id: number) => void;
- onLink: (folder: LibraryFolderTree) => void;
- onRename: (folder: LibraryFolderTree) => void;
- // Share with every library:read_own user, or stop (#3201). library:update_all only.
- onToggleShared?: (folder: LibraryFolderTree) => void;
- hasPermission: (permission: Permission) => boolean;
- // Hide the kebab until its `group` row is hovered or focused — only for
- // pointers that can hover (#2865). The menu is a DOM descendant, so the
- // wrapper stays opaque while it is open: browsers that don't focus a button
- // on click (Safari) would otherwise fade the open menu out with the row.
- revealOnHover?: boolean;
- tabIndex?: number;
- t: TFunction;
- }
- function FolderActionsMenu({ folder, onDelete, onLink, onRename, onToggleShared, hasPermission, revealOnHover = false, tabIndex, t }: FolderActionsMenuProps) {
- const [menuAnchor, setMenuAnchor] = useState<{ x: number; y: number } | null>(null);
- const rootRef = useRef<HTMLDivElement>(null);
- const buttonRef = useRef<HTMLButtonElement>(null);
- const closeMenu = () => {
- setMenuAnchor(null);
- // A menu entry activated by Enter unmounts with the menu; hand focus back
- // to the kebab rather than letting it drop to <body>. Focus that already
- // moved elsewhere (click-outside, the columns pane) is left alone.
- if (rootRef.current?.contains(document.activeElement)) buttonRef.current?.focus();
- };
- const hasChildren = folder.children.length > 0;
- const isLinked = folder.project_id || folder.archive_id;
- const isExternal = folder.is_external;
- // The backend says what this user may do with the folder (#3201): delete
- // their own folder when everything in it is theirs, or an ownerless empty
- // one (#1781). The fallbacks cover a response without those fields.
- const canDeleteFolder =
- folder.can_delete ??
- (hasPermission('library:delete_all') ||
- (hasPermission('library:delete_own') && folder.file_count === 0 && !hasChildren && !isExternal && !isLinked));
- const deleteDisabledTooltip = canDeleteFolder
- ? undefined
- : hasPermission('library:delete_own') && !isExternal && !isLinked
- ? t('fileManager.onlyOwnFoldersDeletable')
- : t('fileManager.noPermissionDeleteFolder');
- const canRename = folder.can_rename ?? hasPermission('library:update_all');
- const canLink = hasPermission('library:update_all');
- const items: ContextMenuItem[] = [
- {
- label: t('common.rename'),
- icon: <Pencil className="w-3.5 h-3.5" />,
- onClick: () => onRename(folder),
- disabled: !canRename,
- title: !canRename ? t('fileManager.noPermissionRenameFolder') : undefined,
- },
- {
- label: isLinked ? t('fileManager.changeLink') : t('fileManager.linkTo'),
- icon: <Link2 className="w-3.5 h-3.5" />,
- onClick: () => onLink(folder),
- disabled: !canLink,
- title: !canLink ? t('fileManager.noPermissionLinkFolder') : undefined,
- },
- ...(onToggleShared && canLink
- ? [
- {
- label: folder.shared ? t('fileManager.unshareFolder') : t('fileManager.shareFolder'),
- icon: <Users className="w-3.5 h-3.5" />,
- onClick: () => onToggleShared(folder),
- title: t('fileManager.shareFolderHint'),
- },
- ]
- : []),
- {
- label: t('common.delete'),
- icon: <Trash2 className="w-3.5 h-3.5" />,
- onClick: () => onDelete(folder.id),
- danger: true,
- disabled: !canDeleteFolder,
- title: deleteDisabledTooltip,
- },
- ];
- return (
- <div
- ref={rootRef}
- className={`relative flex-shrink-0 flex items-center transition-opacity ${
- revealOnHover && !menuAnchor ? 'can-hover:opacity-0 group-hover:opacity-100 group-focus-within:opacity-100' : ''
- }`}
- data-folder-actions
- onClick={(e) => e.stopPropagation()}
- onKeyDown={(e) => {
- // The menu has no arrow-key navigation; Up/Down mean "leave it".
- if (menuAnchor && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) closeMenu();
- }}
- >
- <button
- ref={buttonRef}
- type="button"
- tabIndex={tabIndex}
- onClick={(e) => {
- if (menuAnchor) {
- closeMenu();
- return;
- }
- const rect = e.currentTarget.getBoundingClientRect();
- setMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
- }}
- className="p-1 rounded hover:bg-bambu-dark-tertiary"
- title={t('common.actions')}
- >
- <MoreVertical className="w-3.5 h-3.5 text-bambu-gray" />
- </button>
- {menuAnchor && (
- <ContextMenu x={menuAnchor.x} y={menuAnchor.y} items={items} onClose={closeMenu} anchorRef={buttonRef} />
- )}
- </div>
- );
- }
- function FolderTreeItem({ folder, selectedFolderId, onSelect, onDelete, onLink, onRename, onToggleShared, depth = 0, wrapNames = false, defaultExpanded = true, showModified = false, hasPermission, t }: FolderTreeItemProps) {
- const [expanded, setExpanded] = useState(defaultExpanded);
- const hasChildren = folder.children.length > 0;
- const isLinked = folder.project_id || folder.archive_id;
- const isExternal = folder.is_external;
- return (
- <div>
- <div
- className={`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${
- selectedFolderId === folder.id
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'hover:bg-bambu-dark text-white'
- }`}
- style={{ paddingLeft: `${8 + depth * 12}px` }}
- onClick={() => onSelect(folder.id)}
- >
- {hasChildren ? (
- <button
- onClick={(e) => {
- e.stopPropagation();
- setExpanded(!expanded);
- }}
- className="p-0.5 hover:bg-bambu-dark-tertiary rounded"
- >
- <ChevronRight className={`w-3.5 h-3.5 transition-transform ${expanded ? 'rotate-90' : ''}`} />
- </button>
- ) : (
- <div className="w-4.5" />
- )}
- {isExternal ? (
- <FolderSymlink className="w-4 h-4 text-purple-600 dark:text-purple-400 flex-shrink-0" />
- ) : (
- <FolderOpen className="w-4 h-4 text-bambu-green flex-shrink-0" />
- )}
- <div className="flex-1 min-w-0">
- <span className={`block text-sm ${wrapNames ? 'break-all' : 'truncate'}`} title={folder.name}>{folder.name}</span>
- {/* #2680 follow-up: the same toolbar toggle that shows dates on file
- cards also shows them here. This is `latest_activity_at` — the
- newest timestamp among the folder itself, its files and its
- subfolders (the value "sort by recent activity" orders on) — not
- the folder's own on-disk mtime, hence the distinct label. */}
- {showModified && folder.latest_activity_at && (
- <span className="mt-0.5 flex items-center gap-1 text-xs text-bambu-gray" title={t('fileManager.lastActivity')}>
- <CalendarClock className="w-3 h-3 flex-shrink-0" />
- <span className="truncate">{formatDate(folder.latest_activity_at)}</span>
- </span>
- )}
- </div>
- {/* Link indicator - clickable to change link */}
- {isLinked && (
- <button
- onClick={(e) => { e.stopPropagation(); onLink(folder); }}
- 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"
- title={`${folder.project_name ? `Project: ${folder.project_name}` : `Archive: ${folder.archive_name}`} (click to change)`}
- >
- <Link2 className="w-3 h-3" />
- {folder.project_name ? (
- <Briefcase className="w-3 h-3" />
- ) : (
- <ArchiveIcon className="w-3 h-3" />
- )}
- </button>
- )}
- {folder.shared && (
- <span title={t('fileManager.sharedFolder')}>
- <Users className="w-3 h-3 text-bambu-gray flex-shrink-0" />
- </span>
- )}
- {/* Read-only indicator for external folders */}
- {isExternal && folder.external_readonly && (
- <span title={t('fileManager.readOnly')}>
- <Lock className="w-3 h-3 text-amber-600 dark:text-amber-400 flex-shrink-0" />
- </span>
- )}
- {folder.file_count > 0 && (
- <span className="flex-shrink-0 text-xs text-bambu-gray">{folder.file_count}</span>
- )}
- {/* Quick link button - always visible for unlinked folders */}
- {!isLinked && !isExternal && (
- <button
- onClick={(e) => { e.stopPropagation(); onLink(folder); }}
- className="flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary"
- title={t('fileManager.linkToProjectOrArchive')}
- >
- <Link2 className="w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green" />
- </button>
- )}
- <FolderActionsMenu
- folder={folder}
- onDelete={onDelete}
- onLink={onLink}
- onRename={onRename}
- onToggleShared={onToggleShared}
- hasPermission={hasPermission}
- revealOnHover={!wrapNames}
- t={t}
- />
- </div>
- {hasChildren && expanded && (
- <div>
- {folder.children.map((child) => (
- <FolderTreeItem
- key={child.id}
- folder={child}
- selectedFolderId={selectedFolderId}
- onSelect={onSelect}
- onDelete={onDelete}
- onLink={onLink}
- onRename={onRename}
- onToggleShared={onToggleShared}
- depth={depth + 1}
- wrapNames={wrapNames}
- defaultExpanded={defaultExpanded}
- showModified={showModified}
- hasPermission={hasPermission}
- t={t}
- />
- ))}
- </div>
- )}
- </div>
- );
- }
- // File Card
- // The mark on a file a ?highlight= link points at; the Archives page's colour.
- const HIGHLIGHT_CARD_STYLE = { outline: '4px solid #facc15', outlineOffset: '2px' } as const;
- const HIGHLIGHT_ROW_STYLE = { outline: '2px solid #facc15', outlineOffset: '-2px' } as const;
- interface FileCardProps {
- file: LibraryFileListItem;
- isSelected: boolean;
- /** The file a ?highlight= link points at, marked for a few seconds. */
- isHighlighted?: boolean;
- onSelect: (id: number) => void;
- onDelete: (id: number) => void;
- onDownload: (id: number) => void;
- onPrint?: (file: LibraryFileListItem) => void;
- onSlice?: (file: LibraryFileListItem) => void;
- onOpenInSlicer?: (file: LibraryFileListItem) => void;
- onRunPipeline?: (file: LibraryFileListItem) => void;
- useSlicerApi?: boolean;
- // Which slicer the desktop handoff targets. Decides whether an STL or STEP
- // gets a Slice action at all: Bambu Studio's protocol handler takes 3MF only
- // (#3029), so offering one there would only ever fail.
- desktopSlicer: SlicerType;
- canSlice?: boolean;
- onPreview?: (file: LibraryFileListItem) => void;
- onRename?: (file: LibraryFileListItem) => void;
- onDetails?: (file: LibraryFileListItem) => void;
- onGenerateThumbnail?: (file: LibraryFileListItem) => void;
- onTagClick?: (tagId: number) => void;
- thumbnailVersion?: number;
- hasPermission: (permission: Permission) => boolean;
- canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
- authEnabled: boolean;
- showModified: boolean;
- t: TFunction;
- }
- 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) {
- // Viewport coordinates rather than a flag, because the menu is rendered by
- // `ContextMenu` at `position: fixed` and anchored to the button (#2846). The
- // card it belongs to is only ~270px tall for a bare STL, which is shorter
- // than the seven-entry menu, so a menu positioned inside the card had its
- // top entry -- Slice -- cut off. The archive card menu works the same way.
- const [menuAnchor, setMenuAnchor] = useState<{ x: number; y: number } | null>(null);
- const canPreview3d = hasPermission('library:read');
- const canRename = canModify('library', 'update', file.created_by_id);
- const canDelete = canModify('library', 'delete', file.created_by_id);
- const menuItems: ContextMenuItem[] = [];
- if (onPrint && isSlicedLibraryFile(file)) {
- menuItems.push({
- label: t('common.print'),
- // The action stays visually distinct now that the menu component styles
- // its own labels; only the icon carries the accent.
- icon: <Printer className="w-4 h-4 text-bambu-green" />,
- onClick: () => onPrint(file),
- disabled: !hasPermission('queue:create'),
- title: !hasPermission('queue:create') ? t('fileManager.noPermissionAddToQueue') : undefined,
- });
- }
- if (isSliceableLibraryFile(file, !!useSlicerApi, desktopSlicer) && (useSlicerApi ? onSlice : onOpenInSlicer)) {
- menuItems.push({
- label: t('slice.action'),
- icon: useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />,
- onClick: () => { if (useSlicerApi) onSlice?.(file); else onOpenInSlicer?.(file); },
- disabled: !canSlice,
- title: !canSlice ? (useSlicerApi ? t('fileManager.noPermissionSlice') : t('fileManager.noPermissionDownload')) : undefined,
- });
- }
- if (onRunPipeline && useSlicerApi && isSliceableLibraryFile(file, true, desktopSlicer)) {
- menuItems.push({
- label: t('library.runWithPipeline.actionLabel'),
- icon: <Play className="w-4 h-4" />,
- onClick: () => onRunPipeline(file),
- disabled: !hasPermission('pipelines:run'),
- title: !hasPermission('pipelines:run') ? t('library.runWithPipeline.noPermission') : undefined,
- });
- }
- if (onPreview && isPreviewableLibraryFile(file)) {
- const modelPreview = isModelPreview(file);
- menuItems.push({
- label: modelPreview ? t('fileManager.preview3d') : t('fileManager.preview.open'),
- icon: modelPreview ? <Box className="w-4 h-4" /> : documentPreviewIcon(file.file_type),
- onClick: () => onPreview(file),
- disabled: !canPreview3d,
- title: !canPreview3d ? t('fileManager.noPermissionPreview') : undefined,
- });
- }
- menuItems.push({
- label: t('common.download'),
- icon: <Download className="w-4 h-4" />,
- onClick: () => onDownload(file.id),
- disabled: !hasPermission('library:read'),
- title: !hasPermission('library:read') ? t('fileManager.noPermissionDownload') : undefined,
- });
- if (onRename) {
- menuItems.push({
- label: t('common.rename'),
- icon: <Pencil className="w-4 h-4" />,
- onClick: () => onRename(file),
- disabled: !canRename,
- title: !canRename ? t('fileManager.noPermissionRenameFile') : undefined,
- });
- }
- if (onDetails) {
- menuItems.push({
- label: t('fileManager.details.title'),
- icon: <Info className="w-4 h-4" />,
- onClick: () => onDetails(file),
- disabled: !canPreview3d,
- title: !canPreview3d ? t('fileManager.noPermissionPreview') : undefined,
- });
- }
- if (file.external_url) {
- menuItems.push({
- label: t('fileManager.details.openLink'),
- icon: <Globe className="w-4 h-4" />,
- // The URL is stored by whoever owns the file, so the opened page must
- // not get a handle on this window (#3077).
- onClick: () => window.open(file.external_url!, '_blank', 'noopener,noreferrer'),
- });
- }
- if (onGenerateThumbnail && hasServerThumbnail(file.file_type)) {
- menuItems.push({
- label: t('fileManager.generateThumbnail'),
- icon: <Image className="w-4 h-4" />,
- onClick: () => onGenerateThumbnail(file),
- disabled: !canRename,
- title: !canRename ? t('fileManager.noPermissionGenerateThumbnail') : undefined,
- });
- }
- menuItems.push({
- label: t('common.delete'),
- icon: <Trash2 className="w-4 h-4" />,
- onClick: () => onDelete(file.id),
- danger: true,
- disabled: !canDelete,
- title: !canDelete ? t('fileManager.noPermissionDeleteFile') : undefined,
- });
- return (
- <div
- data-file-id={file.id}
- style={isHighlighted ? HIGHLIGHT_CARD_STYLE : undefined}
- className={`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer ${
- isSelected
- ? 'border-bambu-green ring-1 ring-bambu-green'
- : 'border-bambu-dark-tertiary hover:border-bambu-green/50'
- }`}
- onClick={() => onSelect(file.id)}
- // Double-click opens the preview (#2976). The two clicks that precede it
- // toggle the selection twice, so the selection is left as it was.
- onDoubleClick={() => onPreview?.(file)}
- >
- {/* Thumbnail */}
- <div className="aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden rounded-t-lg">
- {file.thumbnail_path ? (
- <img
- src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersion ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersion}`) : ''}`}
- loading="lazy"
- alt={file.filename}
- className="w-full h-full object-cover"
- />
- ) : (
- <FileTypePlaceholderIcon fileType={file.file_type} className="w-12 h-12 text-bambu-gray/30" />
- )}
- {/* File type badge */}
- <div className={`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${
- file.file_type === '3mf' ? 'bg-bambu-green/90 text-white'
- // Sliced output — share the gcode blue so users see at a glance
- // that the file is already sliced and ready to print (#1543).
- : file.file_type === 'gcode' || file.file_type === 'gcode.3mf' ? 'bg-blue-500/90 text-white'
- : file.file_type === 'stl' ? 'bg-purple-500/90 text-white'
- : isStepType(file.file_type) ? 'bg-amber-500/90 text-white'
- : file.file_type === 'pdf' ? 'bg-red-500/90 text-white'
- : isSpreadsheetType(file.file_type) ? 'bg-teal-500/90 text-white'
- : 'bg-bambu-gray/90 text-white'
- }`}>
- {file.file_type.toUpperCase()}
- </div>
- </div>
- {/* Info */}
- <div className="p-3">
- <h3 className="text-sm font-medium text-white truncate" title={file.print_name || file.filename}>
- {file.print_name || file.filename}
- </h3>
- <div className="flex items-center gap-3 mt-1 text-xs text-bambu-gray">
- <span>{formatFileSize(file.file_size)}</span>
- {file.print_time_seconds && (
- <span className="flex items-center gap-1">
- <Clock className="w-3 h-3" />
- {formatDuration(file.print_time_seconds)}
- </span>
- )}
- </div>
- {file.sliced_for_model && (
- <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1">
- <Printer className="w-3 h-3" />
- {file.sliced_for_model}
- </div>
- )}
- {/* Counts the whole group, including members in other folders (#671 /
- #2570) — printing this file will offer all of them. */}
- {(file.variant_count ?? 0) > 1 && (
- <div className="mt-1 text-xs text-bambu-green flex items-center gap-1">
- <Layers className="w-3 h-3" />
- {t('fileManager.variants.badge', { count: file.variant_count })}
- </div>
- )}
- {file.print_count > 0 && (
- <div className="mt-1 text-xs text-bambu-green">
- {t('fileManager.printedCount', { count: file.print_count })}
- </div>
- )}
- {/* Metadata indicators (#3077): link, notes, photos. The link opens in
- a new tab like the archive card's globe; the others open Details. */}
- {(file.external_url || file.has_notes || (file.photo_count ?? 0) > 0) && (
- <div className="mt-1 flex items-center gap-2 text-xs text-bambu-gray" {...stopRowActivation}>
- {file.external_url && (
- <a
- href={file.external_url}
- target="_blank"
- rel="noopener noreferrer"
- className="p-0.5 rounded hover:text-bambu-green"
- title={t('fileManager.details.openLink')}
- aria-label={t('fileManager.details.openLink')}
- >
- <Globe className="w-3.5 h-3.5" />
- </a>
- )}
- {file.has_notes && (
- <button
- type="button"
- onClick={() => onDetails?.(file)}
- className="p-0.5 rounded hover:text-bambu-green"
- title={t('fileManager.details.hasNotes')}
- aria-label={t('fileManager.details.hasNotes')}
- >
- <StickyNote className="w-3.5 h-3.5" />
- </button>
- )}
- {(file.photo_count ?? 0) > 0 && (
- <button
- type="button"
- onClick={() => onDetails?.(file)}
- className="flex items-center gap-0.5 p-0.5 rounded hover:text-bambu-green"
- title={t('fileManager.details.photoCount', { count: file.photo_count })}
- aria-label={t('fileManager.details.photoCount', { count: file.photo_count })}
- >
- <Camera className="w-3.5 h-3.5" />
- <span>{file.photo_count}</span>
- </button>
- )}
- </div>
- )}
- {authEnabled && file.created_by_username && (
- <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1">
- <User className="w-3 h-3" />
- {file.created_by_username}
- </div>
- )}
- {/* #2680: last-modified date, toggled from the toolbar. Uses the real
- on-disk mtime when known, else the DB created_at. */}
- {showModified && (
- <div className="mt-1 text-xs text-bambu-gray flex items-center gap-1" title={t('fileManager.lastModified')}>
- <CalendarClock className="w-3 h-3" />
- {formatDate(file.fs_modified_at ?? file.created_at)}
- </div>
- )}
- {(file.tags?.length ?? 0) > 0 && (
- <div className="mt-2 flex flex-wrap gap-1" {...stopRowActivation}>
- {file.tags!.map((tg) => (
- <button
- key={tg.id}
- type="button"
- onClick={() => onTagClick?.(tg.id)}
- 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"
- title={tg.name}
- >
- <TagIcon className="w-2.5 h-2.5 flex-shrink-0" />
- <span className="truncate">{tg.name}</span>
- </button>
- ))}
- </div>
- )}
- </div>
- {/* Actions - hover-revealed with a mouse, always there without one (#2865) */}
- <div className="absolute bottom-2 right-2 transition-opacity can-hover:opacity-0 group-hover:opacity-100 group-focus-within:opacity-100" {...stopRowActivation}>
- <button
- onClick={(e) => {
- // No open/close toggle: the menu's own outside-mousedown handler
- // has already dismissed it by the time this click lands.
- const rect = e.currentTarget.getBoundingClientRect();
- setMenuAnchor({ x: rect.left, y: rect.bottom + 4 });
- }}
- className="p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary"
- >
- <MoreVertical className="w-4 h-4 text-bambu-gray" />
- </button>
- {menuAnchor && (
- <ContextMenu x={menuAnchor.x} y={menuAnchor.y} items={menuItems} onClose={() => setMenuAnchor(null)} />
- )}
- </div>
- {/* Selection checkbox - hover-revealed with a mouse, always there without one (#2865) */}
- <div className={`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${
- isSelected
- ? 'bg-bambu-green border-bambu-green'
- : 'border-white/30 bg-black/30 can-hover:opacity-0 group-hover:opacity-100 group-focus-within:opacity-100'
- }`}>
- {isSelected && <div className="w-2 h-2 bg-white rounded-sm" />}
- </div>
- </div>
- );
- }
- // Per-file icon strip: Print, Slice, Run with pipeline, Preview, Download,
- // Details, Rename, Generate thumbnail, Delete. The list row and the columns view render
- // the same strip so the two stay identical in order, icons and gating; the
- // grid card packs the same actions into its kebab menu instead.
- interface FileActionStripProps {
- file: LibraryFileListItem;
- onPrint: (file: LibraryFileListItem) => void;
- onSlice: (file: LibraryFileListItem) => void;
- onOpenInSlicer: (file: LibraryFileListItem) => void;
- onRunPipeline: (file: LibraryFileListItem) => void;
- useSlicerApi: boolean;
- desktopSlicer: SlicerType;
- canSlice: boolean;
- onPreview: (file: LibraryFileListItem) => void;
- onDetails: (file: LibraryFileListItem) => void;
- onDownload: (id: number) => void;
- onRename: (file: LibraryFileListItem) => void;
- onGenerateThumbnail: (file: LibraryFileListItem) => void;
- thumbnailPending: boolean;
- onDelete: (id: number) => void;
- hasPermission: (permission: Permission) => boolean;
- canModify: (resource: 'queue' | 'archives' | 'library', action: 'update' | 'delete' | 'reprint', createdById: number | null | undefined) => boolean;
- // Roving tabindex for the columns view: only the focused row's buttons take
- // part in the Tab order, so Tab from the pane lands on that row's actions.
- tabIndex?: number;
- t: TFunction;
- }
- function FileActionStrip({ file, onPrint, onSlice, onOpenInSlicer, onRunPipeline, useSlicerApi, desktopSlicer, canSlice, onPreview, onDetails, onDownload, onRename, onGenerateThumbnail, thumbnailPending, onDelete, hasPermission, canModify, tabIndex, t }: FileActionStripProps) {
- const canRename = canModify('library', 'update', file.created_by_id);
- const canDelete = canModify('library', 'delete', file.created_by_id);
- return (
- <div className="flex items-center gap-1" data-file-actions {...stopRowActivation}>
- {isSlicedLibraryFile(file) && (
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('queue:create') && onPrint(file)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('queue:create')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('queue:create') ? t('common.print') : t('fileManager.noPermissionAddToQueue')}
- disabled={!hasPermission('queue:create')}
- >
- <Printer className="w-4 h-4" />
- </button>
- )}
- {isSliceableLibraryFile(file, useSlicerApi, desktopSlicer) && (
- <button
- tabIndex={tabIndex}
- onClick={() => {
- if (!canSlice) return;
- (useSlicerApi ? onSlice : onOpenInSlicer)(file);
- }}
- className={`p-1.5 rounded transition-colors ${
- canSlice
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={canSlice ? t('slice.action') : (useSlicerApi ? t('fileManager.noPermissionSlice') : t('fileManager.noPermissionDownload'))}
- disabled={!canSlice}
- >
- {useSlicerApi ? <Cog className="w-4 h-4" /> : <ExternalLink className="w-4 h-4" />}
- </button>
- )}
- {useSlicerApi && isSliceableLibraryFile(file, true, desktopSlicer) && (
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('pipelines:run') && onRunPipeline(file)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('pipelines:run')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('pipelines:run') ? t('library.runWithPipeline.actionLabel') : t('library.runWithPipeline.noPermission')}
- disabled={!hasPermission('pipelines:run')}
- >
- <Play className="w-4 h-4" />
- </button>
- )}
- {isModelPreview(file) && (
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('library:read') && onPreview(file)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('library:read')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('library:read') ? t('fileManager.preview3d') : t('fileManager.noPermissionPreview')}
- disabled={!hasPermission('library:read')}
- >
- <Box className="w-4 h-4" />
- </button>
- )}
- {!isModelPreview(file) && isPreviewableLibraryFile(file) && (
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('library:read') && onPreview(file)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('library:read')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('library:read') ? t('fileManager.preview.open') : t('fileManager.noPermissionPreview')}
- disabled={!hasPermission('library:read')}
- >
- {documentPreviewIcon(file.file_type)}
- </button>
- )}
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('library:read') && onDownload(file.id)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('library:read')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-white'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('library:read') ? t('common.download') : t('fileManager.noPermissionDownload')}
- disabled={!hasPermission('library:read')}
- >
- <Download className="w-4 h-4" />
- </button>
- <button
- tabIndex={tabIndex}
- onClick={() => hasPermission('library:read') && onDetails(file)}
- className={`p-1.5 rounded transition-colors ${
- hasPermission('library:read')
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-white'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={hasPermission('library:read') ? t('fileManager.details.title') : t('fileManager.noPermissionPreview')}
- disabled={!hasPermission('library:read')}
- >
- <Info className="w-4 h-4" />
- </button>
- <button
- tabIndex={tabIndex}
- onClick={() => canRename && onRename(file)}
- className={`p-1.5 rounded transition-colors ${
- canRename
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-white'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={canRename ? t('common.rename') : t('fileManager.noPermissionRenameFile')}
- disabled={!canRename}
- >
- <Pencil className="w-4 h-4" />
- </button>
- {hasServerThumbnail(file.file_type) && (
- <button
- tabIndex={tabIndex}
- onClick={() => canRename && onGenerateThumbnail(file)}
- className={`p-1.5 rounded transition-colors ${
- canRename
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={canRename ? t('fileManager.generateThumbnail') : t('fileManager.noPermissionGenerateThumbnail')}
- disabled={thumbnailPending || !canRename}
- >
- <Image className="w-4 h-4" />
- </button>
- )}
- <button
- tabIndex={tabIndex}
- onClick={() => canDelete && onDelete(file.id)}
- className={`p-1.5 rounded transition-colors ${
- canDelete
- ? 'hover:bg-bambu-dark text-bambu-gray hover:text-red-700 dark:hover:text-red-400'
- : 'text-bambu-gray/50 cursor-not-allowed'
- }`}
- title={canDelete ? t('common.delete') : t('fileManager.noPermissionDeleteFile')}
- disabled={!canDelete}
- >
- <Trash2 className="w-4 h-4" />
- </button>
- </div>
- );
- }
- // One row of a Miller column's file list. Extracted so every column renders
- // its files with the same markup, action strip and double-click behaviour the
- // selected folder's pane has always used.
- interface ColumnFileRowProps {
- file: LibraryFileListItem;
- isSelected: boolean;
- isHighlighted?: boolean;
- isFocused: boolean;
- showModified: boolean;
- thumbnailVersion?: number;
- onSelect: (file: LibraryFileListItem) => void;
- onOpen: (file: LibraryFileListItem) => void;
- actionProps: Omit<FileActionStripProps, 'file' | 'tabIndex'>;
- t: TFunction;
- }
- function ColumnFileRow({ file, isSelected, isHighlighted, isFocused, showModified, thumbnailVersion, onSelect, onOpen, actionProps, t }: ColumnFileRowProps) {
- const thumbnailUrl = api.getLibraryFileThumbnailUrl(file.id);
- return (
- <div
- data-file-id={file.id}
- style={isHighlighted ? HIGHLIGHT_ROW_STYLE : undefined}
- onClick={() => onSelect(file)}
- onDoubleClick={() => onOpen(file)}
- className={`group flex items-center gap-3 px-3 py-2 cursor-pointer transition-colors ${
- isSelected ? 'bg-bambu-green/10' : 'hover:bg-bambu-dark'
- } ${isFocused ? 'ring-1 ring-inset ring-bambu-green/60' : ''}`}
- title={file.print_name || file.filename}
- >
- <div className={`w-4 h-4 rounded border-2 flex-shrink-0 flex items-center justify-center ${
- isSelected ? 'bg-bambu-green border-bambu-green' : 'border-bambu-gray/50'
- }`}>
- {isSelected && <div className="w-1.5 h-1.5 bg-white rounded-sm" />}
- </div>
- <div className="w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden flex items-center justify-center">
- {file.thumbnail_path ? (
- <img
- src={`${thumbnailUrl}${thumbnailVersion ? ((thumbnailUrl.includes('?') ? '&' : '?') + `v=${thumbnailVersion}`) : ''}`}
- loading="lazy"
- alt=""
- className="w-full h-full object-cover"
- />
- ) : (
- <FileTypePlaceholderIcon fileType={file.file_type} className="w-5 h-5 text-bambu-gray/50" />
- )}
- </div>
- <div className="flex-1 min-w-0">
- <div className="text-sm text-white truncate">{file.print_name || file.filename}</div>
- <div className="mt-0.5 flex items-center gap-2 text-xs text-bambu-gray">
- <span className={`px-1.5 py-px rounded font-medium ${fileTypeBadgeClass(file.file_type)}`}>
- {file.file_type.toUpperCase()}
- </span>
- <span>{formatFileSize(file.file_size)}</span>
- {file.print_count > 0 && <span>{file.print_count}x</span>}
- {showModified && (
- <span className="flex items-center gap-1 truncate" title={t('fileManager.lastModified')}>
- <CalendarClock className="w-3 h-3 flex-shrink-0" />
- {formatDate(file.fs_modified_at ?? file.created_at)}
- </span>
- )}
- </div>
- </div>
- {/* Same strip as the list row. Hover-revealed with a mouse, always there
- without one (#2865) and on the focused / selected row so the keyboard
- can reach it. */}
- <div
- className={`flex-shrink-0 transition-opacity ${
- isFocused || isSelected ? '' : 'can-hover:opacity-0 group-hover:opacity-100 group-focus-within:opacity-100'
- }`}
- >
- <FileActionStrip file={file} {...actionProps} tabIndex={isFocused ? 0 : -1} />
- </div>
- </div>
- );
- }
- export function FileManagerPage() {
- const { t } = useTranslation();
- const queryClient = useQueryClient();
- const { showToast } = useToast();
- const { hasPermission, hasAnyPermission, canModify, authEnabled } = useAuth();
- const [searchParams] = useSearchParams();
- const navigate = useNavigate();
- // Read folder ID from URL query parameter
- const folderIdFromUrl = searchParams.get('folder');
- const initialFolderId = folderIdFromUrl ? parseInt(folderIdFromUrl, 10) : null;
- // State
- const [selectedFolderId, setSelectedFolderId] = useState<number | null>(initialFolderId);
- // Which top-level pseudo-view the sidebar shows when no specific folder is
- // selected: "internal" = files in Bambuddy's managed storage, "external" =
- // combined view across every linked external folder (#1621). Per-folder
- // selection bypasses this (selectedFolderId !== null disables the filter).
- const [topLevelView, setTopLevelView] = useState<'internal' | 'external'>('internal');
- const [selectedFiles, setSelectedFiles] = useState<number[]>([]);
- const [showNewFolderModal, setShowNewFolderModal] = useState(false);
- const [showExternalFolderModal, setShowExternalFolderModal] = useState(false);
- const [showMoveModal, setShowMoveModal] = useState(false);
- const [showUploadModal, setShowUploadModal] = useState(false);
- const [droppedFiles, setDroppedFiles] = useState<File[]>([]);
- const [showPurgeModal, setShowPurgeModal] = useState(false);
- // Tag UI state (#1268). selectedTagIds is the AND-style filter applied to
- // the listing; setting it bypasses folder scoping on the server so
- // "every toy" works regardless of which folder is currently selected.
- const [showTagsModal, setShowTagsModal] = useState(false);
- const [showBulkTagsModal, setShowBulkTagsModal] = useState(false);
- const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
- const [linkFolder, setLinkFolder] = useState<LibraryFolderTree | null>(null);
- const [deleteConfirm, setDeleteConfirm] = useState<{ type: 'file' | 'folder' | 'bulk'; id: number; count?: number } | null>(null);
- const [printFile, setPrintFile] = useState<LibraryFileListItem | null>(null);
- const [sliceFile, setSliceFile] = useState<LibraryFileListItem | null>(null);
- const [showCombineModal, setShowCombineModal] = useState(false);
- // A file just built by "Combine to 3MF", handed straight to the SliceModal.
- const [sliceCombined, setSliceCombined] = useState<{ id: number; filename: string } | null>(null);
- // Slicer Pipelines (#1425 PR B) — file gets "Run with pipeline" action.
- const [runPipelineFile, setRunPipelineFile] = useState<LibraryFileListItem | null>(null);
- const [renameItem, setRenameItem] = useState<{ type: 'file' | 'folder'; id: number; name: string } | null>(null);
- const [thumbnailVersions, setThumbnailVersions] = useState<Record<number, number>>({});
- const [viewerFile, setViewerFile] = useState<LibraryFileListItem | null>(null);
- const [pdfPreviewFile, setPdfPreviewFile] = useState<LibraryFileListItem | null>(null);
- const [sheetPreviewFile, setSheetPreviewFile] = useState<LibraryFileListItem | null>(null);
- const [detailsFile, setDetailsFile] = useState<LibraryFileListItem | null>(null);
- const [imagePreviewFile, setImagePreviewFile] = useState<LibraryFileListItem | null>(null);
- const [viewMode, setViewMode] = useState<'grid' | 'list' | 'columns'>(() => {
- return (localStorage.getItem('library-view-mode') as 'grid' | 'list' | 'columns') || 'grid';
- });
- // Miller-columns keyboard navigation (#3020): the pane itself is focusable
- // and arrow keys walk the hierarchy. The focused file is tracked separately
- // from the checkbox selection so Space can toggle a file without the arrow
- // keys hijacking multi-select.
- const columnsViewRef = useRef<HTMLDivElement>(null);
- const [columnsFocusedFileId, setColumnsFocusedFileId] = useState<number | null>(null);
- const [wrapFolderNames, setWrapFolderNames] = useState(() => {
- return localStorage.getItem('library-wrap-folders') === 'true';
- });
- const [collapseFoldersByDefault, setCollapseFoldersByDefault] = useState(() => {
- return localStorage.getItem('library-collapse-folders') === 'true';
- });
- // Folder tree sort (#1770). 'name' = alphabetical (the prior behaviour);
- // 'activity' = most recent file activity inside the folder first. Persisted
- // independently from the file-side sort so each can be tuned to taste.
- const [folderSortField, setFolderSortField] = useState<'name' | 'activity'>(() => {
- const saved = localStorage.getItem('library-folder-sort-field');
- return saved === 'activity' ? 'activity' : 'name';
- });
- const [folderSortDirection, setFolderSortDirection] = useState<'asc' | 'desc'>(() => {
- const saved = localStorage.getItem('library-folder-sort-direction');
- return saved === 'desc' ? 'desc' : 'asc';
- });
- // Resizable sidebar state
- const [sidebarWidth, setSidebarWidth] = useState(() => {
- const saved = localStorage.getItem('library-sidebar-width');
- return saved ? parseInt(saved, 10) : 256; // Default w-64 = 256px
- });
- const [isResizing, setIsResizing] = useState(false);
- const sidebarRef = useRef<HTMLDivElement>(null);
- // Handle sidebar resize
- useEffect(() => {
- if (!isResizing) return;
- // Prevent text selection during resize
- document.body.style.userSelect = 'none';
- document.body.style.cursor = 'col-resize';
- const handleMouseMove = (e: MouseEvent) => {
- if (!sidebarRef.current) return;
- const containerRect = sidebarRef.current.parentElement?.getBoundingClientRect();
- if (!containerRect) return;
- // Calculate new width based on mouse position relative to container
- const newWidth = e.clientX - containerRect.left;
- // Clamp between 200px and 500px
- const clampedWidth = Math.min(500, Math.max(200, newWidth));
- setSidebarWidth(clampedWidth);
- };
- const handleMouseUp = () => {
- setIsResizing(false);
- document.body.style.userSelect = '';
- document.body.style.cursor = '';
- // Save to localStorage
- localStorage.setItem('library-sidebar-width', String(sidebarWidth));
- };
- document.addEventListener('mousemove', handleMouseMove);
- document.addEventListener('mouseup', handleMouseUp);
- return () => {
- document.removeEventListener('mousemove', handleMouseMove);
- document.removeEventListener('mouseup', handleMouseUp);
- document.body.style.userSelect = '';
- document.body.style.cursor = '';
- };
- }, [isResizing, sidebarWidth]);
- // Filter and sort state (persist sort preferences to localStorage)
- const [searchQuery, setSearchQuery] = useState('');
- const [filterType, setFilterType] = useState<string>('all');
- const [filterUsername, setFilterUsername] = useState('');
- const [sortField, setSortField] = useState<SortField>(() => {
- const saved = localStorage.getItem('library-sort-field');
- return (saved as SortField) || 'name';
- });
- const [sortDirection, setSortDirection] = useState<SortDirection>(() => {
- const saved = localStorage.getItem('library-sort-direction');
- return (saved as SortDirection) || 'asc';
- });
- // Show/hide the last-modified date on each file card (#2680). Persisted.
- const [showModified, setShowModified] = useState<boolean>(
- () => localStorage.getItem('library-show-modified') === 'true'
- );
- // Update selectedFolderId when URL parameter changes (e.g., navigating from Project or Archive page)
- useEffect(() => {
- const folderParam = searchParams.get('folder');
- if (folderParam) {
- const newFolderId = parseInt(folderParam, 10);
- setSelectedFolderId(newFolderId);
- }
- }, [searchParams]);
- // ?highlight=<file id> points at one file (the queue card's "View in File
- // Manager"). The link carries only the id: the folder is looked up here, so
- // a file moved since it was queued is still found. The folder's listing is
- // refetched before the file is looked for in it, since a cached one may
- // predate the move.
- const highlightParam = searchParams.get('highlight');
- const [pendingHighlight, setPendingHighlight] = useState<{ fileId: number; folderId: number | null; requestedAt: number } | null>(null);
- const [highlightedFileId, setHighlightedFileId] = useState<number | null>(null);
- const selectedFolderIdRef = useRef(selectedFolderId);
- selectedFolderIdRef.current = selectedFolderId;
- useEffect(() => {
- const fileId = highlightParam ? parseInt(highlightParam, 10) : NaN;
- if (!Number.isFinite(fileId)) return;
- let cancelled = false;
- const folderAtRequest = selectedFolderIdRef.current;
- api.getLibraryFile(fileId).then(
- (file) => {
- // Someone who opened another folder meanwhile is not pulled back.
- if (cancelled || selectedFolderIdRef.current !== folderAtRequest) return;
- const requestedAt = Date.now();
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- setSelectedFolderId(file.folder_id);
- setPendingHighlight({ fileId, folderId: file.folder_id, requestedAt });
- },
- () => {
- if (!cancelled) showToast(t('fileManager.highlightedFileNotFound'), 'warning');
- },
- );
- return () => {
- cancelled = true;
- };
- }, [highlightParam, queryClient, showToast, t]);
- // Queries
- const { data: settings } = useUiSettings();
- const preferredSlicer: SlicerType = resolveDesktopSlicer(settings?.open_in_slicer, settings?.preferred_slicer);
- const handleOpenInSlicer = useCallback(async (file: LibraryFileListItem) => {
- try {
- const { token } = await api.createLibrarySlicerToken(file.id);
- const path = api.getLibrarySlicerDownloadUrl(file.id, token, file.filename);
- openInSlicer(`${window.location.origin}${path}`, preferredSlicer);
- } catch {
- // Fallback to direct URL (works when auth is disabled). With auth on the
- // slicer may then hit a 401, so surface the failure instead of making a
- // permission denial look identical to "no slicer installed".
- showToast(t('fileManager.toast.openInSlicerFailed'), 'error');
- const path = api.getLibraryFileDownloadUrl(file.id);
- openInSlicer(`${window.location.origin}${path}`, preferredSlicer);
- }
- }, [preferredSlicer, showToast, t]);
- // Slice permission: API mode needs upload rights, the desktop handoff is a
- // download. Each mirrors what the backend enforces on the endpoint that
- // branch actually calls, so the UI never offers an action the server refuses.
- //
- // Deliberately NOT accepting the legacy `library:read` on the handoff branch.
- // It looks like the safe back-compat term to include, but the slicer-token
- // endpoint gates on require_ownership_permission(LIBRARY_READ_ALL,
- // LIBRARY_READ_OWN), and neither that dependency nor User.has_permission
- // expands the legacy name — so a group holding only `library:read` gets a 403
- // there. It cannot reach this page to find out either: GET /library/folders
- // gates on the same pair. Accepting it here would only enable a menu item
- // that fails, and the `library:read` -> `library:read_own` migration in
- // core/database.py runs only over the groups named in DEFAULT_GROUPS, so a
- // custom role that still carries it is genuinely stuck rather than silently
- // upgraded.
- const canSlice = useCallback(() => {
- if (settings?.use_slicer_api) {
- return hasPermission('library:upload');
- }
- return hasAnyPermission('library:read_all', 'library:read_own');
- }, [settings?.use_slicer_api, hasPermission, hasAnyPermission]);
- const { data: folders, isLoading: foldersLoading } = useQuery({
- queryKey: ['library-folders'],
- queryFn: () => api.getLibraryFolders(),
- });
- // Recursive folder tree sort (#1770). Applies the same comparator to the
- // top-level list AND to each level of `children`, so sort order is uniform
- // at every depth of nesting. When sorting by activity, the comparator falls
- // back to a created-at fallback for folders with no files (`latest_activity_at`
- // is null) so they stay grouped at the end / start of the bucket instead of
- // randomly interspersed.
- const sortedFolders = useMemo(() => {
- if (!folders) return folders;
- const sortLevel = (items: LibraryFolderTree[]): LibraryFolderTree[] => {
- const sorted = [...items].sort((a, b) => {
- let comparison = 0;
- if (folderSortField === 'name') {
- comparison = a.name.localeCompare(b.name);
- } else {
- // activity: newest first on 'desc', oldest first on 'asc'.
- // Folders with no activity timestamp sort to the end regardless
- // of direction so an empty folder doesn't elbow a recently-used one.
- const aTs = a.latest_activity_at ? new Date(a.latest_activity_at).getTime() : null;
- const bTs = b.latest_activity_at ? new Date(b.latest_activity_at).getTime() : null;
- if (aTs === null && bTs === null) {
- comparison = a.name.localeCompare(b.name);
- } else if (aTs === null) {
- return 1;
- } else if (bTs === null) {
- return -1;
- } else {
- comparison = aTs - bTs;
- }
- }
- return folderSortDirection === 'asc' ? comparison : -comparison;
- });
- return sorted.map((f) => ({ ...f, children: sortLevel(f.children) }));
- };
- return sortLevel(folders);
- }, [folders, folderSortField, folderSortDirection]);
- // Trash count for the header badge (#1008). Empty/error are silently treated
- // as zero so a broken trash endpoint doesn't break the File Manager.
- const { data: trashCount } = useQuery({
- queryKey: ['library-trash-count'],
- queryFn: async () => {
- try {
- const res = await api.listLibraryTrash(1, 0);
- return res.total;
- } catch {
- return 0;
- }
- },
- staleTime: 30_000,
- });
- // #1268: when a folder is selected and the user has typed a search query,
- // ask the server to expand the result to every descendant folder so the
- // client-side filter can match files in subfolders too. Without this the
- // listing is just the immediate children and "robot.3mf" two levels deep
- // is invisible from the parent. Only kicks in for folder-scoped views —
- // root and the internal/external pseudo-nodes already return the union.
- const searchExpandsSubfolders = selectedFolderId !== null && searchQuery.trim().length > 0;
- // The tag filter overrides folder scoping server-side (#1268 design call),
- // so the FE query key includes it as a peer of folder/topLevelView. Sorted
- // so the cache hits regardless of the order tags were toggled.
- const tagFilterKey = useMemo(() => [...selectedTagIds].sort((a, b) => a - b), [selectedTagIds]);
- // Tag catalog — needed to resolve names for the active-filter chip bar.
- // Cheap query, shared with LibraryTagsModal / BulkTagsPickerModal via the
- // same queryKey so they all invalidate together on tag CRUD.
- const { data: tagCatalog = [] } = useQuery({
- queryKey: ['library-tags'],
- queryFn: api.getLibraryTags,
- });
- const tagsById = useMemo(() => {
- const map = new Map<number, string>();
- for (const t of tagCatalog) map.set(t.id, t.name);
- return map;
- }, [tagCatalog]);
- // Prune the active filter when a tag is removed from the catalog so the
- // listing never stalls on a phantom id. Skipped while the catalog query is
- // still settling (empty array on first paint) — otherwise the user's filter
- // gets cleared the moment the page mounts.
- useEffect(() => {
- if (tagCatalog.length === 0) return;
- setSelectedTagIds((prev) => {
- const next = prev.filter((id) => tagsById.has(id));
- return next.length === prev.length ? prev : next;
- });
- }, [tagCatalog.length, tagsById]);
- const toggleTagFilter = useCallback((tagId: number) => {
- setSelectedTagIds((prev) =>
- prev.includes(tagId) ? prev.filter((id) => id !== tagId) : [...prev, tagId],
- );
- }, []);
- // While a search or tag filter is active the file list spans every matching
- // descendant folder, so per-level folder columns would lie about scope —
- // hide them and let the files pane take the full width.
- const columnsFilterActive = searchQuery.trim().length > 0 || selectedTagIds.length > 0;
- // In the columns view the pane beside the root column is that level's own
- // list, the files in no folder, like every other column's. Grid and list keep
- // "All Files", and so does a search or tag filter, whose results span every
- // folder.
- const paneRootOnly = viewMode === 'columns' && selectedFolderId === null && !columnsFilterActive;
- const { data: files, isLoading: filesLoading, dataUpdatedAt: filesUpdatedAt } = useQuery({
- queryKey: ['library-files', selectedFolderId, topLevelView, searchExpandsSubfolders, tagFilterKey, paneRootOnly],
- // When a specific folder is selected we list its contents directly; when
- // no folder is selected the topLevelView pseudo-node decides whether the
- // server scopes the result to internal-managed-storage files or to the
- // union of every external folder (#1621). include_root is false outside
- // the columns view's root level, so "All Files" still descends into
- // subfolders (regression guard from #1499).
- queryFn: () =>
- api.getLibraryFiles(
- selectedFolderId,
- paneRootOnly,
- undefined,
- selectedFolderId === null ? topLevelView : undefined,
- searchExpandsSubfolders,
- tagFilterKey,
- ),
- });
- const { data: stats } = useQuery({
- queryKey: ['library-stats'],
- queryFn: () => api.getLibraryStats(),
- });
- // Get users for the username filter autocomplete -- names only (#1894)
- const { data: users } = useQuery({
- queryKey: ['users', 'slim'],
- queryFn: () => api.getUsersSlim(),
- });
- // Get unique file types for filter dropdown
- const fileTypes = useMemo(() => {
- if (!files) return [];
- const types = new Set(files.map((f) => f.file_type));
- return Array.from(types).sort();
- }, [files]);
- // Filter and sort files
- const filteredAndSortedFiles = useMemo(
- () =>
- filterAndSortFiles(files ?? [], {
- query: searchQuery,
- filterType,
- filterUsername,
- sortField,
- sortDirection,
- }),
- [files, searchQuery, filterType, filterUsername, sortField, sortDirection],
- );
- // Once the file's folder is listed afresh, mark the file; then scroll to it
- // and drop the mark after a few seconds, as the Archives page does.
- useEffect(() => {
- if (!pendingHighlight || filesLoading || !files || selectedFolderId !== pendingHighlight.folderId) return;
- if (filesUpdatedAt < pendingHighlight.requestedAt) return;
- if (filteredAndSortedFiles.some((f) => f.id === pendingHighlight.fileId)) {
- setHighlightedFileId(pendingHighlight.fileId);
- if (viewMode === 'columns') setColumnsFocusedFileId(pendingHighlight.fileId);
- } else {
- showToast(t('fileManager.highlightedFileNotFound'), 'warning');
- }
- setPendingHighlight(null);
- }, [pendingHighlight, filesLoading, files, filesUpdatedAt, selectedFolderId, filteredAndSortedFiles, viewMode, showToast, t]);
- useEffect(() => {
- if (highlightedFileId === null) return;
- const scrollTimer = setTimeout(() => {
- document.querySelector(`[data-file-id="${highlightedFileId}"]`)?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
- }, 100);
- const clearTimer = setTimeout(() => setHighlightedFileId(null), 5000);
- return () => {
- clearTimeout(scrollTimer);
- clearTimeout(clearTimer);
- };
- }, [highlightedFileId]);
- // Check if disk space is low
- const isDiskSpaceLow = useMemo(() => {
- if (!stats || !settings) return false;
- const thresholdBytes = (settings.library_disk_warning_gb || 5) * 1024 * 1024 * 1024;
- return stats.disk_free_bytes < thresholdBytes;
- }, [stats, settings]);
- // Mutations
- const createFolderMutation = useMutation({
- mutationFn: (data: LibraryFolderCreate) => api.createLibraryFolder(data),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- setShowNewFolderModal(false);
- showToast(t('fileManager.toast.folderCreated'), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const createExternalFolderMutation = useMutation({
- mutationFn: async (data: ExternalFolderCreate) => {
- const folder = await api.createExternalFolder(data);
- // Auto-scan after creation
- await api.scanExternalFolder(folder.id);
- return folder;
- },
- onSuccess: (folder) => {
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- setShowExternalFolderModal(false);
- setSelectedFolderId(folder.id);
- showToast(t('fileManager.toast.externalFolderLinked'), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const scanExternalFolderMutation = useMutation({
- mutationFn: (folderId: number) => api.scanExternalFolder(folderId),
- onSuccess: (result) => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- showToast(t('fileManager.toast.folderScanned', { added: result.added, removed: result.removed }), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const deleteFolderMutation = useMutation({
- mutationFn: (id: number) => api.deleteLibraryFolder(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- if (selectedFolderId === deleteConfirm?.id) {
- setSelectedFolderId(null);
- }
- setDeleteConfirm(null);
- showToast(t('fileManager.toast.folderDeleted'), 'success');
- },
- onError: (error: Error) => {
- setDeleteConfirm(null);
- showToast(error.message, 'error');
- },
- });
- const deleteFileMutation = useMutation({
- mutationFn: (id: number) => api.deleteLibraryFile(id),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- queryClient.invalidateQueries({ queryKey: ['library-trash-count'] });
- setSelectedFiles((prev) => prev.filter((id) => id !== deleteConfirm?.id));
- setDeleteConfirm(null);
- showToast(t('fileManager.toast.fileDeleted'), 'success');
- },
- onError: (error: Error) => {
- setDeleteConfirm(null);
- showToast(error.message, 'error');
- },
- });
- // "These files are the same job for different printers" (#671 / #2570).
- // Durable, unlike the ad-hoc selection the Print button uses: once grouped,
- // printing any member offers the others without re-selecting them.
- const groupAsVersionsMutation = useMutation({
- mutationFn: (fileIds: number[]) =>
- api.createVariantGroup(fileIds.map((id) => ({ library_file_id: id }))),
- onSuccess: (group) => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- showToast(t('fileManager.variants.grouped', { count: group.members.length }), 'success');
- setSelectedFiles([]);
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const bulkDeleteMutation = useMutation({
- mutationFn: (fileIds: number[]) => api.bulkDeleteLibrary(fileIds, []),
- onSuccess: (_, fileIds) => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- queryClient.invalidateQueries({ queryKey: ['library-trash-count'] });
- showToast(t('fileManager.toast.filesDeleted', { count: fileIds.length }), 'success');
- setSelectedFiles([]);
- setDeleteConfirm(null);
- },
- onError: (error: Error) => {
- setDeleteConfirm(null);
- showToast(error.message, 'error');
- },
- });
- const moveFilesMutation = useMutation({
- mutationFn: ({ fileIds, folderId }: { fileIds: number[]; folderId: number | null }) =>
- api.moveLibraryFiles(fileIds, folderId),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- setSelectedFiles([]);
- setShowMoveModal(false);
- showToast(t('fileManager.toast.filesMoved'), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const updateFolderMutation = useMutation({
- mutationFn: ({ id, data }: { id: number; data: LibraryFolderUpdate }) =>
- api.updateLibraryFolder(id, data),
- onSuccess: (_, variables) => {
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- // Invalidate project/archive folder queries so other pages see the update
- queryClient.invalidateQueries({ queryKey: ['project-folders'] });
- queryClient.invalidateQueries({ queryKey: ['archive-folders'] });
- setLinkFolder(null);
- const isUnlink = variables.data.project_id === 0 && variables.data.archive_id === 0;
- showToast(isUnlink ? t('fileManager.toast.folderUnlinked') : t('fileManager.toast.folderLinked'), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const renameFileMutation = useMutation({
- mutationFn: ({ id, filename }: { id: number; filename: string }) =>
- api.updateLibraryFile(id, { filename }),
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- setRenameItem(null);
- showToast(t('fileManager.toast.fileRenamed'), 'success');
- },
- onError: (error: Error) => {
- setRenameItem(null);
- showToast(error.message, 'error');
- },
- });
- const renameFolderMutation = useMutation({
- mutationFn: ({ id, name }: { id: number; name: string }) =>
- api.updateLibraryFolder(id, { name }),
- onSuccess: () => {
- // Invalidate both folders and files - files may display folder info
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- setRenameItem(null);
- showToast(t('fileManager.toast.folderRenamed'), 'success');
- },
- onError: (error: Error) => {
- setRenameItem(null);
- showToast(error.message, 'error');
- },
- });
- const shareFolderMutation = useMutation({
- mutationFn: ({ id, shared }: { id: number; shared: boolean }) => api.updateLibraryFolder(id, { shared }),
- onSuccess: (_, variables) => {
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['project-folders'] });
- queryClient.invalidateQueries({ queryKey: ['archive-folders'] });
- showToast(variables.shared ? t('fileManager.toast.folderShared') : t('fileManager.toast.folderUnshared'), 'success');
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const toggleFolderShared = (folder: LibraryFolderTree) =>
- shareFolderMutation.mutate({ id: folder.id, shared: !folder.shared });
- const batchThumbnailMutation = useMutation({
- mutationFn: () => api.batchGenerateStlThumbnails({ all_missing: true }),
- onSuccess: (result) => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- // Update thumbnail versions for cache busting
- if (result.succeeded > 0) {
- const now = Date.now();
- const newVersions: Record<number, number> = {};
- result.results.forEach((r) => {
- if (r.success) {
- newVersions[r.file_id] = now;
- }
- });
- setThumbnailVersions((prev) => ({ ...prev, ...newVersions }));
- }
- if (result.succeeded > 0 && result.failed === 0) {
- showToast(t('fileManager.toast.thumbnailsGenerated', { count: result.succeeded }), 'success');
- } else if (result.succeeded > 0 && result.failed > 0) {
- showToast(t('fileManager.toast.thumbnailsGeneratedPartial', { succeeded: result.succeeded, failed: result.failed }), 'success');
- } else if (result.processed === 0) {
- showToast(t('fileManager.toast.noStlMissingThumbnails'), 'info');
- } else {
- showToast(t('fileManager.toast.failedToGenerateThumbnails', { error: result.results[0]?.error || 'Unknown error' }), 'error');
- }
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- const singleThumbnailMutation = useMutation({
- mutationFn: (fileId: number) => api.batchGenerateStlThumbnails({ file_ids: [fileId] }),
- onSuccess: (result) => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- // Update thumbnail version for cache busting
- if (result.succeeded > 0) {
- const fileId = result.results[0]?.file_id;
- if (fileId) {
- setThumbnailVersions((prev) => ({ ...prev, [fileId]: Date.now() }));
- }
- showToast(t('fileManager.toast.thumbnailGenerated'), 'success');
- } else {
- showToast(t('fileManager.toast.failedToGenerateThumbnail', { error: result.results[0]?.error || 'Unknown error' }), 'error');
- }
- },
- onError: (error: Error) => showToast(error.message, 'error'),
- });
- // The one way into a preview (#2976): the kebab entry, the action-strip
- // icon, a double-click on the card or row, and the toolbar button all end
- // up here. Sliced files open the full-page gcode viewer the archive card
- // uses; everything else opens the modal for its type. A file with no
- // preview does nothing.
- const openPreview = useCallback((file: LibraryFileListItem) => {
- if (!hasPermission('library:read')) return;
- if (isSlicedLibraryFile(file)) {
- navigate(`/gcode-viewer?library_file=${file.id}`);
- } else if (file.file_type === '3mf' || file.file_type === 'stl' || isStepType(file.file_type)) {
- setViewerFile(file);
- } else if (file.file_type === 'pdf') {
- setPdfPreviewFile(file);
- } else if (isSpreadsheetType(file.file_type)) {
- setSheetPreviewFile(file);
- } else if (isPreviewableImageType(file.file_type)) {
- setImagePreviewFile(file);
- }
- }, [hasPermission, navigate]);
- // Handlers
- const handleFileSelect = useCallback((id: number) => {
- // Always toggle selection (multi-select by default)
- setSelectedFiles((prev) => {
- return prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id];
- });
- }, []);
- // In the columns view Select all adds the pane's files to what is ticked, so
- // a file ticked in an earlier column (still on screen) stays ticked (#3020).
- // Grid and list replace the selection: a file a search has hidden must not
- // stay ticked behind the user's back, or a bulk Delete would remove it.
- const handleSelectAll = useCallback(() => {
- if (filteredAndSortedFiles.length > 0) {
- const paneIds = filteredAndSortedFiles.map((f) => f.id);
- setSelectedFiles((prev) => (viewMode === 'columns' ? [...new Set([...prev, ...paneIds])] : paneIds));
- }
- }, [filteredAndSortedFiles, viewMode]);
- // "Deselect all" once every file of the pane is ticked. The pane's own ids,
- // not a count: ticks in earlier columns count towards the selection too.
- const allPaneFilesSelected =
- filteredAndSortedFiles.length > 0 && filteredAndSortedFiles.every((f) => selectedFiles.includes(f.id));
- const handleDeselectAll = useCallback(() => {
- setSelectedFiles([]);
- }, []);
- const handleUploadComplete = () => {
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['library-folders'] });
- queryClient.invalidateQueries({ queryKey: ['library-stats'] });
- };
- // Page-wide drag-and-drop upload (#1510). Disabled when the user lacks
- // library:upload so a non-uploader can't accidentally show the overlay,
- // and also disabled while the upload modal itself is open so drags into
- // the modal's own drop zone don't bubble up and flash the page overlay
- // behind it.
- // Find the selected folder in the tree to check external status
- const selectedFolder = useMemo(() => {
- if (!selectedFolderId || !folders) return null;
- const findFolder = (items: LibraryFolderTree[]): LibraryFolderTree | null => {
- for (const item of items) {
- if (item.id === selectedFolderId) return item;
- const found = findFolder(item.children);
- if (found) return found;
- }
- return null;
- };
- return findFolder(folders);
- }, [selectedFolderId, folders]);
- // A library:read_own user may add only to their own folders and shared
- // ones (#3201); a folder they merely pass through is read-only for them.
- const canWriteHere = selectedFolder?.can_write !== false;
- const canUpload = hasPermission('library:upload') && canWriteHere;
- const addDisabledTitle = !hasPermission('library:upload')
- ? undefined
- : !canWriteHere
- ? t('fileManager.folderNotWritable')
- : undefined;
- const { isDraggingOver, dragHandlers } = usePageFileDrop({
- disabled: !canUpload || showUploadModal,
- onFiles: (files) => {
- setDroppedFiles(files);
- setShowUploadModal(true);
- },
- });
- // Returns the snapshot callback the preview components call with their
- // first render, or undefined when nothing should be persisted — the file
- // already has a thumbnail, or the user may not update it (#2976).
- const previewSnapshotHandler = useCallback(
- (file: LibraryFileListItem): ((blob: Blob) => void) | undefined => {
- if (file.thumbnail_path) return undefined;
- if (!canModify('library', 'update', file.created_by_id)) return undefined;
- return (blob: Blob) => {
- api
- .uploadLibraryPreviewThumbnail(file.id, blob)
- .then((res) => {
- if (res.updated) {
- setThumbnailVersions((prev) => ({ ...prev, [file.id]: (prev[file.id] || 0) + 1 }));
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- }
- })
- .catch(() => {
- // Thumbnail persistence is best-effort; the preview already rendered.
- });
- };
- },
- [canModify, queryClient]
- );
- const handleDownload = (id: number) => {
- api.downloadLibraryFile(id).catch((err) => {
- console.error('Library file download failed:', err);
- });
- };
- const handleDeleteConfirm = () => {
- if (!deleteConfirm) return;
- if (deleteConfirm.type === 'file') {
- deleteFileMutation.mutate(deleteConfirm.id);
- } else if (deleteConfirm.type === 'folder') {
- deleteFolderMutation.mutate(deleteConfirm.id);
- } else if (deleteConfirm.type === 'bulk') {
- bulkDeleteMutation.mutate(selectedFiles);
- }
- };
- const isDeleting = deleteFolderMutation.isPending || deleteFileMutation.isPending || bulkDeleteMutation.isPending;
- const handleViewModeChange = (mode: 'grid' | 'list' | 'columns') => {
- setViewMode(mode);
- localStorage.setItem('library-view-mode', mode);
- };
- // Shared by the list row and the columns view (see FileActionStrip).
- const fileActionProps = {
- onPrint: setPrintFile,
- onSlice: setSliceFile,
- onOpenInSlicer: handleOpenInSlicer,
- onRunPipeline: setRunPipelineFile,
- useSlicerApi: settings?.use_slicer_api ?? false,
- desktopSlicer: preferredSlicer,
- canSlice: canSlice(),
- onPreview: openPreview,
- onDetails: setDetailsFile,
- onDownload: handleDownload,
- onRename: (f: LibraryFileListItem) => setRenameItem({ type: 'file', id: f.id, name: f.filename }),
- onGenerateThumbnail: (f: LibraryFileListItem) => singleThumbnailMutation.mutate(f.id),
- thumbnailPending: singleThumbnailMutation.isPending,
- onDelete: (id: number) => setDeleteConfirm({ type: 'file', id }),
- hasPermission,
- canModify,
- t,
- };
- const isLoading = foldersLoading || filesLoading;
- // The chain of folders from a top-level folder down to the selected one.
- // Selection is the single source of truth — clicking a folder anywhere just
- // moves selectedFolderId, and the path (and with it the path bar and the set
- // of visible columns) is re-derived from the sorted tree.
- const folderPath = useMemo(() => {
- if (!sortedFolders || selectedFolderId === null) return [] as LibraryFolderTree[];
- const path: LibraryFolderTree[] = [];
- const walk = (items: LibraryFolderTree[]): boolean => {
- for (const item of items) {
- path.push(item);
- if (item.id === selectedFolderId) return true;
- if (walk(item.children)) return true;
- path.pop();
- }
- return false;
- };
- walk(sortedFolders);
- return path;
- }, [sortedFolders, selectedFolderId]);
- // Which half of the tree the current location lives in: the selected path's
- // bucket when there is one, otherwise the sidebar's top-level choice. Drives
- // both the path bar's root crumb and the columns view's first column.
- const currentBucketIsExternal =
- folderPath.length > 0 ? Boolean(folderPath[0].is_external) : topLevelView === 'external';
- // One column per level: the top-level bucket, then the children of each
- // folder along the path. `folderId` is the folder the column is the inside
- // of (null = the library root), which is what its file list is keyed on.
- // Leaf folders contribute no column — the files pane to the right is their
- // content.
- const folderColumns = useMemo(() => {
- const rootItems = (sortedFolders ?? []).filter((f) => Boolean(f.is_external) === currentBucketIsExternal);
- const cols: { key: string; folderId: number | null; items: LibraryFolderTree[]; activeId: number | null }[] = [
- { key: 'root', folderId: null, items: rootItems, activeId: folderPath[0]?.id ?? null },
- ];
- folderPath.forEach((node, i) => {
- if (node.children.length > 0) {
- cols.push({
- key: `folder-${node.id}`,
- folderId: node.id,
- items: node.children,
- activeId: folderPath[i + 1]?.id ?? null,
- });
- }
- });
- return cols;
- }, [sortedFolders, folderPath, currentBucketIsExternal]);
- // Every column lists its own level's files, not just the rightmost pane: a
- // folder that holds files and no subfolders used to look empty until it was
- // the selection. One query per rendered level, keyed on that level's folder
- // id so walking back up a path is instant. Only levels the view actually
- // renders are fetched, and the level that IS the current selection is
- // skipped — the pane on the right already lists exactly those files.
- const columnFileLevels = useMemo(() => {
- if (viewMode !== 'columns' || columnsFilterActive) return [];
- return folderColumns
- .filter((col) => col.folderId !== selectedFolderId)
- .map((col) => ({
- key: col.key,
- folderId: col.folderId,
- scope:
- col.folderId === null
- ? currentBucketIsExternal
- ? ('external' as const)
- : ('internal' as const)
- : undefined,
- }));
- }, [viewMode, columnsFilterActive, folderColumns, selectedFolderId, currentBucketIsExternal]);
- const columnFileQueries = useQueries({
- combine: combineColumnFileQueries,
- queries: columnFileLevels.map((level) => ({
- queryKey: ['library-files', 'column', level.folderId, level.scope ?? null],
- // include_root only means anything for the root column, where "this
- // level's files" are the ones that sit in no folder at all. Under a
- // folder id the server already answers with that folder's own files.
- queryFn: () =>
- api.getLibraryFiles(level.folderId, level.folderId === null, undefined, level.scope, false, []),
- })),
- });
- // Keyed by column so the render stays a lookup. Deliberately not memoised:
- // useQueries hands back a fresh array every render, so a memo would recompute
- // anyway.
- const columnFiles = new Map<string, { files: LibraryFileListItem[]; loading: boolean }>();
- columnFileLevels.forEach((level, i) => {
- const query = columnFileQueries.results[i];
- columnFiles.set(level.key, {
- files: filterAndSortFiles(query?.data ?? [], { filterType, filterUsername, sortField, sortDirection }),
- loading: Boolean(query?.isPending),
- });
- });
- // Every file a tick can point at: the pane plus the files of every column
- // the view has loaded, since a file can be ticked in an earlier column
- // (#3020). The toolbar's actions resolve the selection against this.
- const selectableFiles = useMemo(() => {
- const byId = new Map<number, LibraryFileListItem>();
- for (const file of [...(files ?? []), ...columnFileQueries.files]) byId.set(file.id, file);
- return byId;
- }, [files, columnFileQueries.files]);
- // The toolbar's Preview button acts on one file, so it is offered only for
- // a single previewable selection.
- const previewSelection = useMemo(() => {
- if (selectedFiles.length !== 1) return null;
- const file = selectableFiles.get(selectedFiles[0]);
- return file && isPreviewableLibraryFile(file) ? file : null;
- }, [selectableFiles, selectedFiles]);
- // The sliced files among the selection, in the order they were ticked.
- const selectedSlicedFiles = useMemo(
- () =>
- selectedFiles
- .map((id) => selectableFiles.get(id))
- .filter((f): f is LibraryFileListItem => !!f && isSlicedLibraryFile(f)),
- [selectableFiles, selectedFiles],
- );
- // "Combine to 3MF" is offered only when every selected file is an STL, so
- // the action never silently drops part of the selection. Resolved like the
- // rest, so an STL ticked in an earlier column counts too.
- const selectedStlFiles = useMemo(() => {
- const stls = selectedFiles
- .map((id) => selectableFiles.get(id))
- .filter((f): f is LibraryFileListItem => !!f && f.filename.toLowerCase().endsWith('.stl'));
- return stls.length === selectedFiles.length ? stls : [];
- }, [selectableFiles, selectedFiles]);
- // The clicked file's variant group, so printing one member offers the rest
- // without the user re-selecting them (#2570).
- const { data: printFileGroup } = useQuery({
- queryKey: ['variant-group', printFile?.variant_group_id],
- queryFn: () => api.getVariantGroup(printFile!.variant_group_id!),
- enabled: !!printFile?.variant_group_id,
- });
- // Candidates for a cross-model print (#671), or undefined for an ordinary one.
- // An explicit multi-selection wins over the group: the user just said, in this
- // action, which files they meant.
- const printVariantFiles = useMemo(() => {
- if (!printFile) return undefined;
- if (selectedSlicedFiles.length > 1) {
- return selectedSlicedFiles.map(f => ({
- id: f.id,
- filename: f.filename,
- sliced_for_model: f.sliced_for_model,
- }));
- }
- if (printFileGroup && printFileGroup.members.length > 1) {
- return printFileGroup.members.map(m => ({
- id: m.library_file_id,
- filename: m.filename,
- sliced_for_model: m.target_model,
- }));
- }
- return undefined;
- }, [printFile, selectedSlicedFiles, printFileGroup]);
- // The list the arrow keys walk: the one that actually holds the focused
- // file, which may be an intermediate column rather than the selected
- // folder's pane.
- const focusedFileColumnList =
- columnsFocusedFileId === null
- ? undefined
- : columnFileLevels
- .map((level) => columnFiles.get(level.key)?.files)
- .find((list) => list?.some((f) => f.id === columnsFocusedFileId));
- const focusedFileList = focusedFileColumnList ?? filteredAndSortedFiles;
- // Focus the columns pane when the view opens so arrow keys work right away,
- // and drop the file focus whenever the folder (and with it the file list)
- // changes. A modal or the search box taking focus naturally mutes the
- // pane's key handling — no explicit guards needed.
- useEffect(() => {
- if (viewMode === 'columns') columnsViewRef.current?.focus({ preventScroll: true });
- }, [viewMode]);
- useEffect(() => {
- setColumnsFocusedFileId(null);
- }, [selectedFolderId, viewMode]);
- // A selection belongs to the folder it was made in. Every column can tick a
- // file, so a selection that survived a folder change would leave Move and
- // Delete pointing at rows that are no longer anywhere on screen (#3020).
- useEffect(() => {
- setSelectedFiles([]);
- }, [selectedFolderId]);
- // Keep the keyboard-driven selection scrolled into view. Deliberately an
- // effect keyed on the ids, NOT per-render ref callbacks: those re-run on
- // every commit and would snap a manually scrolled column back to the
- // highlighted row whenever anything re-renders. scrollIntoView is guarded
- // because jsdom doesn't implement it.
- useEffect(() => {
- if (viewMode !== 'columns' || selectedFolderId === null) return;
- columnsViewRef.current?.querySelector(`[data-folder-id="${selectedFolderId}"]`)?.scrollIntoView?.({ block: 'nearest' });
- }, [selectedFolderId, viewMode]);
- useEffect(() => {
- if (viewMode !== 'columns' || columnsFocusedFileId === null) return;
- columnsViewRef.current?.querySelector(`[data-file-id="${columnsFocusedFileId}"]`)?.scrollIntoView?.({ block: 'nearest' });
- }, [columnsFocusedFileId, viewMode]);
- // Finder-style keys: Up/Down move within the current column, Right descends
- // (into the first child folder, then into the files), Left ascends, Enter
- // opens the focused file's preview, Space toggles its selection.
- //
- // Actions: the focused file's icon strip is the only one in the Tab order
- // (roving tabindex), so Tab from the pane lands on it; the context-menu
- // key (or Shift+F10) jumps there directly, or opens the selected folder's
- // kebab while no file is focused. Inside a strip Left/Right walk the
- // buttons, Enter/Space activate one natively and Escape returns to the pane.
- const focusColumnsActions = () => {
- const root = columnsViewRef.current;
- if (!root) return;
- if (columnsFocusedFileId !== null) {
- root
- .querySelector<HTMLButtonElement>(`[data-file-id="${columnsFocusedFileId}"] [data-file-actions] button:not([disabled])`)
- ?.focus();
- } else if (selectedFolderId !== null) {
- const kebab = root.querySelector<HTMLButtonElement>(`[data-folder-id="${selectedFolderId}"] [data-folder-actions] button`);
- // Focus first so Tab continues into the menu that the click opens.
- kebab?.focus();
- kebab?.click();
- }
- };
- const handleColumnsKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
- if (e.ctrlKey || e.metaKey || e.altKey) return;
- const target = e.target as HTMLElement;
- if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable) return;
- if (target.closest('[data-folder-actions]')) {
- // A folder kebab (and the menu it opens) handles its own keys, except
- // that Escape and Up/Down hand focus back to the pane — otherwise the
- // arrows are dead until the user clicks or Shift+Tabs out of the kebab.
- if (e.key === 'Escape') {
- e.preventDefault();
- columnsViewRef.current?.focus({ preventScroll: true });
- return;
- }
- if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return;
- columnsViewRef.current?.focus({ preventScroll: true });
- }
- const strip = target.closest<HTMLElement>('[data-file-actions]');
- if (strip) {
- if (e.key === 'Enter' || e.key === ' ') return;
- if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
- e.preventDefault();
- const buttons = Array.from(strip.querySelectorAll<HTMLButtonElement>('button:not([disabled])'));
- buttons[buttons.indexOf(target as HTMLButtonElement) + (e.key === 'ArrowRight' ? 1 : -1)]?.focus();
- return;
- }
- if (e.key === 'Escape') {
- e.preventDefault();
- columnsViewRef.current?.focus({ preventScroll: true });
- return;
- }
- // Up/Down move the row focus below; DOM focus must leave the old row's
- // strip with it, or the next Enter would fire that row's button.
- if (e.key === 'ArrowUp' || e.key === 'ArrowDown') columnsViewRef.current?.focus({ preventScroll: true });
- }
- if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
- e.preventDefault();
- focusColumnsActions();
- return;
- }
- const inFiles = columnsFocusedFileId !== null;
- const selectedNode = folderPath[folderPath.length - 1];
- switch (e.key) {
- case 'ArrowDown':
- case 'ArrowUp': {
- e.preventDefault();
- const dir = e.key === 'ArrowDown' ? 1 : -1;
- if (inFiles || columnsFilterActive) {
- // findIndex yields -1 for a vanished focus id — ArrowDown then
- // lands on index 0, ArrowUp on -2 → no-op, both intended.
- const idx = focusedFileList.findIndex((f) => f.id === columnsFocusedFileId);
- const next = focusedFileList[idx + dir];
- if (next) setColumnsFocusedFileId(next.id);
- else if (dir === -1 && idx === 0 && focusedFileColumnList) {
- // Off the top of a column's files: back onto that same column's
- // folders, which is where ArrowDown came from.
- setColumnsFocusedFileId(null);
- }
- } else if (selectedFolderId === null) {
- if (dir === 1 && folderColumns[0].items.length > 0) {
- setSelectedFolderId(folderColumns[0].items[0].id);
- }
- } else {
- const col = folderColumns[folderPath.length - 1];
- const idx = col ? col.items.findIndex((f) => f.id === selectedFolderId) : -1;
- const next = idx === -1 ? undefined : col.items[idx + dir];
- if (next) setSelectedFolderId(next.id);
- else if (dir === 1 && idx !== -1) {
- // Past the last folder the column's own files continue the list,
- // exactly as they read on screen: the only way a keyboard
- // reaches an intermediate column's rows at all.
- const colFiles = col ? columnFiles.get(col.key)?.files : undefined;
- if (colFiles?.length) setColumnsFocusedFileId(colFiles[0].id);
- }
- }
- break;
- }
- case 'ArrowRight': {
- e.preventDefault();
- if (inFiles) break;
- if (!columnsFilterActive && selectedNode && selectedNode.children.length > 0) {
- setSelectedFolderId(selectedNode.children[0].id);
- } else if (filteredAndSortedFiles.length > 0) {
- setColumnsFocusedFileId(filteredAndSortedFiles[0].id);
- }
- break;
- }
- case 'ArrowLeft': {
- e.preventDefault();
- if (inFiles) {
- setColumnsFocusedFileId(null);
- break;
- }
- // With a filter active the folder columns are hidden — don't move a
- // selection the user can't see.
- if (columnsFilterActive) break;
- if (folderPath.length > 1) {
- setSelectedFolderId(folderPath[folderPath.length - 2].id);
- } else if (folderPath.length === 1) {
- // Ascending past the top level: keep the bucket the user was
- // navigating — the tree can select a folder from either bucket
- // without touching topLevelView, and falling back to a stale one
- // would teleport the root column to the other folder set.
- setTopLevelView(folderPath[0].is_external ? 'external' : 'internal');
- setSelectedFolderId(null);
- } else if (selectedFolderId !== null) {
- // Selection not in the tree (e.g. a deep link to a deleted
- // folder): give the keyboard an escape hatch back to the root.
- setSelectedFolderId(null);
- }
- break;
- }
- // Enter and Space preventDefault BEFORE the inFiles check: DOM focus
- // may still sit on the last-clicked folder button, and the browser's
- // default activation would re-click it — snapping the selection back
- // to a folder the arrows have long left (Space would scroll the page).
- case 'Enter': {
- e.preventDefault();
- if (!inFiles) {
- // Enter means "open the selected thing": on a folder that is
- // descending, exactly like ArrowRight.
- if (!columnsFilterActive && selectedNode && selectedNode.children.length > 0) {
- setSelectedFolderId(selectedNode.children[0].id);
- } else if (filteredAndSortedFiles.length > 0) {
- setColumnsFocusedFileId(filteredAndSortedFiles[0].id);
- }
- break;
- }
- const file = focusedFileList.find((f) => f.id === columnsFocusedFileId);
- if (file) openPreview(file);
- break;
- }
- case ' ': {
- e.preventDefault();
- if (!inFiles) break;
- if (columnsFocusedFileId !== null) handleFileSelect(columnsFocusedFileId);
- break;
- }
- }
- };
- return (
- <div
- className="p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-screen flex flex-col relative"
- {...dragHandlers}
- >
- {/* Drag & Drop Overlay — page-wide file upload (#1510) */}
- {isDraggingOver && (
- <div className="fixed inset-0 z-50 bg-bambu-dark/90 flex items-center justify-center pointer-events-none">
- <div className="border-4 border-dashed border-bambu-green rounded-xl p-12 text-center">
- <Upload className="w-16 h-16 mx-auto mb-4 text-bambu-green" />
- <p className="text-2xl font-semibold text-white mb-2">{t('fileManager.dropFilesHere')}</p>
- <p className="text-bambu-gray">{t('fileManager.releaseToUpload')}</p>
- </div>
- </div>
- )}
- {/* Header */}
- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
- <div>
- <h1 className="text-2xl font-bold text-white flex items-center gap-3">
- <FolderOpen className="w-7 h-7 text-bambu-green" />
- {t('fileManager.title')}
- </h1>
- <p className="text-bambu-gray mt-1">
- {t('fileManager.subtitle')}
- </p>
- </div>
- {/* Wraps: up to nine controls, which pushed the page sideways on a
- phone (#3295). Next to the title it takes only the room left over
- (flex-1 from zero), so the title is not squeezed to fit it. */}
- <div className="flex flex-wrap items-center sm:justify-end sm:flex-1 gap-2 min-w-0">
- {/* View mode toggle */}
- <div className="flex items-center bg-bambu-dark rounded-lg p-1">
- <button
- onClick={() => handleViewModeChange('grid')}
- className={`p-1.5 rounded transition-colors ${
- viewMode === 'grid' ? 'bg-bambu-dark-secondary text-white' : 'text-bambu-gray hover:text-white'
- }`}
- title={t('fileManager.gridView')}
- >
- <LayoutGrid className="w-4 h-4" />
- </button>
- <button
- onClick={() => handleViewModeChange('list')}
- className={`p-1.5 rounded transition-colors ${
- viewMode === 'list' ? 'bg-bambu-dark-secondary text-white' : 'text-bambu-gray hover:text-white'
- }`}
- title={t('fileManager.listView')}
- >
- <List className="w-4 h-4" />
- </button>
- <button
- onClick={() => handleViewModeChange('columns')}
- className={`p-1.5 rounded transition-colors ${
- viewMode === 'columns' ? 'bg-bambu-dark-secondary text-white' : 'text-bambu-gray hover:text-white'
- }`}
- title={t('fileManager.columnsView')}
- >
- <Columns className="w-4 h-4" />
- </button>
- </div>
- <Button
- variant="secondary"
- onClick={() => batchThumbnailMutation.mutate()}
- disabled={batchThumbnailMutation.isPending || !hasAnyPermission('library:update_own', 'library:update_all')}
- title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.noPermissionGenerateThumbnail') : t('fileManager.generateThumbnailsForMissing')}
- >
- {batchThumbnailMutation.isPending ? (
- <Loader2 className="w-4 h-4 mr-2 animate-spin" />
- ) : (
- <Image className="w-4 h-4 mr-2" />
- )}
- {t('fileManager.generateThumbnails')}
- </Button>
- <Button
- variant="secondary"
- onClick={() => setShowExternalFolderModal(true)}
- disabled={!hasPermission('library:upload')}
- title={!hasPermission('library:upload') ? t('fileManager.noPermissionCreateFolder') : t('fileManager.linkExternalFolder')}
- >
- <FolderSymlink className="w-4 h-4 mr-2" />
- {t('fileManager.linkExternal')}
- </Button>
- <Button
- variant="secondary"
- onClick={() => setShowNewFolderModal(true)}
- disabled={!canUpload}
- title={!hasPermission('library:upload') ? t('fileManager.noPermissionCreateFolder') : addDisabledTitle}
- >
- <FolderPlus className="w-4 h-4 mr-2" />
- {t('fileManager.newFolder')}
- </Button>
- <Button
- variant="secondary"
- onClick={() => setShowTagsModal(true)}
- title={t('fileManager.tags.manageTitle')}
- >
- <TagIcon className="w-4 h-4 mr-2" />
- {t('fileManager.tags.manage')}
- </Button>
- {hasPermission('library:purge') && (
- <Button
- variant="secondary"
- onClick={() => setShowPurgeModal(true)}
- title={t('libraryPurge.headerTooltip')}
- >
- <Trash2 className="w-4 h-4 mr-2" />
- {t('libraryPurge.headerButton')}
- </Button>
- )}
- {(hasAnyPermission('library:delete_own', 'library:delete_all')) && (
- <Link
- to="/files/trash"
- 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"
- title={t('libraryTrash.headerTooltip')}
- >
- <Trash2 className="w-4 h-4 mr-2" />
- {t('libraryTrash.headerButton')}
- {typeof trashCount === 'number' && trashCount > 0 && (
- <span className="ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-bambu-green/20 text-bambu-green">
- {trashCount}
- </span>
- )}
- </Link>
- )}
- <Button
- onClick={() => setShowUploadModal(true)}
- disabled={!canUpload}
- title={!hasPermission('library:upload') ? t('fileManager.noPermissionUpload') : addDisabledTitle}
- >
- <Upload className="w-4 h-4 mr-2" />
- {t('common.upload')}
- </Button>
- </div>
- </div>
- {/* Disk space warning */}
- {isDiskSpaceLow && stats && settings && (
- <div className="flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg">
- <AlertTriangle className="w-5 h-5 text-amber-500 flex-shrink-0" />
- <div className="flex-1">
- <p className="text-sm text-amber-500 font-medium">{t('fileManager.lowDiskSpaceWarning')}</p>
- <p className="text-xs text-amber-500/80">
- {t('fileManager.lowDiskSpaceDetails', { free: formatFileSize(stats.disk_free_bytes), total: formatFileSize(stats.disk_total_bytes), threshold: settings.library_disk_warning_gb })}
- </p>
- </div>
- </div>
- )}
- {/* Stats bar */}
- {stats && (
- <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">
- <div className="flex items-center gap-2 text-sm">
- <File className="w-4 h-4 text-bambu-green" />
- <span className="text-bambu-gray">{t('fileManager.files')}:</span>
- <span className="text-white font-medium">{stats.total_files}</span>
- </div>
- <div className="flex items-center gap-2 text-sm">
- <FolderOpen className="w-4 h-4 text-blue-600 dark:text-blue-400" />
- <span className="text-bambu-gray">{t('fileManager.folders')}:</span>
- <span className="text-white font-medium">{stats.total_folders}</span>
- </div>
- <div className="flex items-center gap-2 text-sm">
- <HardDrive className="w-4 h-4 text-amber-600 dark:text-amber-400" />
- <span className="text-bambu-gray">{t('fileManager.size')}:</span>
- <span className="text-white font-medium">{formatFileSize(stats.total_size_bytes)}</span>
- </div>
- <div className="flex items-center gap-2 text-sm sm:ml-auto">
- <span className="text-bambu-gray">{t('fileManager.free')}:</span>
- <span className={`font-medium ${isDiskSpaceLow ? 'text-amber-500' : 'text-white'}`}>
- {formatFileSize(stats.disk_free_bytes)}
- </span>
- </div>
- </div>
- )}
- {/* Main content */}
- <div className="flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0">
- {/* Mobile folder selector */}
- <div className="lg:hidden">
- <select
- value={selectedFolderId !== null ? String(selectedFolderId) : `__top:${topLevelView}`}
- onChange={(e) => {
- const v = e.target.value;
- if (v.startsWith('__top:')) {
- setSelectedFolderId(null);
- setTopLevelView(v.slice('__top:'.length) as 'internal' | 'external');
- } else {
- setSelectedFolderId(parseInt(v, 10));
- }
- }}
- 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"
- >
- <option value="__top:internal">📁 {t('fileManager.allFiles')}</option>
- {folders?.some((f) => f.is_external) && (
- <option value="__top:external">🔗 {t('fileManager.allExternal')}</option>
- )}
- {sortedFolders && (() => {
- // Flatten folder tree for mobile selector
- const flattenFolders = (items: LibraryFolderTree[], depth = 0): { id: number; name: string; fileCount: number; depth: number }[] => {
- const result: { id: number; name: string; fileCount: number; depth: number }[] = [];
- for (const item of items) {
- result.push({ id: item.id, name: item.name, fileCount: item.file_count, depth });
- if (item.children.length > 0) {
- result.push(...flattenFolders(item.children, depth + 1));
- }
- }
- return result;
- };
- return flattenFolders(sortedFolders).map((folder) => (
- <option key={folder.id} value={folder.id}>
- {'│ '.repeat(folder.depth)}📂 {folder.name} {folder.fileCount > 0 ? `(${folder.fileCount})` : ''}
- </option>
- ));
- })()}
- </select>
- </div>
- {/* Folder sidebar - resizable, hidden on mobile */}
- <div
- ref={sidebarRef}
- data-testid="folder-sidebar"
- className="hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative"
- style={{ width: `${sidebarWidth}px` }}
- >
- {/* Resize handle - drag to resize, double-click to reset */}
- <div
- 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 ${
- isResizing ? 'bg-bambu-green' : 'hover:bg-bambu-green/50'
- }`}
- onMouseDown={(e) => {
- e.preventDefault();
- setIsResizing(true);
- }}
- onDoubleClick={() => {
- setSidebarWidth(256); // Reset to default w-64
- localStorage.setItem('library-sidebar-width', '256');
- }}
- title={t('fileManager.dragToResizeTooltip')}
- >
- {/* Grip dots */}
- <div className={`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${isResizing ? 'opacity-100' : ''}`}>
- <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
- <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
- <div className="w-0.5 h-0.5 rounded-full bg-white/70" />
- </div>
- </div>
- <div className="p-3 border-b border-bambu-dark-tertiary flex items-center justify-between">
- <h2 className="text-sm font-medium text-white">{t('fileManager.folders')}</h2>
- <div className="flex items-center gap-1">
- {/* Folder tree sort (#1770). Dropdown drives the comparator;
- direction button flips asc/desc. Both persist to localStorage
- on change so the choice survives reloads. */}
- <select
- value={folderSortField}
- onChange={(e) => {
- const v = e.target.value === 'activity' ? 'activity' : 'name';
- setFolderSortField(v);
- localStorage.setItem('library-folder-sort-field', v);
- }}
- 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"
- title={t('fileManager.folderSort')}
- aria-label={t('fileManager.folderSort')}
- >
- <option value="name">{t('fileManager.folderSortByName')}</option>
- <option value="activity">{t('fileManager.folderSortByActivity')}</option>
- </select>
- <button
- onClick={() => {
- const newValue = folderSortDirection === 'asc' ? 'desc' : 'asc';
- setFolderSortDirection(newValue);
- localStorage.setItem('library-folder-sort-direction', newValue);
- }}
- className="text-bambu-gray hover:text-white hover:bg-bambu-dark p-1 rounded transition-colors"
- title={folderSortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
- aria-label={folderSortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
- >
- {folderSortDirection === 'asc' ? <SortAsc className="w-3.5 h-3.5" /> : <SortDesc className="w-3.5 h-3.5" />}
- </button>
- <button
- onClick={() => {
- const newValue = !collapseFoldersByDefault;
- setCollapseFoldersByDefault(newValue);
- localStorage.setItem('library-collapse-folders', String(newValue));
- }}
- className={`text-xs px-1.5 py-0.5 rounded transition-colors ${
- collapseFoldersByDefault
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'text-bambu-gray hover:text-white hover:bg-bambu-dark'
- }`}
- title={collapseFoldersByDefault ? t('fileManager.expandFoldersByDefault') : t('fileManager.collapseFoldersByDefault')}
- >
- {t('fileManager.collapse')}
- </button>
- <button
- onClick={() => {
- const newValue = !wrapFolderNames;
- setWrapFolderNames(newValue);
- localStorage.setItem('library-wrap-folders', String(newValue));
- }}
- className={`text-xs px-1.5 py-0.5 rounded transition-colors ${
- wrapFolderNames
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'text-bambu-gray hover:text-white hover:bg-bambu-dark'
- }`}
- title={wrapFolderNames ? t('fileManager.disableTextWrapping') : t('fileManager.enableTextWrapping')}
- >
- {t('fileManager.wrap')}
- </button>
- </div>
- </div>
- <div className="flex-1 overflow-y-auto p-2">
- {/* All Files = the user's own uploaded / managed-storage files
- only. External folders are surfaced separately below to keep
- a linked NAS from drowning the user's own uploads (#1621). */}
- <div
- className={`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${
- selectedFolderId === null && topLevelView === 'internal'
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'hover:bg-bambu-dark text-white'
- }`}
- onClick={() => {
- setSelectedFolderId(null);
- setTopLevelView('internal');
- }}
- >
- <FileBox className="w-4 h-4" />
- <span className="text-sm">{t('fileManager.allFiles')}</span>
- </div>
- {/* External (combined) — only shown when at least one external
- folder is linked. Single folder users don't need a combined
- view; clicking the individual folder is just as fast. */}
- {folders?.some((f) => f.is_external) && (
- <div
- className={`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${
- selectedFolderId === null && topLevelView === 'external'
- ? 'bg-bambu-green/20 text-bambu-green'
- : 'hover:bg-bambu-dark text-white'
- }`}
- onClick={() => {
- setSelectedFolderId(null);
- setTopLevelView('external');
- }}
- >
- <FolderSymlink className="w-4 h-4 text-purple-600 dark:text-purple-400" />
- <span className="text-sm">{t('fileManager.allExternal')}</span>
- </div>
- )}
- {/* Folder tree — re-key on the collapse toggle so flipping it
- remounts every FolderTreeItem, which re-reads defaultExpanded
- and makes the preference take effect immediately. */}
- {sortedFolders?.map((folder) => (
- <FolderTreeItem
- key={`${folder.id}-${collapseFoldersByDefault ? 'c' : 'e'}`}
- folder={folder}
- selectedFolderId={selectedFolderId}
- onSelect={setSelectedFolderId}
- onDelete={(id) => setDeleteConfirm({ type: 'folder', id })}
- onLink={setLinkFolder}
- onRename={(f) => setRenameItem({ type: 'folder', id: f.id, name: f.name })}
- onToggleShared={toggleFolderShared}
- wrapNames={wrapFolderNames}
- defaultExpanded={!collapseFoldersByDefault}
- showModified={showModified}
- hasPermission={hasPermission}
- t={t}
- />
- ))}
- </div>
- </div>
- {/* Files area + README rail (#2520 item 2). On wide screens the
- README docks as a collapsible right-hand column (rendered after
- the files column, below) so it no longer steals vertical space
- from the file list; on narrow screens it stacks above the list
- via `order-first` and the page itself scrolls. */}
- <div className="flex-1 flex flex-col lg:flex-row min-w-0 min-h-0 gap-4 lg:gap-6">
- <div className="flex-1 flex flex-col min-w-0 min-h-0">
- {/* Tag filter rail (#1268). Lists every catalog tag as a togglable
- chip — active chips are filled green and show an X, inactive
- chips are outlined and toggle ON when clicked. Clicking an active
- chip removes it from the filter. Hidden entirely when the
- catalog is empty so brand-new installs don't see a stray rail. */}
- {tagCatalog.length > 0 && (
- <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">
- <span className="text-xs text-bambu-gray font-medium shrink-0">
- {t('fileManager.tags.filterLabel')}
- </span>
- {tagCatalog.map((tg) => {
- const active = selectedTagIds.includes(tg.id);
- return (
- <button
- key={tg.id}
- type="button"
- onClick={() => toggleTagFilter(tg.id)}
- className={
- active
- ? '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'
- : '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'
- }
- title={tg.name}
- >
- <TagIcon className="w-3 h-3" />
- <span>{tg.name}</span>
- {active && <X className="w-3 h-3" />}
- </button>
- );
- })}
- {selectedTagIds.length > 0 && (
- <button
- type="button"
- onClick={() => setSelectedTagIds([])}
- className="ml-auto text-xs text-bambu-gray hover:text-white shrink-0"
- >
- {t('fileManager.tags.clearAll')}
- </button>
- )}
- </div>
- )}
- {/* External folder info bar */}
- {selectedFolder?.is_external && (
- <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">
- <FolderSymlink className="w-5 h-5 text-purple-600 dark:text-purple-400 flex-shrink-0" />
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium text-purple-700 dark:text-purple-300">{t('fileManager.externalFolder')}</span>
- {selectedFolder.external_readonly && (
- <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">
- <Lock className="w-3 h-3" />
- {t('fileManager.readOnly')}
- </span>
- )}
- </div>
- <p className="text-xs text-bambu-gray truncate font-mono" title={selectedFolder.external_path || ''}>
- {selectedFolder.external_path}
- </p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => selectedFolderId && scanExternalFolderMutation.mutate(selectedFolderId)}
- disabled={scanExternalFolderMutation.isPending}
- title={t('fileManager.scanFolder')}
- >
- {scanExternalFolderMutation.isPending ? (
- <Loader2 className="w-4 h-4 animate-spin" />
- ) : (
- <RefreshCw className="w-4 h-4" />
- )}
- <span className="ml-1.5">{t('fileManager.scanFolder')}</span>
- </Button>
- </div>
- )}
- {/* Search, Filter, Sort toolbar - sticky on mobile for easier access */}
- {files && files.length > 0 && (
- <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">
- {/* Search */}
- <div className="relative w-full sm:w-auto sm:flex-1 sm:max-w-xs">
- <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray" />
- <input
- type="text"
- placeholder={t('fileManager.searchFiles')}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- 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"
- />
- {searchExpandsSubfolders && (
- <span
- className="absolute -bottom-4 left-0 text-[10px] text-bambu-gray whitespace-nowrap"
- title={t('fileManager.searchSubfoldersHint')}
- >
- {t('fileManager.searchSubfoldersHint')}
- </span>
- )}
- </div>
- {/* Type filter */}
- <div className="flex items-center gap-2">
- <Filter className="w-4 h-4 text-bambu-gray hidden sm:block" />
- <select
- value={filterType}
- onChange={(e) => setFilterType(e.target.value)}
- 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"
- >
- <option value="all">{t('fileManager.allTypes')}</option>
- {fileTypes.map((type) => (
- <option key={type} value={type}>
- {type.toUpperCase()}
- </option>
- ))}
- </select>
- </div>
- {/* Username filter with autocomplete - only show when auth is enabled */}
- {authEnabled && (
- <div className="relative">
- <input
- type="text"
- placeholder={t('fileManager.filterByUser', { defaultValue: 'Filter by user' })}
- value={filterUsername}
- onChange={(e) => setFilterUsername(e.target.value)}
- list="usernames-list"
- 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' : ''}`}
- style={filterUsername ? { WebkitAppearance: 'none', MozAppearance: 'textfield' } : undefined}
- />
- {filterUsername && (
- <button
- onClick={() => setFilterUsername('')}
- className="absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10"
- >
- <X className="w-3 h-3" />
- </button>
- )}
- <datalist id="usernames-list">
- {users?.map((user) => (
- <option key={user.id} value={user.username} />
- ))}
- </datalist>
- </div>
- )}
- {/* Sort */}
- <div className="flex items-center gap-2">
- <select
- value={sortField}
- onChange={(e) => {
- const newField = e.target.value as SortField;
- setSortField(newField);
- localStorage.setItem('library-sort-field', newField);
- }}
- 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"
- >
- <option value="name">{t('common.name')}</option>
- <option value="date">{t('common.date')}</option>
- <option value="size">{t('fileManager.size')}</option>
- <option value="type">{t('common.type')}</option>
- <option value="prints">{t('fileManager.prints')}</option>
- </select>
- <button
- onClick={() => setSortDirection((d) => {
- const newDir = d === 'asc' ? 'desc' : 'asc';
- localStorage.setItem('library-sort-direction', newDir);
- return newDir;
- })}
- className="p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors"
- title={sortDirection === 'asc' ? t('fileManager.ascending') : t('fileManager.descending')}
- >
- {sortDirection === 'asc' ? (
- <SortAsc className="w-4 h-4 text-white" />
- ) : (
- <SortDesc className="w-4 h-4 text-white" />
- )}
- </button>
- <button
- onClick={() => setShowModified((v) => {
- const next = !v;
- localStorage.setItem('library-show-modified', String(next));
- return next;
- })}
- className={`p-1.5 rounded bg-bambu-dark border transition-colors ${
- showModified ? 'border-bambu-green text-bambu-green' : 'border-bambu-dark-tertiary text-white hover:border-bambu-green'
- }`}
- title={showModified ? t('fileManager.hideModified') : t('fileManager.showModified')}
- aria-pressed={showModified}
- >
- <CalendarClock className="w-4 h-4" />
- </button>
- </div>
- {/* Results count */}
- {(searchQuery || filterType !== 'all' || filterUsername) && (
- <span className="text-sm text-bambu-gray hidden sm:inline">
- {t('fileManager.resultsCount', { showing: filteredAndSortedFiles.length, total: files.length })}
- </span>
- )}
- </div>
- )}
- {/* Selection toolbar - sticky on mobile below search bar. It stays
- while anything is selected, even with the selected folder's own
- pane empty: a file ticked in an intermediate column of the
- columns view still needs its count and actions (#3020). */}
- {(filteredAndSortedFiles.length > 0 || selectedFiles.length > 0) && (
- <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">
- {/* Select all / Deselect all */}
- {allPaneFilesSelected ? (
- <Button
- variant="secondary"
- size="sm"
- onClick={handleDeselectAll}
- >
- <Square className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.deselectAll')}</span>
- </Button>
- ) : (
- <Button
- variant="secondary"
- size="sm"
- onClick={handleSelectAll}
- >
- <CheckSquare className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.selectAll')}</span>
- </Button>
- )}
- {selectedFiles.length > 0 && (
- <>
- <span className="text-sm text-bambu-gray ml-2">
- {t('fileManager.selected', { count: selectedFiles.length })}
- </span>
- <div className="hidden sm:block flex-1" />
- <div className="w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0">
- {previewSelection && (
- <Button
- variant="secondary"
- size="sm"
- onClick={() => openPreview(previewSelection)}
- disabled={!hasPermission('library:read')}
- title={!hasPermission('library:read') ? t('fileManager.noPermissionPreview') : undefined}
- >
- <Eye className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.preview.open')}</span>
- </Button>
- )}
- {/* Print used to disappear the moment a second sliced file was
- selected. Selecting several is now how you say "same job,
- different printers" (#671) — one queue item, whichever
- machine frees up first. */}
- {selectedSlicedFiles.length >= 1 && (
- <Button
- variant="primary"
- size="sm"
- onClick={() => setPrintFile(selectedSlicedFiles[0])}
- disabled={!hasPermission('queue:create')}
- title={!hasPermission('queue:create') ? t('fileManager.noPermissionAddToQueue') : undefined}
- >
- <Printer className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">
- {selectedSlicedFiles.length > 1
- ? t('fileManager.variants.printAlternatives', { count: selectedSlicedFiles.length })
- : t('common.print')}
- </span>
- </Button>
- )}
- {selectedSlicedFiles.length >= 2 && !selectedSlicedFiles.some(f => f.variant_group_id) && (
- <Button
- variant="secondary"
- size="sm"
- onClick={() => groupAsVersionsMutation.mutate(selectedSlicedFiles.map(f => f.id))}
- disabled={
- groupAsVersionsMutation.isPending
- || !hasAnyPermission('library:update_own', 'library:update_all')
- }
- title={t('fileManager.variants.groupTooltip')}
- >
- <Layers className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.variants.groupAction')}</span>
- </Button>
- )}
- {selectedStlFiles.length >= 1 && (
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowCombineModal(true)}
- disabled={!hasPermission('library:upload')}
- title={t('fileManager.combine.tooltip')}
- >
- <Combine className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.combine.action')}</span>
- </Button>
- )}
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowMoveModal(true)}
- disabled={!hasAnyPermission('library:update_own', 'library:update_all')}
- title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.noPermissionMoveFiles') : undefined}
- >
- <MoveRight className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('common.move')}</span>
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => setShowBulkTagsModal(true)}
- disabled={!hasAnyPermission('library:update_own', 'library:update_all')}
- title={!hasAnyPermission('library:update_own', 'library:update_all') ? t('fileManager.tags.noPermission') : t('fileManager.tags.bulkTooltip')}
- >
- <TagIcon className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('fileManager.tags.tagAction')}</span>
- </Button>
- <Button
- variant="danger"
- size="sm"
- onClick={() => {
- if (selectedFiles.length === 1) {
- setDeleteConfirm({ type: 'file', id: selectedFiles[0] });
- } else {
- setDeleteConfirm({ type: 'bulk', id: 0, count: selectedFiles.length });
- }
- }}
- disabled={!hasAnyPermission('library:delete_own', 'library:delete_all')}
- title={!hasAnyPermission('library:delete_own', 'library:delete_all') ? t('fileManager.noPermissionDeleteFiles') : undefined}
- >
- <Trash2 className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('common.delete')}</span>
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={handleDeselectAll}
- >
- <X className="w-4 h-4 sm:mr-1" />
- <span className="hidden sm:inline">{t('common.clear')}</span>
- </Button>
- </div>
- </>
- )}
- </div>
- )}
- {/* File grid/list. The columns view is exempt from the full-pane
- loading swap: every keyboard descent into an uncached folder
- flips filesLoading for one round-trip, and replacing the pane
- would strip its tabindex mid-keystroke — the focus-fixup rule
- then drops focus to <body> and kills keyboard navigation. The
- pane stays mounted and only its files pane shows the spinner. */}
- {isLoading && viewMode !== 'columns' ? (
- <div className="flex-1 flex items-center justify-center">
- <div className="flex flex-col items-center gap-3">
- <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
- <p className="text-sm text-bambu-gray">{t('fileManager.loadingFiles')}</p>
- </div>
- </div>
- ) : viewMode === 'columns' ? (
- /* Miller columns (macOS-Finder style): one column per folder level,
- the rightmost pane lists the selected folder's files. Unlike the
- grid/list branches this renders even for an "empty" folder — an
- empty files pane next to navigable folder columns is the whole
- point of the view. */
- <div
- ref={columnsViewRef}
- tabIndex={0}
- aria-label={t('fileManager.columnsView')}
- onKeyDown={handleColumnsKeyDown}
- 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"
- data-testid="columns-view"
- >
- <div className="h-full min-h-[16rem] flex divide-x divide-bambu-dark-tertiary">
- {!columnsFilterActive && folderColumns.map((col) => {
- const level = columnFiles.get(col.key);
- // A column carrying file rows needs the room the files pane
- // has: checkbox, thumbnail and the seven-icon action strip
- // leave nothing for the name at the folder-only width. A
- // column that only lists folders keeps that narrow width.
- const wide = Boolean(level && (level.loading || level.files.length > 0));
- return (
- <div
- key={col.key}
- data-testid={`columns-level-${col.key}`}
- className={`${wide ? 'w-[26rem]' : 'w-64'} flex-shrink-0 overflow-y-auto py-1`}
- >
- {col.items.map((folder) => {
- const isSelectedFolder = selectedFolderId === folder.id;
- return (
- /* The row is a div, not the button itself: the kebab
- is a button of its own and buttons don't nest. */
- <div
- key={folder.id}
- data-folder-id={folder.id}
- className={`group flex items-center pr-1.5 transition-colors ${
- col.activeId === folder.id
- ? 'bg-bambu-green/20 text-bambu-green'
- : isSelectedFolder
- ? 'bg-bambu-green/10 text-white'
- : 'text-white hover:bg-bambu-dark'
- }`}
- >
- <button
- type="button"
- // Roving tabindex: the pane is the keyboard surface
- // (arrows walk the folders), so Tab skips the names
- // and goes straight to the selected row's kebab and
- // on to the focused file's actions.
- tabIndex={-1}
- onClick={() => {
- // Clear the file focus here too: re-clicking the
- // already-selected folder bails out of the state
- // update, so the clearing effect would not run and
- // the arrow keys would stay stuck in the files pane.
- setColumnsFocusedFileId(null);
- setSelectedFolderId(folder.id);
- }}
- className="flex-1 min-w-0 flex items-center gap-2 pl-3 pr-1 py-2.5 text-left text-sm"
- title={folder.name}
- >
- {folder.is_external ? (
- <FolderSymlink className="w-5 h-5 flex-shrink-0 text-purple-600 dark:text-purple-400" />
- ) : (
- <FolderOpen className="w-5 h-5 flex-shrink-0 text-bambu-green" />
- )}
- <span className="flex-1 truncate">{folder.name}</span>
- {(folder.project_id || folder.archive_id) && (
- <Link2 className="w-3.5 h-3.5 flex-shrink-0 text-blue-700 dark:text-blue-400" />
- )}
- {folder.shared && (
- <span title={t('fileManager.sharedFolder')}>
- <Users className="w-3.5 h-3.5 flex-shrink-0 text-bambu-gray" />
- </span>
- )}
- {folder.is_external && folder.external_readonly && (
- <Lock className="w-3.5 h-3.5 flex-shrink-0 text-amber-600 dark:text-amber-400" />
- )}
- {folder.file_count > 0 && (
- <span className="text-xs text-bambu-gray flex-shrink-0">{folder.file_count}</span>
- )}
- {folder.children.length > 0 && (
- <ChevronRightIcon className="w-4 h-4 flex-shrink-0 text-bambu-gray" />
- )}
- </button>
- {/* Kebab: hover-revealed with a mouse, always there
- without one (#2865) and on the selected row. */}
- <FolderActionsMenu
- folder={folder}
- onDelete={(id) => setDeleteConfirm({ type: 'folder', id })}
- onLink={setLinkFolder}
- onRename={(f) => setRenameItem({ type: 'folder', id: f.id, name: f.name })}
- onToggleShared={toggleFolderShared}
- hasPermission={hasPermission}
- revealOnHover={!isSelectedFolder}
- tabIndex={isSelectedFolder ? 0 : -1}
- t={t}
- />
- </div>
- );
- })}
- {level?.loading && (
- <div className="px-3 py-2 text-sm text-bambu-gray" aria-hidden="true">…</div>
- )}
- {level && !level.loading && level.files.map((file) => (
- <ColumnFileRow
- key={file.id}
- file={file}
- isSelected={selectedFiles.includes(file.id)}
- isHighlighted={highlightedFileId === file.id}
- isFocused={columnsFocusedFileId === file.id}
- showModified={showModified}
- thumbnailVersion={thumbnailVersions[file.id]}
- onSelect={(f) => {
- // Focusing a file in an intermediate column must not
- // move the folder selection out from under it.
- setColumnsFocusedFileId(f.id);
- handleFileSelect(f.id);
- }}
- onOpen={openPreview}
- actionProps={fileActionProps}
- t={t}
- />
- ))}
- </div>
- );
- })}
- {/* Files pane — still the selected folder's contents, so a
- leaf folder's column layout is exactly what it was. */}
- <div className="flex-1 min-w-[28rem] overflow-y-auto py-1" data-testid="columns-files-pane">
- {filesLoading ? (
- <div className="h-full flex items-center justify-center">
- <Loader2 className="w-5 h-5 animate-spin text-bambu-green" />
- </div>
- ) : filteredAndSortedFiles.length === 0 ? (
- <div className="h-full flex items-center justify-center px-4 text-sm text-bambu-gray text-center">
- {(files?.length ?? 0) > 0
- ? t('fileManager.noMatchingFiles')
- : selectedFolderId !== null
- ? t('fileManager.folderIsEmpty')
- // At the root the pane lists only the files in no
- // folder, so with folders beside it "No files yet"
- // would be wrong (and an external bucket never has
- // unfiled files at all).
- : paneRootOnly && folderColumns[0].items.length > 0
- ? t('fileManager.noFilesOutsideFolders')
- : topLevelView === 'external'
- ? t('fileManager.externalIsEmpty')
- : t('fileManager.noFilesYet')}
- </div>
- ) : (
- filteredAndSortedFiles.map((file) => (
- <ColumnFileRow
- key={file.id}
- file={file}
- isSelected={selectedFiles.includes(file.id)}
- isHighlighted={highlightedFileId === file.id}
- isFocused={columnsFocusedFileId === file.id}
- showModified={showModified}
- thumbnailVersion={thumbnailVersions[file.id]}
- onSelect={(f) => {
- setColumnsFocusedFileId(f.id);
- handleFileSelect(f.id);
- }}
- onOpen={openPreview}
- actionProps={fileActionProps}
- t={t}
- />
- ))
- )}
- </div>
- </div>
- </div>
- ) : files?.length === 0 ? (
- <div className="flex-1 flex flex-col items-center justify-center">
- <div className="p-4 bg-bambu-dark rounded-2xl mb-4">
- <FileBox className="w-12 h-12 text-bambu-gray/50" />
- </div>
- <h3 className="text-lg font-medium text-white mb-2">
- {selectedFolderId !== null
- ? t('fileManager.folderIsEmpty')
- : topLevelView === 'external'
- ? t('fileManager.externalIsEmpty')
- : t('fileManager.noFilesYet')}
- </h3>
- <p className="text-bambu-gray text-center max-w-md mb-6">
- {selectedFolderId !== null
- ? t('fileManager.folderEmptyDescription')
- : topLevelView === 'external'
- ? t('fileManager.externalEmptyDescription')
- : t('fileManager.noFilesDescription')}
- </p>
- <Button
- onClick={() => setShowUploadModal(true)}
- disabled={!canUpload}
- title={!hasPermission('library:upload') ? t('fileManager.noPermissionUpload') : addDisabledTitle}
- >
- <Plus className="w-4 h-4 mr-2" />
- {t('fileManager.uploadFiles')}
- </Button>
- </div>
- ) : filteredAndSortedFiles.length === 0 ? (
- <div className="flex-1 flex flex-col items-center justify-center">
- <div className="p-4 bg-bambu-dark rounded-2xl mb-4">
- <Search className="w-12 h-12 text-bambu-gray/50" />
- </div>
- <h3 className="text-lg font-medium text-white mb-2">{t('fileManager.noMatchingFiles')}</h3>
- <p className="text-bambu-gray text-center max-w-md mb-6">
- {t('fileManager.noMatchingFilesDescription')}
- </p>
- <Button variant="secondary" onClick={() => { setSearchQuery(''); setFilterType('all'); }}>
- {t('fileManager.clearFilters')}
- </Button>
- </div>
- ) : viewMode === 'grid' ? (
- <div className="flex-1 lg:overflow-y-auto">
- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
- {filteredAndSortedFiles.map((file) => (
- <FileCard
- key={file.id}
- file={file}
- isSelected={selectedFiles.includes(file.id)}
- isHighlighted={highlightedFileId === file.id}
- t={t}
- onSelect={handleFileSelect}
- onDelete={(id) => setDeleteConfirm({ type: 'file', id })}
- onDownload={handleDownload}
- onPrint={setPrintFile}
- onSlice={setSliceFile}
- onOpenInSlicer={handleOpenInSlicer}
- desktopSlicer={preferredSlicer}
- onRunPipeline={setRunPipelineFile}
- useSlicerApi={settings?.use_slicer_api ?? false}
- canSlice={canSlice()}
- onPreview={openPreview}
- onRename={(f) => setRenameItem({ type: 'file', id: f.id, name: f.filename })}
- onDetails={setDetailsFile}
- onGenerateThumbnail={(f) => singleThumbnailMutation.mutate(f.id)}
- onTagClick={toggleTagFilter}
- thumbnailVersion={thumbnailVersions[file.id]}
- hasPermission={hasPermission}
- canModify={canModify}
- authEnabled={authEnabled}
- showModified={showModified}
- />
- ))}
- </div>
- </div>
- ) : (
- <div className="flex-1 lg:overflow-y-auto">
- {/* The wrapper has overflow-x-auto so a narrow viewport scrolls
- horizontally instead of clipping the actions column off the
- right edge. The previous `overflow-hidden` was there for the
- rounded corners but also swallowed any content the actions
- column couldn't fit (#1325 follow-up reported in chat). */}
- <div className="bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-x-auto">
- {/* List header - hidden on mobile, show simplified on small screens.
- Trailing actions column is fixed at 220px (sliced 3MF = 7 icons
- ~220px). It used to be `min-content`, but header + body are sibling
- grids that compute `min-content` independently — the header's empty
- trailing div resolved to 0px, leaving body columns shifted left of
- their headers. Fixed width keeps header and body in lockstep. */}
- <div
- data-testid="file-list-grid-header"
- 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`}
- >
- <div className="w-6" />
- <div>{t('common.name')}</div>
- {authEnabled && <div>{t('fileManager.uploadedBy', { defaultValue: 'Uploaded By' })}</div>}
- <div>{t('common.type')}</div>
- <div>{t('fileManager.size')}</div>
- <div>{t('fileManager.prints')}</div>
- <div>{t('fileManager.tags.title')}</div>
- <div />
- </div>
- {/* List rows */}
- {filteredAndSortedFiles.map((file) => (
- <div
- key={file.id}
- data-testid="file-list-grid-row"
- data-file-id={file.id}
- style={highlightedFileId === file.id ? HIGHLIGHT_ROW_STYLE : undefined}
- 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 ${
- selectedFiles.includes(file.id) ? 'bg-bambu-green/10' : ''
- }`}
- onClick={() => handleFileSelect(file.id)}
- // Double-click opens the preview (#2976), as in the grid.
- onDoubleClick={() => openPreview(file)}
- >
- {/* Checkbox */}
- <div className={`w-5 h-5 rounded border-2 flex items-center justify-center ${
- selectedFiles.includes(file.id)
- ? 'bg-bambu-green border-bambu-green'
- : 'border-bambu-gray/50'
- }`}>
- {selectedFiles.includes(file.id) && <div className="w-2 h-2 bg-white rounded-sm" />}
- </div>
- {/* Name with thumbnail */}
- <div className="flex items-center gap-3 min-w-0">
- <div className="relative group/thumb">
- <div className="w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden">
- {file.thumbnail_path ? (
- <img
- src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersions[file.id] ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersions[file.id]}`) : ''}`}
- loading="lazy"
- alt=""
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="w-full h-full flex items-center justify-center">
- <FileTypePlaceholderIcon fileType={file.file_type} className="w-5 h-5 text-bambu-gray/50" />
- </div>
- )}
- </div>
- {/* Hover preview */}
- {file.thumbnail_path && (
- <div className="absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block">
- <div className="w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden">
- <img
- src={`${api.getLibraryFileThumbnailUrl(file.id)}${thumbnailVersions[file.id] ? ((api.getLibraryFileThumbnailUrl(file.id).includes('?') ? '&' : '?') + `v=${thumbnailVersions[file.id]}`) : ''}`}
- loading="lazy"
- alt={file.filename}
- className="w-full h-full object-contain"
- />
- </div>
- </div>
- )}
- </div>
- <div className="min-w-0">
- <div className="flex items-center gap-1.5 min-w-0">
- <span className="text-sm text-white truncate">{file.print_name || file.filename}</span>
- {/* Metadata indicators (#3077), same set as the card. */}
- {file.external_url && (
- <a
- href={file.external_url}
- target="_blank"
- rel="noopener noreferrer"
- {...stopRowActivation}
- className="flex-shrink-0 text-bambu-gray hover:text-bambu-green"
- title={t('fileManager.details.openLink')}
- aria-label={t('fileManager.details.openLink')}
- >
- <Globe className="w-3.5 h-3.5" />
- </a>
- )}
- {file.has_notes && (
- <span className="flex-shrink-0 text-bambu-gray" title={t('fileManager.details.hasNotes')} aria-label={t('fileManager.details.hasNotes')}>
- <StickyNote className="w-3.5 h-3.5" />
- </span>
- )}
- {(file.photo_count ?? 0) > 0 && (
- <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 })}>
- <Camera className="w-3.5 h-3.5" />
- {file.photo_count}
- </span>
- )}
- </div>
- {/* #2680: last-modified date under the name, toggled from
- the toolbar. Real on-disk mtime when known, else created_at. */}
- {showModified && (
- <div className="text-xs text-bambu-gray flex items-center gap-1 mt-0.5" title={t('fileManager.lastModified')}>
- <CalendarClock className="w-3 h-3 flex-shrink-0" />
- <span className="truncate">{formatDate(file.fs_modified_at ?? file.created_at)}</span>
- </div>
- )}
- </div>
- </div>
- {/* Uploaded By - only show when auth is enabled */}
- {authEnabled && (
- <div className="text-sm text-bambu-gray flex items-center gap-1">
- {file.created_by_username ? (
- <>
- <User className="w-3 h-3" />
- <span className="truncate">{file.created_by_username}</span>
- </>
- ) : (
- '-'
- )}
- </div>
- )}
- {/* Type */}
- <div>
- <span className={`text-xs px-1.5 py-0.5 rounded font-medium ${fileTypeBadgeClass(file.file_type)}`}>
- {file.file_type.toUpperCase()}
- </span>
- </div>
- {/* Size */}
- <div className="text-sm text-bambu-gray">{formatFileSize(file.file_size)}</div>
- {/* Prints */}
- <div className="text-sm text-bambu-gray">{file.print_count > 0 ? `${file.print_count}x` : '-'}</div>
- {/* Tags (#1268) — clickable chips push into the active
- filter; minmax(96px,200px) on the column lets the cell
- shrink/wrap on narrow viewports, and the 96px floor
- keeps chips readable once the wrapper scrolls (#3105). */}
- <div className="min-w-0" {...stopRowActivation}>
- {!file.tags || file.tags.length === 0 ? (
- <span className="text-xs text-bambu-gray/50">-</span>
- ) : (
- <div className="flex flex-wrap gap-1">
- {file.tags.map((tg) => (
- <button
- key={tg.id}
- type="button"
- onClick={() => toggleTagFilter(tg.id)}
- 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"
- title={tg.name}
- >
- <TagIcon className="w-2.5 h-2.5 flex-shrink-0" />
- <span className="truncate">{tg.name}</span>
- </button>
- ))}
- </div>
- )}
- </div>
- {/* Actions */}
- <FileActionStrip file={file} {...fileActionProps} />
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- {/* README rail — collapsible right column on lg+, stacks on top
- on mobile. See the files-area wrapper comment above (#2520). */}
- {selectedFolderId !== null && <FolderReadmePanel folderId={selectedFolderId} />}
- </div>
- </div>
- {/* Modals */}
- {showNewFolderModal && (
- <NewFolderModal
- parentId={selectedFolderId}
- onClose={() => setShowNewFolderModal(false)}
- onSave={(data) => createFolderMutation.mutate(data)}
- isLoading={createFolderMutation.isPending}
- t={t}
- />
- )}
- {showExternalFolderModal && (
- <ExternalFolderModal
- onClose={() => setShowExternalFolderModal(false)}
- onSave={(data) => createExternalFolderMutation.mutate(data)}
- isLoading={createExternalFolderMutation.isPending}
- t={t}
- />
- )}
- {showMoveModal && folders && (
- <MoveFilesModal
- folders={folders}
- selectedFiles={selectedFiles}
- currentFolderId={selectedFolderId}
- onClose={() => setShowMoveModal(false)}
- onMove={(folderId) => moveFilesMutation.mutate({ fileIds: selectedFiles, folderId })}
- isLoading={moveFilesMutation.isPending}
- t={t}
- />
- )}
- {showUploadModal && (
- <FileUploadModal
- folderId={selectedFolderId}
- onClose={() => {
- setShowUploadModal(false);
- setDroppedFiles([]);
- }}
- onUploadComplete={handleUploadComplete}
- initialFiles={droppedFiles.length > 0 ? droppedFiles : undefined}
- />
- )}
- {showPurgeModal && (
- <PurgeOldFilesModal onClose={() => setShowPurgeModal(false)} />
- )}
- <LibraryTagsModal
- open={showTagsModal}
- onClose={() => setShowTagsModal(false)}
- onPickTag={(tagId) => {
- if (!selectedTagIds.includes(tagId)) {
- setSelectedTagIds((prev) => [...prev, tagId]);
- }
- }}
- />
- <BulkTagsPickerModal
- open={showBulkTagsModal}
- fileIds={selectedFiles}
- onClose={() => setShowBulkTagsModal(false)}
- />
- {linkFolder && (
- <LinkFolderModal
- folder={linkFolder}
- onClose={() => setLinkFolder(null)}
- onLink={(data) => updateFolderMutation.mutate({ id: linkFolder.id, data })}
- isLoading={updateFolderMutation.isPending}
- t={t}
- />
- )}
- {deleteConfirm && (
- <ConfirmModal
- title={
- deleteConfirm.type === 'folder'
- ? t('fileManager.deleteFolder')
- : deleteConfirm.type === 'bulk'
- ? t('fileManager.deleteFilesCount', { count: deleteConfirm.count })
- : t('fileManager.deleteFile')
- }
- message={
- deleteConfirm.type === 'folder'
- ? t('fileManager.deleteFolderConfirm')
- : deleteConfirm.type === 'bulk'
- ? t('fileManager.deleteFilesConfirm', { count: deleteConfirm.count })
- : t('fileManager.deleteFileConfirm')
- }
- confirmText={t('common.delete')}
- variant="danger"
- isLoading={isDeleting}
- loadingText={t('fileManager.deleting')}
- onConfirm={handleDeleteConfirm}
- onCancel={() => setDeleteConfirm(null)}
- />
- )}
- {/* Held back until the variant group has loaded. The modal reads its
- candidate list once, on mount, so opening before the group arrives
- would show a single-file print for a file that has alternatives. */}
- {printFile && (!printFile.variant_group_id || printFileGroup !== undefined) && (
- <PrintModal
- mode="create"
- libraryFileId={printVariantFiles?.[0]?.id ?? printFile.id}
- variantFiles={printVariantFiles}
- // Naming a cross-model job after one of its files reads as though the
- // others aren't part of it.
- archiveName={
- printVariantFiles && printVariantFiles.length > 1
- ? `${printVariantFiles[0].filename} ${t('common.plusNMore', { count: printVariantFiles.length - 1 })}`
- : printFile.print_name || printFile.filename
- }
- onClose={() => setPrintFile(null)}
- onSuccess={() => {
- setPrintFile(null);
- setSelectedFiles([]);
- queryClient.invalidateQueries({ queryKey: ['library-files'] });
- queryClient.invalidateQueries({ queryKey: ['queue'] });
- queryClient.invalidateQueries({ queryKey: ['archives'] });
- }}
- />
- )}
- {sliceFile && (
- <SliceModal
- source={{ kind: 'libraryFile', id: sliceFile.id, filename: sliceFile.filename }}
- onClose={() => setSliceFile(null)}
- />
- )}
- {showCombineModal && selectedStlFiles.length > 0 && (
- <CombineFilesModal
- files={selectedStlFiles}
- folderId={selectedFolderId}
- // canSlice() also covers the desktop-slicer handoff; "open the
- // slicer next" means the in-app SliceModal, so the sidecar must be on.
- canSlice={!!settings?.use_slicer_api && canSlice()}
- onClose={() => setShowCombineModal(false)}
- onCombined={(result, sliceNext) => {
- setShowCombineModal(false);
- setSelectedFiles([]);
- if (sliceNext) setSliceCombined({ id: result.id, filename: result.filename });
- }}
- />
- )}
- {sliceCombined && (
- <SliceModal
- source={{ kind: 'libraryFile', id: sliceCombined.id, filename: sliceCombined.filename }}
- onClose={() => setSliceCombined(null)}
- defaultAutoArrange
- />
- )}
- {runPipelineFile && (
- <RunWithPipelineModal
- source={{ kind: 'libraryFile', id: runPipelineFile.id, filename: runPipelineFile.filename }}
- onClose={() => setRunPipelineFile(null)}
- />
- )}
- {viewerFile && (
- <ModelViewerModal
- libraryFileId={viewerFile.id}
- title={viewerFile.print_name || viewerFile.filename}
- fileType={viewerFile.file_type}
- onClose={() => setViewerFile(null)}
- // STEP has no server-side renderer; persist the first client render
- // as the grid thumbnail (#2976).
- onSnapshot={isStepType(viewerFile.file_type) ? previewSnapshotHandler(viewerFile) : undefined}
- onSliceWithBambuddy={
- // Only offer in-app slicing on files the SliceModal can actually
- // handle (matches the file-row Cog visibility check at :2127).
- isSliceableLibraryFile(viewerFile, true, preferredSlicer) && hasPermission('library:upload')
- ? () => {
- const f = viewerFile;
- setViewerFile(null);
- setSliceFile(f);
- }
- : undefined
- }
- />
- )}
- {(pdfPreviewFile || sheetPreviewFile || imagePreviewFile) && (
- <Suspense fallback={null}>
- {pdfPreviewFile && (
- <PdfPreviewModal
- libraryFileId={pdfPreviewFile.id}
- filename={pdfPreviewFile.print_name || pdfPreviewFile.filename}
- fileSize={pdfPreviewFile.file_size}
- onClose={() => setPdfPreviewFile(null)}
- onSnapshot={previewSnapshotHandler(pdfPreviewFile)}
- />
- )}
- {sheetPreviewFile && (
- <SpreadsheetPreviewModal
- libraryFileId={sheetPreviewFile.id}
- filename={sheetPreviewFile.print_name || sheetPreviewFile.filename}
- fileType={sheetPreviewFile.file_type}
- fileSize={sheetPreviewFile.file_size}
- onClose={() => setSheetPreviewFile(null)}
- onSnapshot={previewSnapshotHandler(sheetPreviewFile)}
- />
- )}
- {imagePreviewFile && (
- <ImagePreviewModal
- libraryFileId={imagePreviewFile.id}
- filename={imagePreviewFile.print_name || imagePreviewFile.filename}
- fileSize={imagePreviewFile.file_size}
- onClose={() => setImagePreviewFile(null)}
- />
- )}
- </Suspense>
- )}
- {detailsFile && (
- <LibraryFileDetailsModal
- file={detailsFile}
- canEdit={canModify('library', 'update', detailsFile.created_by_id)}
- onClose={() => setDetailsFile(null)}
- />
- )}
- {renameItem && (
- <RenameModal
- type={renameItem.type}
- currentName={renameItem.name}
- onClose={() => setRenameItem(null)}
- onSave={(newName) => {
- if (renameItem.type === 'file') {
- renameFileMutation.mutate({ id: renameItem.id, filename: newName });
- } else {
- renameFolderMutation.mutate({ id: renameItem.id, name: newName });
- }
- }}
- isLoading={renameFileMutation.isPending || renameFolderMutation.isPending}
- t={t}
- />
- )}
- </div>
- );
- }
|