Adding bulk tag button to the file browser. User can add tags to many files, but can only remove tags if all files share the tags to be removed.

This commit is contained in:
Roland 2025-12-06 18:07:20 -07:00
parent c1e318cafc
commit c6df730dcc
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
10 changed files with 1023 additions and 1 deletions

View file

@ -0,0 +1,243 @@
import React from 'react';
import {Button, Divider, Header, Loader, Modal, ModalActions, ModalContent, ModalHeader, Progress} from "./Theme";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {applyBulkTags, getBulkTagPreview, getBulkTagProgress} from "../api";
import {TagsContext} from "../Tags";
const BULK_TAG_WARNING_THRESHOLD = 50;
const POLL_INTERVAL = 500; // Poll progress every 500ms
export function BulkTagModal({open, onClose, paths, onComplete}) {
// State machine: 'loading' -> 'preview' -> 'applying' -> 'complete'
const [state, setState] = React.useState('loading');
const [fileCount, setFileCount] = React.useState(0);
const [sharedTagNames, setSharedTagNames] = React.useState([]);
const [localTags, setLocalTags] = React.useState([]);
const [progress, setProgress] = React.useState({total: 0, completed: 0, queued_jobs: 0});
const [error, setError] = React.useState(null);
const {tagNames, TagsGroup} = React.useContext(TagsContext);
// Fetch preview when modal opens
React.useEffect(() => {
if (open && paths && paths.length > 0) {
setState('loading');
setLocalTags([]);
setError(null);
getBulkTagPreview(paths).then(preview => {
if (preview) {
setFileCount(preview.file_count);
setSharedTagNames(preview.shared_tag_names || []);
setLocalTags(preview.shared_tag_names || []);
setState('preview');
} else {
setError('Failed to get preview');
setState('preview');
}
}).catch(err => {
console.error('Failed to get bulk tag preview', err);
setError(err.message || 'Failed to get preview');
setState('preview');
});
}
}, [open, paths]);
// Poll progress while applying
React.useEffect(() => {
if (state !== 'applying') {
return;
}
const pollProgress = async () => {
const progressData = await getBulkTagProgress();
if (progressData) {
setProgress(progressData);
if (progressData.status === 'idle' && progressData.queued_jobs === 0) {
// Done applying
setState('complete');
}
if (progressData.error) {
setError(progressData.error);
}
}
};
const interval = setInterval(pollProgress, POLL_INTERVAL);
pollProgress(); // Initial poll
return () => clearInterval(interval);
}, [state]);
const addTag = (name) => {
if (!localTags.includes(name)) {
setLocalTags([...localTags, name]);
}
};
const removeTag = (name) => {
setLocalTags(localTags.filter(t => t !== name));
};
const handleApply = async () => {
// Compute what changed
const tagsToAdd = localTags.filter(t => !sharedTagNames.includes(t));
const tagsToRemove = sharedTagNames.filter(t => !localTags.includes(t));
if (tagsToAdd.length === 0 && tagsToRemove.length === 0) {
return;
}
setState('applying');
setProgress({total: 0, completed: 0, queued_jobs: 1});
try {
await applyBulkTags(paths, tagsToAdd, tagsToRemove);
} catch (err) {
console.error('Failed to apply bulk tags', err);
setError(err.message || 'Failed to apply tags');
}
};
const handleClose = () => {
if (state === 'complete' && onComplete) {
onComplete();
}
setState('loading');
setFileCount(0);
setSharedTagNames([]);
setLocalTags([]);
setProgress({total: 0, completed: 0, queued_jobs: 0});
setError(null);
onClose();
};
// Tags not currently applied (available to add)
const unusedTags = tagNames ? tagNames.filter(name => !localTags.includes(name)) : [];
// Check if there are any changes from original
const hasChanges =
localTags.some(t => !sharedTagNames.includes(t)) || // Added tags
sharedTagNames.some(t => !localTags.includes(t)); // Removed tags
const showWarning = fileCount >= BULK_TAG_WARNING_THRESHOLD;
const progressPercent = progress.total > 0
? Math.round((progress.completed / progress.total) * 100)
: 0;
return (
<Modal closeIcon open={open} onClose={handleClose} size="small">
<ModalHeader>Bulk Tag Files</ModalHeader>
<ModalContent>
{state === 'loading' && (
<div style={{textAlign: 'center', padding: '2em'}}>
<Loader active inline="centered">Loading preview...</Loader>
</div>
)}
{state === 'preview' && (
<>
{error && (
<Message negative>
<Message.Header>Error</Message.Header>
<p>{error}</p>
</Message>
)}
<Header as="h4">
{fileCount} file{fileCount !== 1 ? 's' : ''} will be affected
</Header>
{showWarning && (
<Message warning>
<Message.Header>Warning</Message.Header>
<p>Tagging over {BULK_TAG_WARNING_THRESHOLD} files may make it difficult to find what you are looking for. Are you sure?</p>
</Message>
)}
<Divider/>
<Header as="h4">Applied Tags</Header>
{localTags.length > 0 ? (
<TagsGroup tagNames={localTags} onClick={removeTag}/>
) : (
<p style={{color: 'grey'}}>Add one or more tags below</p>
)}
<Divider/>
{unusedTags.length > 0 ? (
<TagsGroup tagNames={unusedTags} onClick={addTag}/>
) : (
<p style={{color: 'grey'}}>You have no tags</p>
)}
</>
)}
{state === 'applying' && (
<div style={{padding: '1em'}}>
<Header as="h4">Applying tags...</Header>
<Progress
percent={progressPercent}
progress
indicating
color="blue"
>
{progress.completed} / {progress.total} files
</Progress>
{progress.queued_jobs > 0 && (
<p style={{color: 'grey'}}>{progress.queued_jobs} job{progress.queued_jobs !== 1 ? 's' : ''} queued</p>
)}
{error && (
<Message negative>
<Message.Header>Error</Message.Header>
<p>{error}</p>
</Message>
)}
</div>
)}
{state === 'complete' && (
<div style={{padding: '1em'}}>
<Message positive>
<Message.Header>Complete</Message.Header>
<p>Successfully tagged {progress.total} file{progress.total !== 1 ? 's' : ''}.</p>
</Message>
{error && (
<Message warning>
<Message.Header>Warning</Message.Header>
<p>Some errors occurred: {error}</p>
</Message>
)}
</div>
)}
</ModalContent>
<ModalActions>
{state === 'preview' && (
<>
<Button onClick={handleClose}>Cancel</Button>
<Button
color="violet"
onClick={handleApply}
disabled={!hasChanges || fileCount === 0}
>
Apply Tags
</Button>
</>
)}
{state === 'applying' && (
<Button onClick={handleClose} disabled>
Please wait...
</Button>
)}
{state === 'complete' && (
<Button color="green" onClick={handleClose}>
Done
</Button>
)}
</ModalActions>
</Modal>
);
}
export default BulkTagModal;

