diff --git a/app/src/api.js b/app/src/api.js
index 7a0bab62..b1a0f126 100644
--- a/app/src/api.js
+++ b/app/src/api.js
@@ -1684,3 +1684,37 @@ export async function triggerUpgrade() {
}
return response;
}
+
+export async function getBulkTagPreview(paths) {
+ const body = {paths};
+ const response = await apiPost(`${API_URI}/files/bulk_tag/preview`, body);
+ if (response.ok) {
+ return await response.json();
+ } else {
+ const message = await getErrorMessage(response, 'Failed to get bulk tag preview.');
+ toast({type: 'error', title: 'Bulk Tag Error', description: message, time: 5000});
+ }
+}
+
+export async function applyBulkTags(paths, addTagNames, removeTagNames) {
+ const body = {
+ paths,
+ add_tag_names: addTagNames || [],
+ remove_tag_names: removeTagNames || [],
+ };
+ const response = await apiPost(`${API_URI}/files/bulk_tag/apply`, body);
+ if (!response.ok) {
+ const message = await getErrorMessage(response, 'Failed to apply bulk tags.');
+ toast({type: 'error', title: 'Bulk Tag Error', description: message, time: 5000});
+ }
+ return response;
+}
+
+export async function getBulkTagProgress() {
+ const response = await apiGet(`${API_URI}/files/bulk_tag/progress`);
+ if (response.ok) {
+ return await response.json();
+ }
+ // Not toasting because this happens often during polling.
+ return null;
+}
diff --git a/app/src/components/BulkTagModal.js b/app/src/components/BulkTagModal.js
new file mode 100644
index 00000000..663cc0f9
--- /dev/null
+++ b/app/src/components/BulkTagModal.js
@@ -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 (
+
+ Bulk Tag Files
+
+ {state === 'loading' && (
+
+ Loading preview...
+
+ )}
+
+ {state === 'preview' && (
+ <>
+ {error && (
+
+ Error
+ {error}
+
+ )}
+
+
+ {fileCount} file{fileCount !== 1 ? 's' : ''} will be affected
+
+
+ {showWarning && (
+
+ Warning
+ Tagging over {BULK_TAG_WARNING_THRESHOLD} files may make it difficult to find what you are looking for. Are you sure?
+
+ )}
+
+
+
+
+ {localTags.length > 0 ? (
+
+ ) : (
+ Add one or more tags below
+ )}
+
+
+
+ {unusedTags.length > 0 ? (
+
+ ) : (
+ You have no tags
+ )}
+ >
+ )}
+
+ {state === 'applying' && (
+
+
+
+ {progress.queued_jobs > 0 && (
+
{progress.queued_jobs} job{progress.queued_jobs !== 1 ? 's' : ''} queued
+ )}
+ {error && (
+
+ Error
+ {error}
+
+ )}
+
+ )}
+
+ {state === 'complete' && (
+
+
+ Complete
+ Successfully tagged {progress.total} file{progress.total !== 1 ? 's' : ''}.
+
+ {error && (
+
+ Warning
+ Some errors occurred: {error}
+
+ )}
+
+ )}
+
+
+ {state === 'preview' && (
+ <>
+
+
+ >
+ )}
+ {state === 'applying' && (
+
+ )}
+ {state === 'complete' && (
+
+ )}
+
+
+ );
+}
+
+export default BulkTagModal;
diff --git a/app/src/components/BulkTagModal.test.js b/app/src/components/BulkTagModal.test.js
new file mode 100644
index 00000000..e2f1ccca
--- /dev/null
+++ b/app/src/components/BulkTagModal.test.js
@@ -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 (
+
+ {closeIcon && }
+ {children}
+
+ );
+ },
+ ModalHeader: ({children}) => {children}
,
+ ModalContent: ({children}) => {children}
,
+ ModalActions: ({children}) => {children}
,
+ Button: ({children, onClick, disabled, color, ...props}) => (
+
+ ),
+ Header: ({children, as}) => {children}
,
+ Divider: () =>
,
+ Loader: ({children}) => {children}
,
+ Message: ({children, warning, negative, positive}) => (
+
+ {children}
+
+ ),
+ Progress: ({percent, children}) => (
+ {children}
+ ),
+}));
+
+// Import mocked API functions
+import {getBulkTagPreview, applyBulkTags, getBulkTagProgress} from '../api';
+
+// Mock TagsGroup component for testing
+const MockTagsGroup = ({tagNames, onClick}) => (
+
+ {tagNames?.map(name => (
+ onClick && onClick(name)} data-testid={`tag-${name}`}>
+ {name}
+
+ ))}
+
+);
+
+// Create a wrapper with TagsContext
+const TagsContextWrapper = ({children}) => {
+ const tagsValue = {
+ tagNames: ['tag1', 'tag2', 'tag3'],
+ TagsGroup: MockTagsGroup,
+ };
+ return (
+
+ {children}
+
+ );
+};
+
+// 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();
+ expect(screen.getByTestId('modal')).toBeInTheDocument();
+ });
+
+ it('does not render modal when open is false', () => {
+ renderWithTags();
+ expect(screen.queryByTestId('modal')).not.toBeInTheDocument();
+ });
+
+ it('shows header', async () => {
+ renderWithTags();
+ 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();
+ expect(screen.getByTestId('loader')).toBeInTheDocument();
+ });
+ });
+
+ describe('Preview State', () => {
+ it('shows file count after loading', async () => {
+ renderWithTags();
+ 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();
+ 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();
+ 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();
+
+ // 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();
+ 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();
+ // Modal should still be visible
+ expect(screen.getByTestId('modal')).toBeInTheDocument();
+ });
+ });
+});
diff --git a/app/src/components/FileBrowser.js b/app/src/components/FileBrowser.js
index c6ee9002..21fab418 100644
--- a/app/src/components/FileBrowser.js
+++ b/app/src/components/FileBrowser.js
@@ -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}