Reworking FileBrowser selection using context to reduce prop drilling.

This commit is contained in:
Roland 2026-02-03 16:36:44 -07:00
parent 0e6dcd280d
commit 98ea05b689
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
6 changed files with 134 additions and 45 deletions

View file

@ -66,8 +66,8 @@ export function splitPathParentAndName(path) {
return [path.substring(0, slashIndex), path.substring(slashIndex + 1, path.length)];
}
function Folder({folder, onFolderClick, sortData, selectedPaths, onFileClick, onSelect, disabled}) {
const {handleDragStart, handleDragMove, getDragState} = useContext(DragSelectionContext);
function Folder({folder, onFolderClick, sortData, onFileClick, disabled, loadingFolders}) {
const {handleDragStart, handleDragMove, getDragState, shouldAllowClick, selectedPaths, onSelect} = useContext(DragSelectionContext);
// Creates a single table row for a folder, or a row for itself and indented rows for its children.
let {path, children, is_empty} = folder;
const ignored = useIsIgnoredDirectory(path);
@ -79,9 +79,13 @@ function Folder({folder, onFolderClick, sortData, selectedPaths, onFileClick, on
const showAsSelected = (isInSelectedPaths && !isDragDeselecting) || isDragSelecting;
// Visual highlight class
const dragClass = isDragSelecting ? 'drag-selecting' : (isDragDeselecting ? 'drag-deselecting' : '');
const isLoading = loadingFolders && loadingFolders.has(path);
const depth = (path.match(/\//g) || []).length;
const f = <TableRow
key={path}
disabled={disabled}
disabled={isLoading || disabled}
className={dragClass}
onMouseDown={(e) => handleDragStart(path, e)}
onMouseEnter={() => handleDragMove(path)}
@ -89,7 +93,7 @@ function Folder({folder, onFolderClick, sortData, selectedPaths, onFileClick, on
<TableCell collapsing>
<Checkbox checked={showAsSelected} onChange={() => onSelect(folder['path'])}/>
</TableCell>
<TableCell onClick={() => onFolderClick(path)} className='file-path' colSpan={2} disabled={is_empty}>
<TableCell onClick={() => shouldAllowClick() && onFolderClick(path)} className='file-path' colSpan={2} disabled={is_empty}>
{depthIndentation(pathWithNoTrailingSlash)}
{is_empty ? <Icon name='folder outline'/> : <Icon name='folder'/>}
{ignored && <Icon name='eye slash' color='red'/>}
@ -104,21 +108,27 @@ function Folder({folder, onFolderClick, sortData, selectedPaths, onFileClick, on
childPaths = [...childPaths,
<InlineErrorBoundary key={k}>
<Path path={p} onFolderClick={onFolderClick} sortData={sortData} onFileClick={onFileClick}
selectedPaths={selectedPaths} onSelect={onSelect} disabled={disabled}/>
disabled={disabled} loadingFolders={loadingFolders}/>
</InlineErrorBoundary>];
});
return <React.Fragment>
{f}
{childPaths}
</React.Fragment>
} else if (isLoading) {
// Folder is loading - show skeleton rows
return <React.Fragment>
{f}
<SkeletonFileRow depth={depth}/>
</React.Fragment>;
} else {
// Folder has no children.
return f;
}
}
function File({file, onFileClick, selectedPaths, onSelect, disabled}) {
const {handleDragStart, handleDragMove, getDragState} = useContext(DragSelectionContext);
function File({file, onFileClick, disabled}) {
const {handleDragStart, handleDragMove, getDragState, shouldAllowClick, selectedPaths, onSelect} = useContext(DragSelectionContext);
const {path, size} = file;
const isInSelectedPaths = selectedPaths.indexOf(path) >= 0;
const {isDragSelecting, isDragDeselecting} = getDragState(path, isInSelectedPaths);
@ -136,7 +146,7 @@ function File({file, onFileClick, selectedPaths, onSelect, disabled}) {
<TableCell collapsing>
<Checkbox checked={showAsSelected} onChange={() => onSelect(path)}/>
</TableCell>
<TableCell onClick={() => onFileClick(file)} className='file-path'>
<TableCell onClick={() => shouldAllowClick() && onFileClick(file)} className='file-path'>
{depthIndentation(path)}
<FileRowTagIcon file={file}/>
{/*null size to make icon the correct size*/}
@ -149,28 +159,42 @@ function File({file, onFileClick, selectedPaths, onSelect, disabled}) {
</TableRow>
}
function Path({path, onFolderClick, onFileClick, sortData, selectedPaths, onSelect, disabled}) {
function Path({path, onFolderClick, onFileClick, sortData, disabled, loadingFolders}) {
if (path['path'].endsWith('/')) {
return <Folder
folder={path}
onFolderClick={onFolderClick}
sortData={sortData}
selectedPaths={selectedPaths}
onSelect={onSelect}
onFileClick={onFileClick}
disabled={disabled}
loadingFolders={loadingFolders}
/>
} else {
return <File
file={path}
onFileClick={onFileClick}
selectedPaths={selectedPaths}
onSelect={onSelect}
disabled={disabled}
/>
}
}
function SkeletonFileRow({depth}) {
const indentation = '\xa0\xa0\xa0\xa0'.repeat(depth);
return (
<TableRow>
<TableCell collapsing>
<Checkbox disabled/>
</TableCell>
<TableCell className='file-path' colSpan={2}>
{indentation}
<Placeholder style={{display: 'inline-block', width: '200px', marginLeft: '0.5em'}}>
<PlaceholderLine/>
</Placeholder>
</TableCell>
</TableRow>
);
}
export function FileBrowser() {
const [selectedPaths, setSelectedPaths] = React.useState([]);
const [renameOpen, setRenameOpen] = React.useState(false);
@ -180,6 +204,8 @@ export function FileBrowser() {
const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
const [uploadOpen, setUploadOpen] = React.useState(false);
const [pending, setPending] = React.useState(false);
// Tracks which folders are currently loading their children
const [loadingFolders, setLoadingFolders] = React.useState(new Set());
// Only true if only one path is selected, and it is a directory.
const [singleDirectorySelected, setSingleDirectorySelected] = React.useState(false);
// Only true if single directory is selected, and it is in settings['ignored_directories']
@ -256,23 +282,18 @@ export function FileBrowser() {
}
}, [browseFiles]);
// Clear loading states when file data updates
useEffect(() => {
if (loadingFolders.size > 0) {
setLoadingFolders(new Set());
}
}, [browseFiles]);
const onIgnore = async () => {
setIgnoreDirectoryOpen(false);
await fetchSettings();
}
const onSelect = (path) => {
let newSelectedPaths;
// Select or deselect if the paths was previously selected.
if (selectedPathsCount && selectedPaths.indexOf(path) >= 0) {
newSelectedPaths = selectedPaths.filter(i => i !== path);
} else {
newSelectedPaths = [...selectedPaths, path];
}
setSelectedPaths(newSelectedPaths);
console.debug('selectedPaths', newSelectedPaths);
}
const onDelete = async () => {
await deleteFile(selectedPaths);
// Remove deleted directories from openFolders to prevent fetching non-existent directories
@ -406,6 +427,8 @@ export function FileBrowser() {
} else {
// Add the new folder to the opened folders.
newFolders = [...openFolders, folder];
// Mark folder as loading so skeleton rows show
setLoadingFolders(prev => new Set([...prev, folder]));
// If folder is selected, mark it for auto-selection of its children
if (selectedPaths.includes(folder)) {
pendingAutoSelectRef.current = folder;
@ -435,22 +458,21 @@ export function FileBrowser() {
headers={headers}
onFolderClick={onFolderClick}
setPreviewFile={setPreviewFile}
selectedPaths={selectedPaths}
onSelect={onSelect}
pending={pending}
loadingFolders={loadingFolders}
/>
{footer}
</DragSelectionProvider>
}
function FileBrowserContent({browseFiles, headers, onFolderClick, setPreviewFile, selectedPaths, onSelect, pending}) {
function FileBrowserContent({browseFiles, headers, onFolderClick, setPreviewFile, pending, loadingFolders}) {
const {isDragging} = useContext(DragSelectionContext);
const containerClassName = isDragging ? 'file-browser-dragging' : '';
return (
<div style={{marginBottom: '4em'}} className={containerClassName}>
<SortableTable
tableProps={{unstackable: true}}
tableProps={{unstackable: true, selectable: true, striped: true}}
data={browseFiles}
tableHeaders={headers}
defaultSortColumn='path'
@ -462,9 +484,8 @@ function FileBrowserContent({browseFiles, headers, onFolderClick, setPreviewFile
onFolderClick={onFolderClick}
onFileClick={(file) => setPreviewFile(file)}
sortData={sortData}
selectedPaths={selectedPaths}
onSelect={onSelect}
disabled={pending}
loadingFolders={loadingFolders}
/>
)}
/>

View file

@ -88,7 +88,7 @@ function DownloadMessage() {
const ViewerMessage = () => {
return <HandPointMessage>
<p>You can view your Map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
<p>You can view the Map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
}

View file

@ -13,6 +13,7 @@ export const FILES_MEDIA_URI = `https://${window.location.hostname}:${port}/medi
export const MAP_VIEWER_URI = `https://${window.location.hostname}:8084`;
export const ZIM_VIEWER_URI = `https://${window.location.hostname}:8085`;
export const HELP_VIEWER_URI = `https://${window.location.hostname}:8086`;
export const CONTROLLER_URI = `http://${window.location.hostname}:8087`; // no https
export const API_ARCHIVE_UPLOAD_URI = `http://${window.location.hostname}:8081/api/archive/upload`;
export let defaultFileOrder = '-published_datetime'; // Most recently published files first.
@ -130,4 +131,4 @@ export const Downloaders = {
ScrapeHtml: 'scrape_html',
Video: 'video',
VideoChannel: 'video_channel',
};
};

View file

@ -1,7 +1,7 @@
import React from 'react';
import {Checkbox, Container, Dropdown, Form, Icon, Input} from "semantic-ui-react";
import {Button, Confirm, Header, Loader, Modal, Segment, Table} from "../Theme";
import {APIButton, HotspotToggle, ThrottleToggle, Toggle,} from "../Common";
import {APIButton, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle,} from "../Common";
import {useDockerized} from "../../hooks/customHooks";
import {Media} from "../../contexts/contexts";
import {
@ -23,6 +23,8 @@ import {
} from "../../api/controller";
import {toast} from "react-semantic-toasts-2";
import {RestartButton, ShutdownButton} from "./Settings";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {CONTROLLER_URI} from "../Vars";
// Service status color mapping
@ -1074,6 +1076,12 @@ function AdminControlsSection() {
);
}
function ControllerLink() {
return <HandPointMessage>
You can view the Controller at <a href={CONTROLLER_URI}>{CONTROLLER_URI}</a>
</HandPointMessage>
}
export function ControllerPage() {
return (
@ -1081,6 +1089,7 @@ export function ControllerPage() {
<AdminControlsSection/>
<ServicesSection/>
<DiskSection/>
<ControllerLink/>
</Container>
);
}

View file

@ -1,6 +1,7 @@
import React, {useContext} from 'react';
import {Link} from 'react-router';
import {Message, Placeholder, PlaceholderHeader, PlaceholderLine, Table, TableCell, TableRow} from 'semantic-ui-react';
import {Message, PlaceholderHeader, PlaceholderLine, TableCell, TableRow} from 'semantic-ui-react';
import {Placeholder, Table} from '../Theme';
import _ from 'lodash';
import {SortableTable} from '../SortableTable';
import {formatFrequency, humanFileSize} from '../Common';

View file

@ -91,6 +91,12 @@ export const DragSelectionContext = React.createContext({
handleDragStart: () => {},
handleDragMove: () => {},
getDragState: () => ({isDragSelecting: false, isDragDeselecting: false}),
shouldAllowClick: () => true,
// Selection state and functions
selectedPaths: [],
onSelect: () => {},
isSelected: () => false,
clearSelection: () => {},
});
export function DragSelectionProvider({children, selectedPaths, setSelectedPaths, browseFiles, openFolders}) {
@ -99,11 +105,17 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
// Drag selection state
const isTouchDevice = useIsTouchDevice();
const [isDragging, setIsDragging] = useState(false);
const [isMouseDown, setIsMouseDown] = useState(false);
const [dragStartPath, setDragStartPath] = useState(null);
const [dragSelection, setDragSelection] = useState(new Set());
const [dragMode, setDragMode] = useState('select'); // 'select' or 'deselect'
const allRowPathsRef = useRef([]);
const dragStartPosRef = useRef({x: 0, y: 0});
// Track pending drag start - stored in refs to avoid visual changes before threshold
const pendingDragPathRef = useRef(null);
const pendingDragModeRef = useRef('select');
// Track if a drag just completed - used to prevent onClick from firing after drag
const dragJustCompletedRef = useRef(false);
// Update ordered list of visible row paths when files change
useEffect(() => {
@ -123,10 +135,12 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
// Determine mode: if starting from selected item, we're deselecting; otherwise selecting
const mode = selectedPaths.includes(path) ? 'deselect' : 'select';
// Store in refs - don't set dragSelection yet to avoid visual flap
// Visual changes only happen after drag threshold is exceeded
dragStartPosRef.current = {x: event.clientX, y: event.clientY};
setDragStartPath(path);
setDragSelection(new Set([path]));
setDragMode(mode);
pendingDragPathRef.current = path;
pendingDragModeRef.current = mode;
setIsMouseDown(true);
}, [isTouchDevice, selectedPaths]);
const handleDragMove = useCallback((path) => {
@ -150,7 +164,7 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
}, [isDragging, dragStartPath]);
const handleDragEnd = useCallback(() => {
if (!isDragging && !dragStartPath) return;
if (!isMouseDown) return;
const draggedPaths = Array.from(dragSelection);
if (draggedPaths.length > 0 && isDragging) {
@ -163,27 +177,36 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
newSelectedPaths = [...new Set([...selectedPaths, ...draggedPaths])];
}
setSelectedPaths(newSelectedPaths);
// Mark that a drag just completed - onClick handlers should not fire
dragJustCompletedRef.current = true;
}
// Reset drag state
// Reset all drag state
setIsMouseDown(false);
setIsDragging(false);
setDragStartPath(null);
setDragSelection(new Set());
setDragMode('select');
}, [isDragging, dragStartPath, selectedPaths, dragSelection, dragMode, setSelectedPaths]);
pendingDragPathRef.current = null;
pendingDragModeRef.current = 'select';
}, [isMouseDown, isDragging, selectedPaths, dragSelection, dragMode, setSelectedPaths]);
// Global mouse event listeners for drag selection
useEffect(() => {
if (!dragStartPath) return;
if (!isMouseDown) return;
const handleGlobalMouseMove = (e) => {
if (!isDragging && dragStartPath) {
if (!isDragging && pendingDragPathRef.current) {
// Check if we've moved enough to start dragging
const dx = e.clientX - dragStartPosRef.current.x;
const dy = e.clientY - dragStartPosRef.current.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance > DRAG_THRESHOLD) {
// NOW initialize drag state - this triggers visual feedback
setDragStartPath(pendingDragPathRef.current);
setDragSelection(new Set([pendingDragPathRef.current]));
setDragMode(pendingDragModeRef.current);
setIsDragging(true);
}
}
@ -191,7 +214,7 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
const handleGlobalMouseUp = () => handleDragEnd();
const handleSelectStart = (e) => {
if (isDragging) e.preventDefault();
if (isMouseDown) e.preventDefault();
};
document.addEventListener('mousemove', handleGlobalMouseMove);
@ -203,7 +226,7 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
document.removeEventListener('mouseup', handleGlobalMouseUp);
document.removeEventListener('selectstart', handleSelectStart);
};
}, [dragStartPath, isDragging, handleDragEnd, DRAG_THRESHOLD]);
}, [isMouseDown, isDragging, handleDragEnd, DRAG_THRESHOLD]);
// Helper function for components to compute their visual drag state
const getDragState = useCallback((path, isSelected) => {
@ -213,11 +236,45 @@ export function DragSelectionProvider({children, selectedPaths, setSelectedPaths
return {isDragSelecting, isDragDeselecting};
}, [dragSelection, dragMode]);
// Check if a click should be allowed (not blocked by a recent drag)
// This is called by onClick handlers to determine if they should proceed
const shouldAllowClick = useCallback(() => {
if (dragJustCompletedRef.current) {
dragJustCompletedRef.current = false;
return false;
}
return true;
}, []);
// Selection functions - moved from FileBrowser to eliminate prop drilling
const onSelect = useCallback((path) => {
setSelectedPaths(prev => {
if (prev.includes(path)) {
return prev.filter(i => i !== path);
}
return [...prev, path];
});
}, [setSelectedPaths]);
const isSelected = useCallback((path) => {
return selectedPaths.includes(path);
}, [selectedPaths]);
const clearSelection = useCallback(() => {
setSelectedPaths([]);
}, [setSelectedPaths]);
const value = {
isDragging,
handleDragStart,
handleDragMove,
getDragState,
shouldAllowClick,
// Selection state and functions
selectedPaths,
onSelect,
isSelected,
clearSelection,
};
return (