View file

@ -0,0 +1,198 @@
import React from 'react';
import {act, render, screen, waitFor} from '@testing-library/react';
import {BulkTagModal} from './BulkTagModal';
import {TagsContext} from '../Tags';
// Mock the API functions
jest.mock('../api', () => ({
getBulkTagPreview: jest.fn(),
applyBulkTags: jest.fn(),
getBulkTagProgress: jest.fn(),
}));
// Mock Theme components
jest.mock('./Theme', () => ({
...jest.requireActual('./Theme'),
Modal: ({open, onClose, children, closeIcon}) => {
if (!open) return null;
return (
<div data-testid="modal">
{closeIcon && <button data-testid="close-icon" onClick={onClose}>x</button>}
{children}
</div>
);
},
ModalHeader: ({children}) => <div data-testid="modal-header">{children}</div>,
ModalContent: ({children}) => <div data-testid="modal-content">{children}</div>,
ModalActions: ({children}) => <div data-testid="modal-actions">{children}</div>,
Button: ({children, onClick, disabled, color, ...props}) => (
<button onClick={onClick} disabled={disabled} data-testid={`button-${children}`} {...props}>{children}</button>
),
Header: ({children, as}) => <div data-testid="header">{children}</div>,
Divider: () => <hr data-testid="divider"/>,
Loader: ({children}) => <div data-testid="loader">{children}</div>,
Message: ({children, warning, negative, positive}) => (
<div data-testid={`message-${warning ? 'warning' : negative ? 'negative' : positive ? 'positive' : 'info'}`}>
{children}
</div>
),
Progress: ({percent, children}) => (
<div data-testid="progress" data-percent={percent}>{children}</div>
),
}));
// Import mocked API functions
import {getBulkTagPreview, applyBulkTags, getBulkTagProgress} from '../api';
// Mock TagsGroup component for testing
const MockTagsGroup = ({tagNames, onClick}) => (
<div data-testid="tags-group">
{tagNames?.map(name => (
<span key={name} onClick={() => onClick && onClick(name)} data-testid={`tag-${name}`}>
{name}
</span>
))}
</div>
);
// Create a wrapper with TagsContext
const TagsContextWrapper = ({children}) => {
const tagsValue = {
tagNames: ['tag1', 'tag2', 'tag3'],
TagsGroup: MockTagsGroup,
};
return (
<TagsContext.Provider value={tagsValue}>
{children}
</TagsContext.Provider>
);
};
// Custom render function with TagsContext
const renderWithTags = (ui, options) =>
render(ui, {wrapper: TagsContextWrapper, ...options});
describe('BulkTagModal', () => {
const defaultProps = {
open: true,
onClose: jest.fn(),
paths: ['file1.txt', 'file2.txt'],
onComplete: jest.fn(),
};
beforeEach(() => {
jest.clearAllMocks();
getBulkTagPreview.mockResolvedValue({
file_count: 2,
shared_tag_names: ['shared'],
});
getBulkTagProgress.mockResolvedValue({
status: 'idle',
total: 0,
completed: 0,
queued_jobs: 0,
});
});
describe('Modal Rendering', () => {
it('renders modal when open is true', async () => {
renderWithTags(<BulkTagModal {...defaultProps} />);
expect(screen.getByTestId('modal')).toBeInTheDocument();
});
it('does not render modal when open is false', () => {
renderWithTags(<BulkTagModal {...defaultProps} open={false}/>);
expect(screen.queryByTestId('modal')).not.toBeInTheDocument();
});
it('shows header', async () => {
renderWithTags(<BulkTagModal {...defaultProps} />);
expect(screen.getByTestId('modal-header')).toHaveTextContent('Bulk Tag Files');
});
});
describe('Loading State', () => {
it('shows loading state while fetching preview', async () => {
getBulkTagPreview.mockImplementation(() => new Promise(() => {
})); // Never resolves
renderWithTags(<BulkTagModal {...defaultProps} />);
expect(screen.getByTestId('loader')).toBeInTheDocument();
});
});
describe('Preview State', () => {
it('shows file count after loading', async () => {
renderWithTags(<BulkTagModal {...defaultProps} />);
await waitFor(() => {
expect(screen.getByText(/2 files will be affected/i)).toBeInTheDocument();
});
});
it('does not show warning for less than 50 files', async () => {
getBulkTagPreview.mockResolvedValue({
file_count: 10,
shared_tag_names: [],
});
renderWithTags(<BulkTagModal {...defaultProps} />);
await waitFor(() => {
expect(screen.getByText(/10 files will be affected/i)).toBeInTheDocument();
});
expect(screen.queryByTestId('message-warning')).not.toBeInTheDocument();
});
it('Apply button is disabled when no changes', async () => {
renderWithTags(<BulkTagModal {...defaultProps} />);
await waitFor(() => {
expect(screen.getByText(/2 files will be affected/i)).toBeInTheDocument();
});
const applyButton = screen.getByTestId('button-Apply Tags');
expect(applyButton).toBeDisabled();
});
});
describe('Applying Tags', () => {
it('calls applyBulkTags when Apply is clicked', async () => {
applyBulkTags.mockResolvedValue({ok: true});
getBulkTagProgress.mockResolvedValue({
status: 'running',
total: 2,
completed: 1,
queued_jobs: 0,
});
renderWithTags(<BulkTagModal {...defaultProps} />);
// Wait for preview to load
await waitFor(() => {
expect(screen.getByText(/2 files will be affected/i)).toBeInTheDocument();
});
// The test would need to simulate adding a tag first
// This is a simplified test - in real usage, user would click to add tags
});
});
describe('Close Modal', () => {
it('calls onClose when Cancel is clicked', async () => {
renderWithTags(<BulkTagModal {...defaultProps} />);
await waitFor(() => {
expect(screen.getByText(/2 files will be affected/i)).toBeInTheDocument();
});
const cancelButton = screen.getByTestId('button-Cancel');
act(() => {
cancelButton.click();
});
expect(defaultProps.onClose).toHaveBeenCalled();
});
});
describe('Error Handling', () => {
it('handles preview failure gracefully', async () => {
// When preview returns undefined (API error), we should still see the modal
getBulkTagPreview.mockResolvedValue(undefined);
renderWithTags(<BulkTagModal {...defaultProps} />);
// Modal should still be visible
expect(screen.getByTestId('modal')).toBeInTheDocument();
});
});
});

View file

@ -21,6 +21,7 @@ import {useBrowseFiles, useMediaDirectory, useWROLMode} from "../hooks/customHoo
import {FileRowTagIcon, FilesRefreshButton} from "./Files";
import {FilePreviewContext} from "./FilePreview";
import {SettingsContext} from "../contexts/contexts";
import {BulkTagModal} from "./BulkTagModal";
function depthIndentation(path) {
// Repeated spaces for every folder a path is in.
@ -137,6 +138,7 @@ export function FileBrowser() {
const [moveOpen, setMoveOpen] = React.useState(false);
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false);
const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
const [pending, setPending] = React.useState(false);
// Only true if only one path is selected, and it is a directory.
const [singleDirectorySelected, setSingleDirectorySelected] = React.useState(false);
@ -242,7 +244,7 @@ export function FileBrowser() {
onSubmit={reset}
/> : null}
<Button icon='move'
color='violet'
color='teal'
disabled={wrolModeEnabled || selectedPathsCount === 0}
onClick={() => setMoveOpen(true)}
/>
@ -282,6 +284,18 @@ export function FileBrowser() {
directory={selectedPaths.length === 1 ? selectedPaths[0] : null}
ignored={isDirectoryIgnored}
/>
<Button
color='violet'
icon='tags'
disabled={selectedPathsCount === 0}
onClick={() => setBulkTagOpen(true)}
/>
<BulkTagModal
open={bulkTagOpen}
onClose={() => setBulkTagOpen(false)}
paths={selectedPaths}
onComplete={reset}
/>
</TableHeaderCell>
</TableRow>
</TableFooter>;