TagSpaces is an offline, open source, document manager with tagging support
feat: brand new move/copy entries dialog, with recent files
Ilian Sapundshiev3adb04c3e91e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8eb09e348..91d4ce176 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -160,6 +160,26 @@ The app runs on multiple platforms and storage backends. When working with file/When comparing paths (e.g., `startsWith`, equality checks), normalize **both** sides with the same functions. A common bug pattern: applying `cleanFrontDirSeparator` (strips leading `/`) to one path but not the other, breaking the comparison on Mac/Linux where absolute paths start with `/`. Path utilities live in `@tagspaces/tagspaces-common/paths.js`.+## IO actions: cross-location limitations++`useIOActionsContext`'s `moveFiles` / `copyFiles` / `moveDirs` / `copyDirs` in `src/renderer/hooks/IOActionsContextProvider.tsx` operate on a **single location** — they accept a `targetLocationID` but resolve both source and target through the same location's `moveFilesPromise` / `copyFilesPromise`. They don't move files between distinct locations.++- **Cross-location transfers** go through `uploadFilesAPI` instead (download from source → upload to target, with `sourceLocationId` + `targetLocationId` args). This is the path `TargetFileBox` uses when files are dropped from the OS onto a cloud location.+- The Move/Copy dialog (`MoveCopyFilesDialog`) v1 disables cloud destinations whenever they differ from the source location (`computeMoveCopyValidity` returns `reason: 'cloud-cross-location'`), to avoid an apologetic CTA that can't actually fire. Local→local across two configured local locations does work.+- Future work to lift this limit: extend the four IO helpers with a download-then-upload pipeline, unified progress reporting, atomicity guarantees, and sidecar/thumb transfer. Tracked as a followup; **WebDAV is deprecated** and should not be special-cased.++## Recent destinations LRU++`useRecentDestinationsContext` (`src/renderer/hooks/RecentDestinationsContextProvider.tsx`) is the reusable LRU store for "places the user moved/copied to recently". Pattern:++- Array in `localStorage` under `tsRecentMoveCopyDestinations`, dedup by `(locationId, path)`, unshift-then-truncate+- Cap in the settings reducer (`tsRecentMoveCopyDestinations: 6` default; selector `getMaxRecentMoveCopyDestinations`)+- Cross-tab sync via `BroadcastChannel('recent-destinations-sync')` with `instanceId` guard — same shape as `HistoryContextProvider`+- Items: `{ path, locationId, label, ts }`. Pushers are responsible for validating `(locationId, path)` still exists on click; on failure call `removeRecent` + show a snackbar+- Mounted in `src/renderer/containers/Root.tsx` next to `HistoryContextProvider`++Reuse it in any new dialog that needs "recent X". The same persistence + cap + broadcast pattern can be cloned for a separate LRU under a different storage key — mirror `HistoryContextProvider` if you do.+## Read-only Locations`CommonLocation.isReadOnly` gates all writes: index/fulltext files, sidecar meta, thumbnails, tag-in-filename renames, `.ts/tsm.json`. Write primitives (`saveTextFilePromise`, `saveBinaryFilePromise`, `renameFilePromise`) reject with `Error('read only Location')`, but callers often swallow that into a sentinel (`false` / `undefined` / `[]`).diff --git a/src/renderer/components/DirectoryListView.tsx b/src/renderer/components/DirectoryListView.tsxdeleted file mode 100644index cb9589e30..000000000--- a/src/renderer/components/DirectoryListView.tsx+++ /dev/null@@ -1,228 +0,0 @@-import AppConfig from '-/AppConfig';-import {- FolderOutlineIcon as FolderIcon,- NewFolderIcon,- ParentFolderIcon,-} from '-/components/CommonIcons';-import { useCreateDirectoryDialogContext } from '-/components/dialogs/hooks/useCreateDirectoryDialogContext';-import TsButton from '-/components/TsButton';-import TsSelect from '-/components/TsSelect';-import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';-import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';-import { getShowUnixHiddenEntries } from '-/reducers/settings';-import { TS } from '-/tagspaces.namespace';-import { CommonLocation } from '-/utils/CommonLocation';-import { Box } from '@mui/material';-import FormControl from '@mui/material/FormControl';-import List from '@mui/material/List';-import ListItem from '@mui/material/ListItem';-import ListItemIcon from '@mui/material/ListItemIcon';-import ListItemText from '@mui/material/ListItemText';-import MenuItem from '@mui/material/MenuItem';-import Typography from '@mui/material/Typography';-import { locationType } from '@tagspaces/tagspaces-common/misc';-import { extractContainingDirectoryPath } from '@tagspaces/tagspaces-common/paths';-import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from 'react';-import { useTranslation } from 'react-i18next';-import { useSelector } from 'react-redux';--interface Props {- setTargetDir: (dirPath: string) => void;- targetPath?: string;- targetLocationID?: string;-}--const DirectoryListView: React.FC<Props> = ({- targetPath,- setTargetDir,- targetLocationID,-}) => {- const { t } = useTranslation();- const { currentLocation, findLocation, locations } =- useCurrentLocationContext();- const { currentDirectoryEntries } = useDirectoryContentContext();- const { openCreateDirectoryDialog } = useCreateDirectoryDialogContext();- const showUnixHiddenEntries: boolean = useSelector(getShowUnixHiddenEntries);-- const chosenLocationId = useRef<string>(- targetLocationID || currentLocation?.uuid,- );- const chosenDirectory = useRef<string>(targetPath);- const [directoryContent, setDirectoryContent] = useState<- TS.FileSystemEntry[]- >(currentDirectoryEntries.filter((entry) => !entry.isFile));-- // List directory content and filter out unwanted entries- const listDirectory = useCallback(- (directoryPath: string) => {- chosenDirectory.current = directoryPath;- const location = findLocation(chosenLocationId.current);- if (!location) return;- location- .listDirectoryPromise(directoryPath, [], [])- .then((results) => {- if (results !== undefined) {- setDirectoryContent(- results.filter(- (entry) =>- !entry.isFile &&- entry.name !== AppConfig.metaFolder &&- !entry.name.endsWith('/' + AppConfig.metaFolder) &&- !(!showUnixHiddenEntries && entry.name.startsWith('.')),- ),- );- }- })- .catch((error) => {- console.error('listDirectoryPromise', error);- });- },- [findLocation, showUnixHiddenEntries],- );-- // On mount, if targetLocationID is different, list its directory- useEffect(() => {- if (targetLocationID && targetLocationID !== currentLocation?.uuid) {- const chosenLocation = findLocation(chosenLocationId.current);- if (chosenLocation) {- listDirectory(targetPath);- }- }- // eslint-disable-next-line- }, []);-- // Handle location change from dropdown- const handleLocationChange = useCallback(- (event: React.ChangeEvent<HTMLInputElement>) => {- chosenLocationId.current = event.target.value;- const chosenLocation = findLocation(chosenLocationId.current);- if (chosenLocation) {- listDirectory(chosenLocation.path);- setTargetDir(chosenLocation.path);- }- },- [findLocation, listDirectory, setTargetDir],- );-- // Render location selector if local locations are available- const dirLocations = useMemo(() => {- const chosenLocation = findLocation(chosenLocationId.current);- if (!chosenLocation || chosenLocation.type !== locationType.TYPE_LOCAL) {- return null;- }- return (- <FormControl- fullWidth- variant="standard"- sx={{- flexFlow: 'nowrap',- alignItems: 'center',- }}- >- <Typography sx={{ display: 'inline' }} variant="subtitle2">- {t('targetLocation')}: - </Typography>- <TsSelect- fullWidth- onChange={handleLocationChange}- value={chosenLocationId.current}- >- {locations- .filter((loc) => loc.type === locationType.TYPE_LOCAL)- .map((location: CommonLocation) => (- <MenuItem key={location.uuid} value={location.uuid}>- <Box sx={{ width: '100%' }}>{location.name}</Box>- </MenuItem>- ))}- </TsSelect>- </FormControl>- );- }, [findLocation, handleLocationChange, locations, t]);-- // Render folder content- const folderContent = useMemo(() => {- if (directoryContent && directoryContent.length > 0) {- return directoryContent.map((entry) => (- <ListItem- key={entry.path}- data-tid={'MoveTarget' + entry.name}- title={'Navigate to: ' + entry.path}- onClick={() => setTargetDir(entry.path)}- onDoubleClick={() => listDirectory(entry.path)}- >- <ListItemIcon sx={{ minWidth: 35 }}>- <FolderIcon />- </ListItemIcon>- <ListItemText primary={entry.name} />- </ListItem>- ));- }- return <Box sx={{ padding: '10px' }}>{t('core:noSubFoldersFound')}</Box>;- }, [directoryContent, listDirectory, setTargetDir, t]);-- // Handler for navigating to parent directory- const handleNavigateParent = useCallback(() => {- if (chosenDirectory.current) {- let currentPath = chosenDirectory.current;- if (currentPath.endsWith(currentLocation?.getDirSeparator())) {- currentPath = currentPath.slice(0, -1);- }- const parentDir = extractContainingDirectoryPath(currentPath);- listDirectory(parentDir);- setTargetDir(parentDir);- }- }, [currentLocation, listDirectory, setTargetDir]);-- // Handler for creating a new subdirectory- const handleCreateSubdirectory = useCallback(() => {- openCreateDirectoryDialog(- chosenDirectory.current,- (newDirPath) => {- listDirectory(chosenDirectory.current);- setTargetDir(newDirPath);- },- true,- );- }, [listDirectory, openCreateDirectoryDialog, setTargetDir]);-- return (- <Box sx={{ marginTop: '10px' }}>- {dirLocations}- <TsButton- startIcon={<ParentFolderIcon />}- sx={{ marginTop: '10px', marginBottom: '10px' }}- data-tid="navigateToParentTID"- onClick={handleNavigateParent}- >- {t('core:navigateToParentDirectory')}- </TsButton>- <TsButton- startIcon={<NewFolderIcon />}- sx={{ marginLeft: '5px', marginTop: '10px', marginBottom: '10px' }}- data-tid="newSubdirectoryTID"- onClick={handleCreateSubdirectory}- >- {t('core:newSubdirectory')}- </TsButton>- <List- dense- sx={{- borderRadius: AppConfig.defaultCSSRadius,- border: '1px solid gray',- maxHeight: 300,- overflowY: 'auto',- }}- >- {folderContent}- </List>- </Box>- );-};--export default React.memo(DirectoryListView);diff --git a/src/renderer/components/FolderBrowser/FolderBrowser.tsx b/src/renderer/components/FolderBrowser/FolderBrowser.tsxnew file mode 100644index 000000000..8867e55c3--- /dev/null+++ b/src/renderer/components/FolderBrowser/FolderBrowser.tsx@@ -0,0 +1,225 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import AppConfig from '-/AppConfig';+import { ParentFolderIcon } from '-/components/CommonIcons';+import TsButton from '-/components/TsButton';+import TsIconButton from '-/components/TsIconButton';+import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';+import ClearIcon from '@mui/icons-material/Clear';+import CreateNewFolderOutlinedIcon from '@mui/icons-material/CreateNewFolderOutlined';+import SearchIcon from '@mui/icons-material/Search';+import Box from '@mui/material/Box';+import InputAdornment from '@mui/material/InputAdornment';+import Paper from '@mui/material/Paper';+import TextField from '@mui/material/TextField';+import { extractParentDirectoryPath } from '@tagspaces/tagspaces-common/paths';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import FolderList, { FolderListFilter } from './FolderList';+import LocationBreadcrumb from './LocationBreadcrumb';+import LocationPicker from './LocationPicker';++interface Props {+ locations: CommonLocation[];+ activeLocationId: string;+ onActiveLocationChange: (location: CommonLocation) => void;+ /** Absolute path within the active location. Controlled by parent. */+ path: string;+ onPathChange: (newPath: string) => void;+ /** Optional handler for the "Add location…" menu item. */+ onAddLocation?: () => void;+ /** Locations rendered as disabled in the picker. */+ disabledLocationIds?: string[];+ /** Tooltip shown on disabled location rows. */+ locationDisabledTooltip?: string;+ /** Which entries the folder list shows. Default: 'folders'. */+ filter?: FolderListFilter;+ /** File-picker callback (when filter includes files). */+ onFileSelect?: (entry: TS.FileSystemEntry) => void;+ /** When provided, shows a "New folder" button. Receives the current path. */+ onCreateFolder?: (parentPath: string) => void;+ /** Notifies parent when the search query changes (so e.g. recents can hide). */+ onQueryChange?: (query: string) => void;+ /** Fixed height of the folder list area. */+ listHeight?: number | string;+}++function FolderBrowser({+ locations,+ activeLocationId,+ onActiveLocationChange,+ path,+ onPathChange,+ onAddLocation,+ disabledLocationIds,+ locationDisabledTooltip,+ filter = 'folders',+ onFileSelect,+ onCreateFolder,+ onQueryChange,+ listHeight = 240,+}: Props) {+ const { t } = useTranslation();+ const [query, setQuery] = useState('');+ const activeLocation = locations.find((l) => l.uuid === activeLocationId);+ const sep = activeLocation?.getDirSeparator?.() || '/';++ const atLocationRoot =+ !!activeLocation &&+ (path === (activeLocation.path || '') ||+ (path === '' && !activeLocation.path));++ function setQueryAndNotify(next: string) {+ setQuery(next);+ onQueryChange?.(next);+ }++ function handleUp() {+ if (atLocationRoot || !activeLocation) return;+ const parent = extractParentDirectoryPath(path, sep);+ if (+ activeLocation.path &&+ (parent === activeLocation.path ||+ parent === '' ||+ !parent.startsWith(activeLocation.path))+ ) {+ onPathChange(activeLocation.path);+ } else {+ onPathChange(parent);+ }+ }++ if (!activeLocation) {+ return null;+ }++ return (+ <Box>+ {/* Destination row */}+ <Paper+ variant="outlined"+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 0.5,+ padding: '4px 4px 4px 6px',+ borderRadius: AppConfig.defaultCSSRadius,+ minHeight: 40,+ }}+ >+ <LocationPicker+ locations={locations}+ activeLocationId={activeLocation.uuid}+ onSelect={onActiveLocationChange}+ onAddLocation={onAddLocation}+ disabledLocationIds={disabledLocationIds}+ locationDisabledTooltip={locationDisabledTooltip}+ />+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <LocationBreadcrumb+ location={activeLocation}+ path={path || activeLocation.path || ''}+ onJump={onPathChange}+ />+ </Box>+ <TsIconButton+ size="small"+ data-tid="navigateToParentTID"+ onClick={handleUp}+ disabled={atLocationRoot}+ aria-label={t('core:upOneLevel')}+ tooltip={t('core:upOneLevel')}+ >+ <ParentFolderIcon fontSize="small" />+ </TsIconButton>+ </Paper>++ {/* Tools row: search + (optional) New folder */}+ <Box sx={{ display: 'flex', gap: 1, marginTop: 1 }}>+ <TextField+ size="small"+ fullWidth+ placeholder={t('core:filterFolders')}+ value={query}+ onChange={(e) => setQueryAndNotify(e.target.value)}+ slotProps={{+ htmlInput: { 'data-tid': 'folderBrowserSearch' },+ input: {+ startAdornment: (+ <InputAdornment position="start">+ <SearchIcon fontSize="small" />+ </InputAdornment>+ ),+ endAdornment: query ? (+ <InputAdornment position="end">+ <TsIconButton+ size="small"+ onClick={() => setQueryAndNotify('')}+ aria-label={t('core:clearSearch')}+ tooltip={t('core:clearSearch')}+ >+ <ClearIcon fontSize="small" />+ </TsIconButton>+ </InputAdornment>+ ) : undefined,+ sx: { borderRadius: AppConfig.defaultCSSRadius },+ },+ }}+ />+ {onCreateFolder && (+ <TsButton+ data-tid="newSubdirectoryTID"+ startIcon={<CreateNewFolderOutlinedIcon fontSize="small" />}+ onClick={() => onCreateFolder(path || activeLocation.path || '')}+ sx={{+ flexShrink: 0,+ whiteSpace: 'nowrap',+ }}+ >+ {t('core:createDirectory')}+ </TsButton>+ )}+ </Box>++ {/* Folder list */}+ <Box+ sx={{+ marginTop: 1,+ border: '1px solid',+ borderColor: 'divider',+ borderRadius: AppConfig.defaultCSSRadius,+ overflow: 'hidden',+ }}+ >+ <FolderList+ location={activeLocation}+ path={path || activeLocation.path || ''}+ query={query}+ filter={filter}+ onDescend={onPathChange}+ onFileSelect={onFileSelect}+ height={listHeight}+ />+ </Box>+ </Box>+ );+}++export default FolderBrowser;diff --git a/src/renderer/components/FolderBrowser/FolderList.tsx b/src/renderer/components/FolderBrowser/FolderList.tsxnew file mode 100644index 000000000..45292ec4a--- /dev/null+++ b/src/renderer/components/FolderBrowser/FolderList.tsx@@ -0,0 +1,245 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import AppConfig from '-/AppConfig';+import { FileIcon, FolderIcon } from '-/components/CommonIcons';+import TsTooltip from '-/components/TsTooltip';+import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';+import ChevronRightIcon from '@mui/icons-material/ChevronRight';+import Box from '@mui/material/Box';+import List from '@mui/material/List';+import ListItemButton from '@mui/material/ListItemButton';+import ListItemIcon from '@mui/material/ListItemIcon';+import ListItemText from '@mui/material/ListItemText';+import Skeleton from '@mui/material/Skeleton';+import Typography from '@mui/material/Typography';+import { useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++export type FolderListFilter = 'folders' | 'files' | 'all';++interface Props {+ location: CommonLocation;+ /** Absolute path within the location whose immediate children to list. */+ path: string;+ /** Optional case-insensitive substring filter over entry names. */+ query?: string;+ /** Whether to list folders only (default), files only, or both. */+ filter?: FolderListFilter;+ /** Highlight a specific entry's path (e.g. just-created folder). */+ selectedPath?: string;+ /** Called when the user descends into a folder. */+ onDescend?: (path: string) => void;+ /** Called when the user clicks a file (file-picker mode). */+ onFileSelect?: (entry: TS.FileSystemEntry) => void;+ /** Fixed visible height for the list area. Content scrolls; loading and+ * empty states center inside this area so the parent's layout stays stable. */+ height?: number | string;+}++function FolderList({+ location,+ path,+ query,+ filter = 'folders',+ selectedPath,+ onDescend,+ onFileSelect,+ height = 240,+}: Props) {+ const { t } = useTranslation();+ const [entries, setEntries] = useState<TS.FileSystemEntry[]>([]);+ const [loading, setLoading] = useState(true);+ const listRef = useRef<HTMLUListElement | null>(null);++ function handleListKeyDown(event: React.KeyboardEvent<HTMLUListElement>) {+ if (!listRef.current) return;+ const buttons = Array.from(+ listRef.current.querySelectorAll<HTMLElement>('[data-tid^="MoveTarget"]'),+ );+ if (buttons.length === 0) return;+ const active = document.activeElement as HTMLElement | null;+ let idx = active ? buttons.indexOf(active) : -1;+ switch (event.key) {+ case 'ArrowDown':+ event.preventDefault();+ idx = idx < 0 ? 0 : Math.min(idx + 1, buttons.length - 1);+ buttons[idx].focus();+ break;+ case 'ArrowUp':+ event.preventDefault();+ idx = idx <= 0 ? 0 : idx - 1;+ buttons[idx].focus();+ break;+ case 'Home':+ event.preventDefault();+ buttons[0].focus();+ break;+ case 'End':+ event.preventDefault();+ buttons[buttons.length - 1].focus();+ break;+ default:+ break;+ }+ }++ useEffect(() => {+ let cancelled = false;+ setLoading(true);+ if (!location?.listDirectoryPromise) {+ setEntries([]);+ setLoading(false);+ return () => {+ cancelled = true;+ };+ }+ location+ .listDirectoryPromise(path, [], [])+ .then((results: TS.FileSystemEntry[] | undefined) => {+ if (cancelled) return;+ setEntries(+ (results || []).filter(+ (e) =>+ e.name !== AppConfig.metaFolder &&+ !e.name.endsWith('/' + AppConfig.metaFolder) &&+ !e.name.startsWith('.'),+ ),+ );+ setLoading(false);+ })+ .catch((err: unknown) => {+ if (cancelled) return;+ console.error('FolderList listDirectoryPromise', err);+ setEntries([]);+ setLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [location, path]);++ const visible = useMemo(() => {+ const q = (query || '').trim().toLowerCase();+ return entries.filter((e) => {+ if (filter === 'folders' && e.isFile) return false;+ if (filter === 'files' && !e.isFile) return false;+ if (q && !e.name.toLowerCase().includes(q)) return false;+ return true;+ });+ }, [entries, filter, query]);++ function handleClick(entry: TS.FileSystemEntry) {+ if (entry.isFile) {+ onFileSelect?.(entry);+ } else {+ onDescend?.(entry.path);+ }+ }++ const containerSx = {+ height,+ display: 'flex',+ flexDirection: 'column' as const,+ overflow: 'hidden',+ };++ if (loading) {+ return (+ <Box sx={{ ...containerSx, padding: 1 }}>+ {[0, 1, 2].map((i) => (+ <Skeleton+ key={i}+ variant="rectangular"+ height={36}+ sx={{ marginBottom: 0.5, borderRadius: 1 }}+ />+ ))}+ </Box>+ );+ }++ if (visible.length === 0) {+ return (+ <Box+ sx={{+ ...containerSx,+ alignItems: 'center',+ justifyContent: 'center',+ padding: 3,+ textAlign: 'center',+ color: 'text.secondary',+ fontSize: '0.875rem',+ }}+ >+ {query ? t('core:noFoldersMatch') : t('core:thisFolderIsEmpty')}+ </Box>+ );+ }++ return (+ <Box sx={containerSx}>+ <List+ dense+ ref={listRef}+ onKeyDown={handleListKeyDown}+ aria-label={t('core:destination')}+ sx={{+ flex: 1,+ overflowY: 'auto',+ padding: 0,+ }}+ >+ {visible.map((entry) => {+ const isSelected = selectedPath === entry.path;+ return (+ <TsTooltip key={entry.path} title={entry.path}>+ <ListItemButton+ data-tid={'MoveTarget' + entry.name}+ selected={isSelected}+ onClick={() => handleClick(entry)}+ onDoubleClick={() => !entry.isFile && onDescend?.(entry.path)}+ sx={{ gap: 1 }}+ >+ <ListItemIcon sx={{ minWidth: 32 }}>+ {entry.isFile ? <FileIcon /> : <FolderIcon />}+ </ListItemIcon>+ <ListItemText+ primary={+ <Typography variant="body2" noWrap>+ {entry.name}+ </Typography>+ }+ />+ {!entry.isFile && (+ <ChevronRightIcon+ fontSize="small"+ sx={{ color: 'text.disabled', flexShrink: 0 }}+ />+ )}+ </ListItemButton>+ </TsTooltip>+ );+ })}+ </List>+ </Box>+ );+}++export default FolderList;diff --git a/src/renderer/components/FolderBrowser/LocationBreadcrumb.tsx b/src/renderer/components/FolderBrowser/LocationBreadcrumb.tsxnew file mode 100644index 000000000..9283fa95f--- /dev/null+++ b/src/renderer/components/FolderBrowser/LocationBreadcrumb.tsx@@ -0,0 +1,138 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import { CommonLocation } from '-/utils/CommonLocation';+import Box from '@mui/material/Box';+import Breadcrumbs from '@mui/material/Breadcrumbs';+import Link from '@mui/material/Link';+import Typography from '@mui/material/Typography';+import {+ cleanFrontDirSeparator,+ cleanTrailingDirSeparator,+} from '@tagspaces/tagspaces-common/paths';+import { useTranslation } from 'react-i18next';++interface Props {+ location: CommonLocation;+ /** Absolute path within the location (or equal to location.path for root). */+ path: string;+ /** Jump to an ancestor path within the location. */+ onJump: (newPath: string) => void;+}++function normalize(p: string): string {+ if (!p) return '';+ // Convert backslashes to forward slashes for splitting, then strip surrounding separators.+ return cleanTrailingDirSeparator(+ cleanFrontDirSeparator(p.replace(/\\/g, '/')),+ );+}++function LocationBreadcrumb({ location, path, onJump }: Props) {+ const { t } = useTranslation();+ const sep = location.getDirSeparator?.() || '/';+ const rootNorm = normalize(location.path || '');+ const pathNorm = normalize(path || '');++ // Compute the segments inside the location.+ let inside = pathNorm;+ if (+ rootNorm &&+ (pathNorm === rootNorm || pathNorm.startsWith(rootNorm + '/'))+ ) {+ inside = pathNorm.slice(rootNorm.length).replace(/^\/+/, '');+ }+ const segments = inside.split('/').filter((s) => s.length > 0);++ // At the location root → render a single muted separator so the row never looks empty.+ if (segments.length === 0) {+ return (+ <Typography+ component="span"+ variant="body2"+ color="text.secondary"+ sx={{ padding: '2px 4px' }}+ title={location.path || location.name}+ >+ {sep}+ </Typography>+ );+ }++ const jumpTo = (i: number) => {+ const subset = segments.slice(0, i + 1).join(sep);+ const newPath = location.path+ ? location.path.replace(/[\\/]+$/, '') + sep + subset+ : subset;+ onJump(newPath);+ };++ return (+ <Box sx={{ minWidth: 0, overflow: 'hidden' }}>+ <Breadcrumbs+ separator={sep}+ aria-label={t('core:destination')}+ maxItems={4}+ itemsBeforeCollapse={1}+ itemsAfterCollapse={2}+ sx={{+ '& .MuiBreadcrumbs-ol': {+ flexWrap: 'nowrap',+ },+ '& .MuiBreadcrumbs-li': {+ minWidth: 0,+ },+ '& .MuiBreadcrumbs-separator': {+ marginLeft: 0.5,+ marginRight: 0.5,+ },+ }}+ >+ {segments.map((seg, i) => {+ const isLast = i === segments.length - 1;+ return (+ <Link+ key={`${seg}-${i}`}+ component="button"+ type="button"+ underline="hover"+ color={isLast ? 'text.primary' : 'text.secondary'}+ onClick={() => jumpTo(i)}+ sx={{+ fontSize: '0.85rem',+ fontWeight: isLast ? 600 : 500,+ maxWidth: 160,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ padding: '2px 4px',+ borderRadius: 1,+ lineHeight: 1.4,+ }}+ title={seg}+ >+ {seg}+ </Link>+ );+ })}+ </Breadcrumbs>+ </Box>+ );+}++export default LocationBreadcrumb;diff --git a/src/renderer/components/FolderBrowser/LocationPicker.tsx b/src/renderer/components/FolderBrowser/LocationPicker.tsxnew file mode 100644index 000000000..1529b35fb--- /dev/null+++ b/src/renderer/components/FolderBrowser/LocationPicker.tsx@@ -0,0 +1,221 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import {+ AddIcon,+ CheckIcon,+ CloudLocationIcon,+ LocalLocationIcon,+} from '-/components/CommonIcons';+import TsButton from '-/components/TsButton';+import { CommonLocation } from '-/utils/CommonLocation';+import ArrowDropDownIcon from '@mui/icons-material/ArrowDropDown';+import Divider from '@mui/material/Divider';+import ListItemIcon from '@mui/material/ListItemIcon';+import ListItemText from '@mui/material/ListItemText';+import ListSubheader from '@mui/material/ListSubheader';+import Menu from '@mui/material/Menu';+import MenuItem from '@mui/material/MenuItem';+import TsTooltip from '-/components/TsTooltip';+import Typography from '@mui/material/Typography';+import React, { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++interface Props {+ locations: CommonLocation[];+ activeLocationId?: string;+ onSelect: (location: CommonLocation) => void;+ /** Optional handler for the "Add location…" trailing item. Hidden when absent. */+ onAddLocation?: () => void;+ /** IDs of locations that should render disabled (e.g. unsupported destinations). */+ disabledLocationIds?: string[];+ /** Tooltip shown on disabled location rows. */+ locationDisabledTooltip?: string;+}++function isCloud(loc: CommonLocation): boolean {+ // WebDAV is deprecated and not considered; only S3 counts as cloud here.+ return loc.haveObjectStoreSupport();+}++function LocationPicker({+ locations,+ activeLocationId,+ onSelect,+ onAddLocation,+ disabledLocationIds,+ locationDisabledTooltip,+}: Props) {+ const { t } = useTranslation();+ const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);+ const open = Boolean(anchorEl);++ const { localList, cloudList } = useMemo(() => {+ const local: CommonLocation[] = [];+ const cloud: CommonLocation[] = [];+ for (const loc of locations) {+ (isCloud(loc) ? cloud : local).push(loc);+ }+ return { localList: local, cloudList: cloud };+ }, [locations]);++ const activeLocation =+ locations.find((l) => l.uuid === activeLocationId) ?? locations[0];+ const disabledSet = new Set(disabledLocationIds ?? []);++ const handleClose = () => setAnchorEl(null);+ const handlePick = (loc: CommonLocation) => {+ handleClose();+ if (loc.uuid !== activeLocation?.uuid) {+ onSelect(loc);+ }+ };++ const renderRow = (loc: CommonLocation) => {+ const disabled = disabledSet.has(loc.uuid);+ const active = loc.uuid === activeLocation?.uuid;+ const Icon = isCloud(loc) ? CloudLocationIcon : LocalLocationIcon;+ const row = (+ <MenuItem+ key={loc.uuid}+ data-tid={'folderBrowserLocationItem_' + loc.name}+ selected={active}+ disabled={disabled && !active}+ onClick={() => handlePick(loc)}+ >+ <ListItemIcon>+ <Icon fontSize="small" />+ </ListItemIcon>+ <ListItemText+ primary={loc.name}+ secondary={+ loc.path ? (+ <Typography+ component="span"+ variant="caption"+ color="text.secondary"+ sx={{+ display: 'block',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ maxWidth: 220,+ }}+ >+ {loc.path}+ </Typography>+ ) : null+ }+ />+ {active && <CheckIcon fontSize="small" sx={{ marginLeft: 1 }} />}+ </MenuItem>+ );+ if (disabled && !active && locationDisabledTooltip) {+ return (+ <TsTooltip+ key={loc.uuid}+ title={locationDisabledTooltip}+ placement="right"+ >+ <span>{row}</span>+ </TsTooltip>+ );+ }+ return row;+ };++ const ActiveIcon = activeLocation+ ? isCloud(activeLocation)+ ? CloudLocationIcon+ : LocalLocationIcon+ : LocalLocationIcon;++ return (+ <>+ <TsButton+ data-tid="folderBrowserLocationPicker"+ variant="text"+ color="inherit"+ onClick={(e: React.MouseEvent<HTMLButtonElement>) =>+ setAnchorEl(e.currentTarget)+ }+ startIcon={<ActiveIcon fontSize="small" />}+ endIcon={<ArrowDropDownIcon fontSize="small" />}+ aria-haspopup="menu"+ aria-expanded={open}+ aria-label={t('core:switchLocation')}+ tooltip={t('core:switchLocation')}+ sx={{+ fontWeight: 600,+ padding: '2px 6px',+ minWidth: 0,+ flexShrink: 0,+ maxWidth: 160,+ '& .MuiButton-startIcon': { marginRight: 0.5 },+ '& .MuiButton-endIcon': { marginLeft: 0.25 },+ }}+ >+ <span+ style={{+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {activeLocation?.name ?? '—'}+ </span>+ </TsButton>+ <Menu+ anchorEl={anchorEl}+ open={open}+ onClose={handleClose}+ slotProps={{ paper: { sx: { minWidth: 260, maxWidth: 320 } } }}+ >+ {localList.length > 0 && (+ <ListSubheader sx={{ lineHeight: '28px' }}>+ {t('core:localLocations')}+ </ListSubheader>+ )}+ {localList.map(renderRow)}+ {cloudList.length > 0 && (+ <ListSubheader sx={{ lineHeight: '28px' }}>+ {t('core:cloudLocations')}+ </ListSubheader>+ )}+ {cloudList.map(renderRow)}+ {onAddLocation && [+ <Divider key="div" />,+ <MenuItem+ key="add"+ onClick={() => {+ handleClose();+ onAddLocation();+ }}+ >+ <ListItemIcon>+ <AddIcon fontSize="small" />+ </ListItemIcon>+ <ListItemText primary={t('core:addLocationEllipsis')} />+ </MenuItem>,+ ]}+ </Menu>+ </>+ );+}++export default LocationPicker;diff --git a/src/renderer/components/FolderBrowser/index.ts b/src/renderer/components/FolderBrowser/index.tsnew file mode 100644index 000000000..44980e6d9--- /dev/null+++ b/src/renderer/components/FolderBrowser/index.ts@@ -0,0 +1,5 @@+export { default as FolderBrowser } from './FolderBrowser';+export { default as FolderList } from './FolderList';+export type { FolderListFilter } from './FolderList';+export { default as LocationBreadcrumb } from './LocationBreadcrumb';+export { default as LocationPicker } from './LocationPicker';diff --git a/src/renderer/components/TsToggleButton.tsx b/src/renderer/components/TsToggleButton.tsxindex 0036e09fd..bfc01d20d 100644--- a/src/renderer/components/TsToggleButton.tsx+++ b/src/renderer/components/TsToggleButton.tsx@@ -42,24 +42,37 @@ function TsToggleButton(props: TSToggleButtonProps) {<ToggleButtonsize={desktopMode ? 'small' : 'medium'}variant="outlined" // text outlined contained+ selected={selected}{...rest}sx={{- ...sx,borderRadius: AppConfig.defaultCSSRadius,textTransform: 'none', //'capitalize',fontSize: '14px',- // fontWeight: selected ? 'bold' : 'normal',fontWeight: 'normal',+ // Inside a ToggleButtonGroup, non-first buttons have margin-left:-1px and+ // a 1px transparent left border. With the default `border-box` background+ // clip, the selected/hover background would paint under that transparent+ // border and cover the previous button's right border (the visible+ // separator). Clipping to the padding box keeps the separator visible.+ backgroundClip: 'padding-box',+ borderColor: theme.palette.divider,'&:hover': {- backgroundColor: alpha(theme.palette.background.default, 0.8),+ backgroundColor: theme.palette.action.hover,+ borderColor: theme.palette.divider,},'&.Mui-selected': {color: theme.palette.primary.main,backgroundColor: alpha(theme.palette.background.default, 0.9),+ borderColor: theme.palette.divider,},'&.Mui-selected:hover': {- backgroundColor: alpha(theme.palette.background.default, 0.8),+ backgroundColor: theme.palette.action.hover,+ borderColor: theme.palette.divider,},+ // Caller sx wins so a parent ToggleButtonGroup can flatten inner radii+ // and the separator between buttons stays crisp instead of fading+ // behind a curved corner.+ ...sx,}}>{children}diff --git a/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx b/src/renderer/components/dialogs/MoveCopyFilesDialog.tsxindex 9b68a1ac5..530d807aa 100644--- a/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx+++ b/src/renderer/components/dialogs/MoveCopyFilesDialog.tsx@@ -1,38 +1,53 @@import AppConfig from '-/AppConfig';-import { FileIcon, FolderIcon } from '-/components/CommonIcons';-import DirectoryListView from '-/components/DirectoryListView';+import { CheckIcon, FolderIcon, WarningIcon } from '-/components/CommonIcons';import DraggablePaper from '-/components/DraggablePaper';+import { FolderBrowser } from '-/components/FolderBrowser';import TsButton from '-/components/TsButton';+import TsToggleButton from '-/components/TsToggleButton';+import TsTooltip from '-/components/TsTooltip';+import SelectedItemsSummary from '-/components/dialogs/components/SelectedItemsSummary';import TsDialogActions from '-/components/dialogs/components/TsDialogActions';import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';+import {+ computeMoveCopyValidity,+ getValidityMessageKey,+} from '-/components/dialogs/components/computeMoveCopyValidity';+import { useCreateDirectoryDialogContext } from '-/components/dialogs/hooks/useCreateDirectoryDialogContext';+import { useCreateEditLocationDialogContext } from '-/components/dialogs/hooks/useCreateEditLocationDialogContext';import { useEntryExistDialogContext } from '-/components/dialogs/hooks/useEntryExistDialogContext';import { useFileUploadDialogContext } from '-/components/dialogs/hooks/useFileUploadDialogContext';+import { useRecentDestinationsContext } from '-/hooks/RecentDestinationsContextProvider';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';import { useIOActionsContext } from '-/hooks/useIOActionsContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { actions as AppActions, AppDispatch } from '-/reducers/app';+import {+ actions as SettingsActions,+ getLastMoveCopyMode,+} from '-/reducers/settings';import {executePromisesInBatches,getDirProperties,} from '-/services/utils-io';import { TS } from '-/tagspaces.namespace';+import AccessTimeIcon from '@mui/icons-material/AccessTime';import Box from '@mui/material/Box';+import Chip from '@mui/material/Chip';import Dialog from '@mui/material/Dialog';import DialogContent from '@mui/material/DialogContent';-import List from '@mui/material/List';-import ListItem from '@mui/material/ListItem';-import ListItemIcon from '@mui/material/ListItemIcon';import Paper from '@mui/material/Paper';+import Stack from '@mui/material/Stack';+import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';import Typography from '@mui/material/Typography';import { useTheme } from '@mui/material/styles';import useMediaQuery from '@mui/material/useMediaQuery';-import { formatBytes } from '@tagspaces/tagspaces-common/misc';import { extractFileName, joinPaths } from '@tagspaces/tagspaces-common/paths';-import { useEffect, useReducer, useRef, useState } from 'react';+import { useEffect, useMemo, useReducer, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useDispatch } from 'react-redux';+import { useDispatch, useSelector } from 'react-redux';interface Props {open: boolean;@@ -57,14 +72,19 @@ function MoveCopyFilesDialog(props: Props) {targetLocationId,skipTargetPicker,} = props;- const { findLocation } = useCurrentLocationContext();+ const { findLocation, locations } = useCurrentLocationContext();const { currentDirectoryPath, sendDirMessage } = useDirectoryContentContext();const { handleEntryExist, openEntryExistDialog } =useEntryExistDialogContext();const { copyFiles, copyDirs, moveFiles, moveDirs } = useIOActionsContext();const { openFileUploadDialog } = useFileUploadDialogContext();+ const { openCreateDirectoryDialog } = useCreateDirectoryDialogContext();+ const { openCreateEditLocationDialog } = useCreateEditLocationDialogContext();const { setReflectMetaActions } = useEditedEntryMetaContext();const { selectedEntries } = useSelectedEntriesContext();+ const { recents, pushRecent, removeRecent } = useRecentDestinationsContext();+ const { showNotification } = useNotificationContext();+ const lastMoveCopyMode = useSelector(getLastMoveCopyMode);const currentEntries = entries || selectedEntries;const [targetPath, setTargetPath] = useState(@@ -74,8 +94,70 @@ function MoveCopyFilesDialog(props: Props) {const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);- const currentLocation = findLocation();- const targetLocation = findLocation(targetLocationId);+ const sourceLocation = findLocation();+ const [activeTargetLocationId, setActiveTargetLocationId] = useState<+ string | undefined+ >(targetLocationId || sourceLocation?.uuid);+ const targetLocation = findLocation(activeTargetLocationId);+ // Kept as `currentLocation` for the existing dir-size effect below — same behavior.+ const currentLocation = sourceLocation;++ // WebDAV is deprecated and not considered; only S3 counts as cloud here.+ const isCloudLoc = (+ loc?: { haveObjectStoreSupport: () => boolean } | undefined,+ ) => !!loc && loc.haveObjectStoreSupport();+ const sourceIsCloud = isCloudLoc(sourceLocation);+ const disabledLocationIds = useMemo(() => {+ if (sourceIsCloud) {+ // When source is cloud, lock the picker to the source location.+ return locations+ .filter((l) => l.uuid !== sourceLocation?.uuid)+ .map((l) => l.uuid);+ }+ // When source is local, all cloud locations are disabled (cross-location to cloud unsupported).+ return locations.filter((l) => isCloudLoc(l)).map((l) => l.uuid);+ }, [locations, sourceIsCloud, sourceLocation?.uuid]);++ // Phase 7 will use `searchQuery` to hide the Recent destinations row while typing.+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const [searchQuery, setSearchQuery] = useState('');++ function handlePickLocation(loc: any) {+ setActiveTargetLocationId(loc.uuid);+ setTargetPath(loc.path || '');+ }++ // Filter recents to those that match a currently-known location (so deleted+ // locations don't show stale chips). v1 also gates on the source location to+ // sidestep cross-location issues — recents from other locations are hidden.+ const visibleRecents = useMemo(() => {+ if (!sourceLocation) return [];+ return recents.filter(+ (r) =>+ r.locationId === sourceLocation.uuid &&+ !!locations.find((l) => l.uuid === r.locationId),+ );+ }, [recents, locations, sourceLocation?.uuid]);++ async function handleClickRecent(recent: {+ path: string;+ locationId: string;+ }) {+ const loc = findLocation(recent.locationId);+ if (!loc) {+ removeRecent(recent.locationId, recent.path);+ return;+ }+ try {+ // Validate the path still exists before jumping there.+ await loc.getPropertiesPromise(recent.path);+ setActiveTargetLocationId(loc.uuid);+ setTargetPath(recent.path);+ } catch (err) {+ removeRecent(recent.locationId, recent.path);+ showNotification(t('core:recentDestinationGone'), 'warning', true);+ }+ }const selectedFiles = currentEntries? currentEntries@@ -89,6 +171,17 @@ function MoveCopyFilesDialog(props: Props) {.map((fsentry) => fsentry.path): [];+ // Android can't move directories; if the selection includes dirs, force copy mode.+ const moveDisallowed = AppConfig.isAndroid && selectedDirs.length > 0;+ const [mode, setModeState] = useState<'move' | 'copy'>(+ moveDisallowed ? 'copy' : lastMoveCopyMode,+ );+ const setMode = (next: 'move' | 'copy') => {+ setModeState(next);+ dispatch(SettingsActions.setLastMoveCopyMode(next));+ };+ const itemCount = currentEntries ? currentEntries.length : 0;+useEffect(() => {// getDirProperties have Electron impl onlyif (@@ -123,6 +216,19 @@ function MoveCopyFilesDialog(props: Props) {});}+ function recordRecentDestination() {+ if (skipTargetPicker || !targetLocation || !targetPath) {+ return;+ }+ const sep = targetLocation.getDirSeparator?.() || '/';+ const leaf = extractFileName(targetPath, sep) || targetLocation.name;+ pushRecent({+ path: targetPath,+ locationId: targetLocation.uuid,+ label: leaf,+ });+ }+function generateThumbsForTransferred(sourceFilePaths: string[]) {if (!targetLocation) {return;@@ -218,120 +324,243 @@ function MoveCopyFilesDialog(props: Props) {onClose(true);}- function copyMove(copy: boolean) {+ function onPrimary() {+ const commit = () => {+ recordRecentDestination();+ if (mode === 'copy') {+ handleCopy();+ } else {+ handleMove();+ }+ };handleEntryExist(currentEntries, targetPath).then((exist) => {if (exist) {- openEntryExistDialog(exist, () => {- if (copy) {- handleCopy();- } else {- handleMove();- }- });+ openEntryExistDialog(exist, commit);} else {- if (copy) {- handleCopy();- } else {- handleMove();- }+ commit();}});}const theme = useTheme();const smallScreen = useMediaQuery(theme.breakpoints.down('md'));++ const dialogTitleText =+ mode === 'copy'+ ? t('core:copyNItems', { count: itemCount })+ : t('core:moveNItems', { count: itemCount });++ const validity = computeMoveCopyValidity({+ entries: currentEntries,+ targetPath,+ targetLocation,+ sourceLocation,+ mode,+ });+ const validityMessageKey = getValidityMessageKey(validity.reason);+ // Don't show inline error for the "no target chosen yet" state — empty state+ // is self-explanatory via the destination row's placeholder.+ const showInlineError = validity.disabled && !!validityMessageKey;+ const primaryDisabled = validity.disabled;++ const titleBlock = (+ <Box>+ <Typography+ component="div"+ variant="h6"+ id="mcf-title"+ sx={{ fontSize: '1.05rem', fontWeight: 600 }}+ >+ {dialogTitleText}+ </Typography>+ </Box>+ );+return (<Dialogopen={open}onClose={() => onClose()}keepMountedscroll="paper"- aria-labelledby="draggable-dialog-title"+ aria-labelledby="mcf-title"+ aria-describedby="mcf-subtitle"PaperComponent={smallScreen ? Paper : DraggablePaper}fullScreen={smallScreen}+ fullWidth+ maxWidth="sm"><TsDialogTitle- dialogTitle={t('core:copyMoveEntriesTitle')}+ dialogTitle={titleBlock}closeButtonTestId="closeMCFilesTID"onClose={onClose}/><DialogContent sx={{ overflowX: 'hidden', overflowY: 'auto' }}>- <Typography variant="subtitle2">- {t('selectedFilesAndFolders')}- </Typography>- <List- dense- sx={{- overflowY: 'auto',- width: '550px',- maxHeight: '200px',- }}- >- {currentEntries.length > 0 &&- currentEntries.map((entry) => (- <ListItem title={entry.path} key={entry.path}>- <ListItemIcon>- {entry.isFile ? <FileIcon /> : <FolderIcon />}- </ListItemIcon>- <Typography variant="subtitle2" noWrap>- {entry.name}- {dirProp.current[entry.path] &&- ' (' +- t('fileSize') +- ': ' +- formatBytes(dirProp.current[entry.path]['totalSize']) +- ')'}- </Typography>- </ListItem>- ))}- </List>- {!skipTargetPicker && (- <DirectoryListView- setTargetDir={setTargetPath}- targetPath={targetPath}- targetLocationID={targetLocation?.uuid}+ {/* Region 2: Selected-items summary (collapsible pill) */}+ <Box sx={{ marginBottom: 1.5 }}>+ <SelectedItemsSummary+ entries={currentEntries}+ dirProp={dirProp.current}+ defaultCollapsed={smallScreen || currentEntries.length >= 5}/>- )}- <Box sx={{ marginTop: '10px' }}>- {targetPath ? (- <Typography variant="subtitle2">- {t('moveCopyToPath') + ': ' + targetPath}- </Typography>- ) : (- <Typography variant="subtitle2">- {t('chooseTargetLocationAndPath')}- </Typography>- )}</Box>++ {/* Regions 3 + 4 + 6: Destination row + Tools row + Folder list (single composition) */}+ {!skipTargetPicker && targetLocation && (+ <>+ <Typography+ variant="overline"+ color="text.secondary"+ sx={{ display: 'block', marginTop: 1, marginBottom: 0.5 }}+ >+ {t('core:destination')}+ </Typography>+ {!smallScreen && !searchQuery && visibleRecents.length > 0 && (+ <Box sx={{ marginBottom: 1 }}>+ <Box+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 0.5,+ marginBottom: 0.5,+ color: 'text.secondary',+ }}+ >+ <AccessTimeIcon sx={{ fontSize: '0.9rem' }} />+ <Typography variant="caption" color="text.secondary">+ {t('core:recent')}+ </Typography>+ </Box>+ <Box+ sx={{+ display: 'flex',+ flexWrap: 'wrap',+ gap: 0.5,+ }}+ >+ {visibleRecents.map((r) => (+ <TsTooltip key={r.locationId + r.path} title={r.path}>+ <Chip+ variant="outlined"+ size="small"+ clickable+ icon={<FolderIcon style={{ fontSize: 14 }} />}+ label={r.label}+ onClick={() => handleClickRecent(r)}+ sx={{+ borderRadius: AppConfig.defaultCSSRadius,+ maxWidth: 200,+ }}+ />+ </TsTooltip>+ ))}+ </Box>+ </Box>+ )}+ <FolderBrowser+ locations={locations}+ activeLocationId={targetLocation.uuid}+ onActiveLocationChange={handlePickLocation}+ path={targetPath || targetLocation.path || ''}+ onPathChange={setTargetPath}+ onAddLocation={openCreateEditLocationDialog}+ disabledLocationIds={disabledLocationIds}+ locationDisabledTooltip={t('core:cloudCrossLocationNotSupported')}+ filter="folders"+ onCreateFolder={(parent) =>+ openCreateDirectoryDialog(parent, (newDirPath: string) =>+ setTargetPath(newDirPath),+ )+ }+ onQueryChange={setSearchQuery}+ listHeight={smallScreen ? '50vh' : 240}+ />+ {showInlineError && validityMessageKey && (+ <Box+ id="mcf-validity-error"+ role="alert"+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 0.75,+ marginTop: 1,+ color: 'error.main',+ }}+ >+ <WarningIcon fontSize="small" />+ <Typography variant="body2" color="error.main">+ {t(validityMessageKey)}+ </Typography>+ </Box>+ )}+ </>+ )}</DialogContent>- <TsDialogActions>- <TsButton data-tid="closeMoveCopyDialog" onClick={() => onClose()}>- {t('core:cancel')}- </TsButton>- {(!AppConfig.isAndroid || selectedDirs.length === 0) && (- <TsButton- data-tid="confirmMoveFiles"- disabled={- !targetPath ||- (!skipTargetPicker && targetPath === currentDirectoryPath)+ <TsDialogActions+ sx={{+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ rowGap: 1,+ }}+ >+ <ToggleButtonGroup+ value={mode}+ exclusive+ onChange={(_, next) => {+ if (next) {+ setMode(next);}- onClick={() => copyMove(false)}- variant="contained"+ }}+ aria-label={t('core:copyMoveEntriesTitle')}+ sx={{+ borderRadius: AppConfig.defaultCSSRadius,+ '& .MuiToggleButton-root': {+ // Align toggle button height with the adjacent TsButton small size.+ padding: '3px 11px',+ '&:first-of-type': {+ borderTopLeftRadius: AppConfig.defaultCSSRadius,+ borderBottomLeftRadius: AppConfig.defaultCSSRadius,+ },+ '&:last-of-type': {+ borderTopRightRadius: AppConfig.defaultCSSRadius,+ borderBottomRightRadius: AppConfig.defaultCSSRadius,+ },+ },+ }}+ >+ <TsToggleButton+ value="move"+ data-tid="mcfModeMove"+ disabled={moveDisallowed}+ sx={{ gap: mode === 'move' ? 0.5 : 0 }}>+ {mode === 'move' && <CheckIcon sx={{ fontSize: '1rem' }} />}{t('core:moveEntriesButton')}+ </TsToggleButton>+ <TsToggleButton+ value="copy"+ data-tid="mcfModeCopy"+ sx={{ gap: mode === 'copy' ? 0.5 : 0 }}+ >+ {mode === 'copy' && <CheckIcon sx={{ fontSize: '1rem' }} />}+ {t('core:copyEntriesButton')}+ </TsToggleButton>+ </ToggleButtonGroup>+ <Stack direction="row" spacing={1}>+ <TsButton data-tid="closeMoveCopyDialog" onClick={() => onClose()}>+ {t('core:cancel')}</TsButton>- )}- <TsButton- onClick={() => copyMove(true)}- data-tid="confirmCopyFiles"- disabled={- !targetPath ||- (!skipTargetPicker && targetPath === currentDirectoryPath)- }- variant="contained"- >- {t('core:copyEntriesButton')}- </TsButton>+ <TsButton+ data-tid={mode === 'copy' ? 'confirmCopyFiles' : 'confirmMoveFiles'}+ disabled={primaryDisabled}+ onClick={onPrimary}+ variant="contained"+ aria-describedby={+ showInlineError ? 'mcf-validity-error' : undefined+ }+ >+ {mode === 'copy' ? t('core:copyHere') : t('core:moveHere')}+ </TsButton>+ </Stack></TsDialogActions></Dialog>);diff --git a/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx b/src/renderer/components/dialogs/components/SelectedItemsSummary.tsxnew file mode 100644index 000000000..65858d2b4--- /dev/null+++ b/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx@@ -0,0 +1,297 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import AppConfig from '-/AppConfig';+import { FileIcon, FolderIcon } from '-/components/CommonIcons';+import FileExtBadge from '-/components/FileExtBadge';+import {+ getDefaultFolderColor,+ getSupportedFileTypes,+} from '-/reducers/settings';+import { findColorForEntry } from '-/services/utils-io';+import { TS } from '-/tagspaces.namespace';+import ExpandLess from '@mui/icons-material/ExpandLess';+import ExpandMore from '@mui/icons-material/ExpandMore';+import Box from '@mui/material/Box';+import ButtonBase from '@mui/material/ButtonBase';+import Collapse from '@mui/material/Collapse';+import List from '@mui/material/List';+import ListItem from '@mui/material/ListItem';+import ListItemIcon from '@mui/material/ListItemIcon';+import Paper from '@mui/material/Paper';+import Stack from '@mui/material/Stack';+import Typography from '@mui/material/Typography';+import { formatBytes } from '@tagspaces/tagspaces-common/misc';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useSelector } from 'react-redux';++type DirSize = { totalSize?: number };++interface Props {+ entries: TS.FileSystemEntry[];+ /** Pre-fetched directory sizes, keyed by directory path. */+ dirProp?: Record<string, DirSize>;+ /** When true (e.g. on <md or large selections), the pill starts collapsed. */+ defaultCollapsed?: boolean;+}++function getTotalSize(+ entries: TS.FileSystemEntry[],+ dirProp: Record<string, DirSize>,+): number {+ let total = 0;+ for (const entry of entries) {+ if (entry.isFile && typeof entry.size === 'number') {+ total += entry.size;+ } else if (!entry.isFile && dirProp[entry.path]?.totalSize) {+ total += dirProp[entry.path].totalSize as number;+ }+ }+ return total;+}++const TILE_SX = {+ minWidth: 36,+ height: 22,+ fontSize: 10,+ lineHeight: 1,+ padding: '0 4px',+} as const;++function ExtensionTile({+ entry,+ supportedFileTypes,+ defaultFolderColor,+}: {+ entry: TS.FileSystemEntry;+ supportedFileTypes: Array<any>;+ defaultFolderColor: string;+}) {+ const color = findColorForEntry(+ entry,+ supportedFileTypes,+ defaultFolderColor,+ );+ return (+ <FileExtBadge+ noWrap+ sx={{+ ...TILE_SX,+ backgroundColor: color,+ }}+ >+ {entry.isFile ? (+ entry.extension || '·'+ ) : (+ <FolderIcon style={{ fontSize: 14, color: 'white' }} />+ )}+ </FileExtBadge>+ );+}++function SelectedItemsSummary({ entries, dirProp, defaultCollapsed }: Props) {+ const { t } = useTranslation();+ const supportedFileTypes = useSelector(getSupportedFileTypes);+ const defaultFolderColor = useSelector(getDefaultFolderColor);+ const itemCount = entries.length;+ const [expanded, setExpanded] = useState(!defaultCollapsed);++ if (itemCount === 0) {+ return null;+ }++ const totalSize = getTotalSize(entries, dirProp || {});+ const sizeLabel = totalSize > 0 ? formatBytes(totalSize) : null;++ // Single-item shortcut — no collapsible chrome.+ if (itemCount === 1) {+ const entry = entries[0];+ const itemSize = entry.isFile+ ? entry.size+ : dirProp?.[entry.path]?.totalSize;+ return (+ <Paper+ variant="outlined"+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 1.25,+ padding: '8px 12px',+ width: '100%',+ boxSizing: 'border-box',+ borderRadius: AppConfig.defaultCSSRadius,+ }}+ >+ <ExtensionTile+ entry={entry}+ supportedFileTypes={supportedFileTypes}+ defaultFolderColor={defaultFolderColor}+ />+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <Typography variant="body2" noWrap title={entry.path}>+ {entry.name}+ </Typography>+ </Box>+ {typeof itemSize === 'number' && itemSize > 0 && (+ <Typography+ variant="caption"+ color="text.secondary"+ sx={{ flexShrink: 0 }}+ >+ {formatBytes(itemSize)}+ </Typography>+ )}+ </Paper>+ );+ }++ const visibleTiles = entries.slice(0, 3);+ const overflowCount = itemCount - visibleTiles.length;++ return (+ <Box sx={{ width: '100%' }}>+ <Paper+ variant="outlined"+ sx={{+ width: '100%',+ boxSizing: 'border-box',+ borderRadius: AppConfig.defaultCSSRadius,+ overflow: 'hidden',+ }}+ >+ <ButtonBase+ onClick={() => setExpanded((v) => !v)}+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 1.25,+ padding: '8px 12px',+ width: '100%',+ justifyContent: 'flex-start',+ textAlign: 'left',+ }}+ aria-expanded={expanded}+ aria-label={t('core:selectedFilesAndFolders')}+ >+ <Stack+ direction="row"+ sx={{+ flexShrink: 0,+ '& > :not(:first-of-type)': { marginLeft: '-6px' },+ }}+ >+ {visibleTiles.map((entry) => (+ <ExtensionTile+ key={entry.path}+ entry={entry}+ supportedFileTypes={supportedFileTypes}+ defaultFolderColor={defaultFolderColor}+ />+ ))}+ {overflowCount > 0 && (+ <Box+ sx={{+ ...TILE_SX,+ marginLeft: '-6px',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderRadius: 1,+ backgroundColor: 'action.selected',+ color: 'text.primary',+ fontWeight: 600,+ fontSize: 10,+ }}+ >+ +{overflowCount}+ </Box>+ )}+ </Stack>+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <Typography variant="body2" component="span" noWrap>+ <Box component="strong" sx={{ fontWeight: 600 }}>+ {t('core:itemCount', { count: itemCount })}+ </Box>+ {sizeLabel && (+ <Typography+ component="span"+ variant="body2"+ color="text.secondary"+ sx={{ marginLeft: 0.75 }}+ >+ · {sizeLabel}+ </Typography>+ )}+ </Typography>+ </Box>+ {expanded ? (+ <ExpandLess fontSize="small" />+ ) : (+ <ExpandMore fontSize="small" />+ )}+ </ButtonBase>+ <Collapse in={expanded} unmountOnExit>+ <Box sx={{ borderTop: '1px solid', borderColor: 'divider' }}>+ <List+ dense+ sx={{+ overflowY: 'auto',+ maxHeight: '200px',+ paddingY: 0,+ }}+ >+ {entries.map((entry) => {+ const itemSize = entry.isFile+ ? entry.size+ : dirProp?.[entry.path]?.totalSize;+ const sizeText =+ typeof itemSize === 'number' && itemSize > 0+ ? formatBytes(itemSize)+ : null;+ return (+ <ListItem title={entry.path} key={entry.path} sx={{ gap: 1 }}>+ <ListItemIcon sx={{ minWidth: 32 }}>+ {entry.isFile ? <FileIcon /> : <FolderIcon />}+ </ListItemIcon>+ <Box sx={{ flex: 1, minWidth: 0 }}>+ <Typography variant="body2" noWrap>+ {entry.name}+ </Typography>+ </Box>+ {sizeText && (+ <Typography+ variant="caption"+ color="text.secondary"+ sx={{ flexShrink: 0, whiteSpace: 'nowrap' }}+ >+ {sizeText}+ </Typography>+ )}+ </ListItem>+ );+ })}+ </List>+ </Box>+ </Collapse>+ </Paper>+ </Box>+ );+}++export default SelectedItemsSummary;diff --git a/src/renderer/components/dialogs/components/computeMoveCopyValidity.ts b/src/renderer/components/dialogs/components/computeMoveCopyValidity.tsnew file mode 100644index 000000000..2c5d73ac6--- /dev/null+++ b/src/renderer/components/dialogs/components/computeMoveCopyValidity.ts@@ -0,0 +1,126 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';+import { extractContainingDirectoryPath } from '@tagspaces/tagspaces-common/paths';++export type MoveCopyInvalidReason =+ | 'no-target'+ | 'cyclic'+ | 'noop'+ | 'readonly'+ | 'cloud-cross-location';++export interface MoveCopyValidity {+ disabled: boolean;+ reason?: MoveCopyInvalidReason;+}++function isCloud(loc?: CommonLocation): boolean {+ // WebDAV is deprecated and not considered; only S3 counts as cloud here.+ return !!loc && loc.haveObjectStoreSupport();+}++function normalize(p: string): string {+ if (!p) return '';+ // Strip a trailing separator (either kind) so descendant checks compare cleanly.+ return p.replace(/[\\/]+$/, '').replace(/\\/g, '/');+}++interface Params {+ entries: TS.FileSystemEntry[];+ targetPath: string;+ targetLocation?: CommonLocation;+ sourceLocation?: CommonLocation;+ mode: 'move' | 'copy';+}++export function computeMoveCopyValidity({+ entries,+ targetPath,+ targetLocation,+ sourceLocation,+ mode,+}: Params): MoveCopyValidity {+ if (!targetPath || !targetLocation) {+ return { disabled: true, reason: 'no-target' };+ }++ // Read-only destination — always disabled.+ if (targetLocation.isReadOnly) {+ return { disabled: true, reason: 'readonly' };+ }++ // Cloud cross-location — v1 limitation.+ // TODO(cloud-cross-location): drop this branch when copyFiles/moveFiles gain+ // a download-then-upload pipeline that handles S3↔local, WebDAV↔local, and+ // S3↔S3-across-buckets with unified progress reporting + sidecar transfer.+ // See MOVE_COPY_DIALOG_REDESIGN_PLAN.md "Out of scope" for the followup spec.+ if (+ sourceLocation &&+ targetLocation.uuid !== sourceLocation.uuid &&+ (isCloud(targetLocation) || isCloud(sourceLocation))+ ) {+ return { disabled: true, reason: 'cloud-cross-location' };+ }++ const target = normalize(targetPath);+ const selectedDirs = entries.filter((e) => !e.isFile);+ const sep = targetLocation.getDirSeparator?.() || '/';++ // Cyclic: target is one of the selected folders or descendant of one.+ for (const d of selectedDirs) {+ const dp = normalize(d.path);+ if (!dp) continue;+ if (target === dp || target.startsWith(dp + '/')) {+ return { disabled: true, reason: 'cyclic' };+ }+ }++ // No-op move: target equals the parent dir of every selected entry.+ if (mode === 'move' && entries.length > 0) {+ const allInTarget = entries.every((entry) => {+ const parent = normalize(extractContainingDirectoryPath(entry.path, sep));+ return parent === target;+ });+ if (allInTarget) {+ return { disabled: true, reason: 'noop' };+ }+ }++ return { disabled: false };+}++export function getValidityMessageKey(+ reason?: MoveCopyInvalidReason,+): string | undefined {+ switch (reason) {+ case 'cyclic':+ return 'core:cantMoveIntoSelectedFolder';+ case 'noop':+ return 'core:filesAlreadyInThisFolder';+ case 'readonly':+ return 'core:locationIsReadOnly';+ case 'cloud-cross-location':+ return 'core:cloudCrossLocationNotSupported';+ case 'no-target':+ default:+ return undefined;+ }+}diff --git a/src/renderer/containers/Root.tsx b/src/renderer/containers/Root.tsxindex e29dc682a..2eef9cd16 100644--- a/src/renderer/containers/Root.tsx+++ b/src/renderer/containers/Root.tsx@@ -33,6 +33,7 @@ import { ExtensionsContextProvider } from '-/hooks/ExtensionsContextProvider';import { FSWatcherContextProvider } from '-/hooks/FSWatcherContextProvider';import { FileUploadContextProvider } from '-/hooks/FileUploadContextProvider';import { HistoryContextProvider } from '-/hooks/HistoryContextProvider';+import { RecentDestinationsContextProvider } from '-/hooks/RecentDestinationsContextProvider';import { IOActionsContextProvider } from '-/hooks/IOActionsContextProvider';import { LocationIndexContextProvider } from '-/hooks/LocationIndexContextProvider';import { NotificationContextProvider } from '-/hooks/NotificationContextProvider';@@ -138,6 +139,7 @@ const SHARED_PROVIDERS = [FileUploadContextProvider,FileUploadDialogContextProvider,HistoryContextProvider,+ RecentDestinationsContextProvider,] as React.ComponentType<any>[];export default function Root({ store, persistor }: RootType) {diff --git a/src/renderer/hooks/RecentDestinationsContextProvider.tsx b/src/renderer/hooks/RecentDestinationsContextProvider.tsxnew file mode 100644index 000000000..05c69979b--- /dev/null+++ b/src/renderer/hooks/RecentDestinationsContextProvider.tsx@@ -0,0 +1,165 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import { getMaxRecentMoveCopyDestinations } from '-/reducers/settings';+import { instanceId } from '-/services/utils-io';+import React, {+ createContext,+ useContext,+ useEffect,+ useMemo,+ useReducer,+ useRef,+} from 'react';+import { useSelector } from 'react-redux';++export interface RecentDestination {+ /** Absolute path within the location. */+ path: string;+ /** Stable location identifier. */+ locationId: string;+ /** Short label for the chip (typically the leaf folder name). */+ label: string;+ /** Timestamp at the moment of insertion. */+ ts: number;+}++interface RecentDestinationsContextData {+ recents: RecentDestination[];+ pushRecent: (item: Omit<RecentDestination, 'ts'>) => void;+ removeRecent: (locationId: string, path: string) => void;+ clearRecents: () => void;+}++const STORAGE_KEY = 'tsRecentMoveCopyDestinations';+const BROADCAST_KEY = 'recent-destinations-sync';++export const RecentDestinationsContext =+ createContext<RecentDestinationsContextData>({+ recents: [],+ pushRecent: () => undefined,+ removeRecent: () => undefined,+ clearRecents: () => undefined,+ });++function readRecents(): RecentDestination[] {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (!raw) return [];+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed) ? parsed : [];+ } catch (e) {+ console.warn('RecentDestinations: failed to parse storage', e);+ return [];+ }+}++function writeRecents(list: RecentDestination[]) {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(list));+ } catch (e) {+ console.warn('RecentDestinations: failed to write storage', e);+ }+}++export const useRecentDestinationsContext = () =>+ useContext(RecentDestinationsContext);++export type RecentDestinationsProviderProps = {+ children: React.ReactNode;+};++export const RecentDestinationsContextProvider = ({+ children,+}: RecentDestinationsProviderProps) => {+ const cap = useSelector(getMaxRecentMoveCopyDestinations);+ const recents = useRef<RecentDestination[]>(readRecents());+ const [, forceUpdate] = useReducer((x) => x + 1, 0);++ useEffect(() => {+ const channel = new BroadcastChannel(BROADCAST_KEY);+ channel.onmessage = (event: MessageEvent) => {+ const msg = event.data as { uuid: string };+ if (msg && msg.uuid !== instanceId) {+ recents.current = readRecents();+ forceUpdate();+ }+ };+ return () => {+ channel.close();+ };+ }, []);++ function broadcast() {+ try {+ const channel = new BroadcastChannel(BROADCAST_KEY);+ channel.postMessage({ uuid: instanceId });+ channel.close();+ } catch (e) {+ // BroadcastChannel may be unavailable in some environments — silent.+ }+ }++ function pushRecent(item: Omit<RecentDestination, 'ts'>) {+ if (!item.path || !item.locationId || cap <= 0) {+ return;+ }+ const next: RecentDestination = { ...item, ts: Date.now() };+ // Dedupe by (locationId, path); newest first; cap.+ const filtered = recents.current.filter(+ (r) => !(r.locationId === item.locationId && r.path === item.path),+ );+ filtered.unshift(next);+ recents.current = filtered.slice(0, cap);+ writeRecents(recents.current);+ forceUpdate();+ broadcast();+ }++ function removeRecent(locationId: string, path: string) {+ recents.current = recents.current.filter(+ (r) => !(r.locationId === locationId && r.path === path),+ );+ writeRecents(recents.current);+ forceUpdate();+ broadcast();+ }++ function clearRecents() {+ recents.current = [];+ writeRecents(recents.current);+ forceUpdate();+ broadcast();+ }++ const value = useMemo<RecentDestinationsContextData>(+ () => ({+ recents: recents.current,+ pushRecent,+ removeRecent,+ clearRecents,+ }),+ [recents.current],+ );++ return (+ <RecentDestinationsContext.Provider value={value}>+ {children}+ </RecentDestinationsContext.Provider>+ );+};diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex 7a8e14974..748b621bd 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -22,6 +22,29 @@"chooseTargetLocationAndPath": "Choose target location and path","moveEntriesButton": "Move","copyEntriesButton": "Copy",+ "moveNItems_one": "Move {{count}} item",+ "moveNItems_other": "Move {{count}} items",+ "copyNItems_one": "Copy {{count}} item",+ "copyNItems_other": "Copy {{count}} items",+ "itemCount_one": "{{count}} item",+ "itemCount_other": "{{count}} items",+ "moveHere": "Move here",+ "copyHere": "Copy here",+ "destination": "Destination",+ "recent": "Recent",+ "switchLocation": "Switch location",+ "addLocationEllipsis": "Add location…",+ "localLocations": "Local",+ "cloudLocations": "Cloud",+ "upOneLevel": "Up one level",+ "cloudCrossLocationNotSupported": "Cross-location move/copy not yet supported for cloud locations.",+ "cantMoveIntoSelectedFolder": "Can't move into a selected folder.",+ "filesAlreadyInThisFolder": "Files are already in this folder.",+ "locationIsReadOnly": "This location is read-only.",+ "thisFolderIsEmpty": "This folder is empty.",+ "noFoldersMatch": "No folders match.",+ "filterFolders": "Filter folders",+ "recentDestinationGone": "That folder is no longer available.","sortByName": "Name","addTagsToGroupTitle": "Add tags to tag group","addTagsToGroupTagsPlaceholder": "Comma separated list of tags",diff --git a/src/renderer/reducers/settings-default.ts b/src/renderer/reducers/settings-default.tsindex 9a642d737..bb4cdb735 100644--- a/src/renderer/reducers/settings-default.ts+++ b/src/renderer/reducers/settings-default.ts@@ -123,6 +123,8 @@ export default {tsLastOpenedFoldersHistory: 10,tsLastEditedFilesHistory: 10,tsSearchHistory: 10,+ tsRecentMoveCopyDestinations: 5,+ lastMoveCopyMode: 'move' as 'move' | 'copy',storedSearchesVisible: true,showBookmarks: true,fileOpenHistory: false,diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.tsindex 0d2fd6ee7..ae47b68a1 100644--- a/src/renderer/reducers/settings.ts+++ b/src/renderer/reducers/settings.ts@@ -110,6 +110,7 @@ export const types = {SET_FILE_OPEN_HISTORY: 'SET_FILE_OPEN_HISTORY',SET_FOLDER_OPEN_HISTORY: 'SET_FOLDER_OPEN_HISTORY',SET_FILE_EDIT_HISTORY: 'SET_FILE_EDIT_HISTORY',+ SET_LAST_MOVE_COPY_MODE: 'SETTINGS/SET_LAST_MOVE_COPY_MODE',SET_HIDE_PRO_FEATURES: 'SETTINGS/SET_HIDE_PRO_FEATURES',SET_AUTO_SAVE_DESCRIPTION: 'SETTINGS/SET_AUTO_SAVE_DESCRIPTION',SET_PERSPECTIVE_ENABLED: 'SETTINGS/SET_PERSPECTIVE_ENABLED',@@ -542,6 +543,12 @@ export default (state: any = defaultSettings, action: any) => {folderOpenHistory: action.folderOpenHistory,};}+ case types.SET_LAST_MOVE_COPY_MODE: {+ return {+ ...state,+ lastMoveCopyMode: action.mode,+ };+ }case types.SET_FILE_EDIT_HISTORY: {return {...state,@@ -968,6 +975,10 @@ export const actions = {type: types.SET_FILE_EDIT_HISTORY,fileEditHistory,}),+ setLastMoveCopyMode: (mode: 'move' | 'copy') => ({+ type: types.SET_LAST_MOVE_COPY_MODE,+ mode,+ }),checkForUpdate: () => (dispatch: (actions: Object) => void) => {getLastVersionPromise().then((lastVersion) => {@@ -1022,6 +1033,13 @@ export const getMapTileServer = (state: any): TS.MapTileServer =>export const getMapTileServers = (state: any): Array<TS.MapTileServer> =>AppConfig.ExtMapTileServers || state.settings.mapTileServers;export const getSettings = (state: any) => state.settings;+export const getMaxRecentMoveCopyDestinations = (state: any): number => {+ const v = state.settings.tsRecentMoveCopyDestinations;+ return typeof v === 'number' && v >= 0 ? v : 6;+};+export const getLastMoveCopyMode = (state: any): 'move' | 'copy' => {+ return state.settings.lastMoveCopyMode === 'copy' ? 'copy' : 'move';+};export const getEnableWS = (state: any) => state.settings.enableWS;export const getDesktopMode = (state: any) => {if (typeof AppConfig.ExtDisplayMode === 'undefined') {diff --git a/tests/e2e/folder.pw.e2e.js b/tests/e2e/folder.pw.e2e.jsindex f3f0b0bc9..9b9c31d26 100644--- a/tests/e2e/folder.pw.e2e.js+++ b/tests/e2e/folder.pw.e2e.js@@ -218,6 +218,7 @@ test.describe('TST01 - Folder management', () => {await setInputValue('[data-tid=directoryName] input', folderToCopy);await clickOn('[data-tid=confirmCreateNewDirectory]');await clickOn('[data-tid=MoveTarget' + folderToCopy + ']');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');await clickOn('[data-tid=location_' + defaultLocationName + ']');@@ -274,6 +275,7 @@ test.describe('TST01 - Folder management', () => {'fileMenuMoveCopyFile',);await clickOn('[data-tid=MoveTargetempty_folder]');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');@@ -283,6 +285,7 @@ test.describe('TST01 - Folder management', () => {'fileMenuMoveCopyFile',);await clickOn('[data-tid=MoveTargetempty_folder]');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');diff --git a/tests/e2e/folderprops.pw.e2e.js b/tests/e2e/folderprops.pw.e2e.jsindex c20d632ca..c801b9042 100644--- a/tests/e2e/folderprops.pw.e2e.js+++ b/tests/e2e/folderprops.pw.e2e.js@@ -252,6 +252,7 @@ test.describe('TST02 - Folder properties', () => {'fileMenuMoveCopyFile',);await clickOn('[data-tid=MoveTargetempty_folder]');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');await clickOn('[data-tid=changePerspectiveTID]', {diff --git a/tests/e2e/move-copy-dialog.pw.e2e.js b/tests/e2e/move-copy-dialog.pw.e2e.jsnew file mode 100644index 000000000..b6695e1d8--- /dev/null+++ b/tests/e2e/move-copy-dialog.pw.e2e.js@@ -0,0 +1,220 @@+/*+ * Copyright (c) 2016-present - TagSpaces GmbH. All rights reserved.+ */+import { expect, test } from './fixtures';+import {+ clickOn,+ clickOnIfVisible,+ expectElementExist,+ getGridFileSelector,+ setInputValue,+} from './general.helpers';+import { startTestingApp, stopApp } from './hook';+import {+ createPwLocation,+ createS3Location,+ defaultLocationName,+} from './location.helpers';+import { openContextEntryMenu } from './test-utils';+import { clearDataStorage, closeWelcomePlaywright } from './welcome.helpers';++test.beforeAll(async ({ isWeb, isS3, webServerPort }, testInfo) => {+ if (isS3) {+ await startTestingApp({ isWeb, isS3, webServerPort, testInfo });+ await closeWelcomePlaywright();+ } else {+ await startTestingApp(+ { isWeb, isS3, webServerPort, testInfo },+ 'extconfig.js',+ );+ }+});++test.afterAll(async () => {+ await stopApp();+});++test.afterEach(async () => {+ await clearDataStorage();+});++test.beforeEach(async ({ isS3, testDataDir }) => {+ if (isS3) {+ await createS3Location('', defaultLocationName, true);+ await closeWelcomePlaywright();+ } else {+ await createPwLocation(testDataDir, defaultLocationName, true);+ }+ await clickOn('[data-tid=location_' + defaultLocationName + ']');+ await expectElementExist(getGridFileSelector('empty_folder'), true, 15000);+});++async function openMoveCopyDialogForEmptyFolder() {+ await openContextEntryMenu(+ '[data-tid=fsEntryName_empty_folder]',+ 'fileMenuMoveCopyDirectoryTID',+ );+ // Wait for the dialog primary CTA — default mode is Move → confirmMoveFiles+ await expectElementExist('[data-tid=confirmMoveFiles]', true, 10000);+}++async function closeMoveCopyDialog() {+ await clickOnIfVisible('[data-tid=closeMoveCopyDialog]', 3000);+}++test.describe('TST10 - Move/Copy dialog new features', () => {+ test('TST1001 - Mode toggle switches the primary CTA [web,s3,electron]', async () => {+ await openMoveCopyDialogForEmptyFolder();++ // Default Move → confirmMoveFiles is present, confirmCopyFiles is not+ await expectElementExist('[data-tid=confirmMoveFiles]', true, 5000);+ await expectElementExist('[data-tid=confirmCopyFiles]', false, 1500);++ // Switch to Copy mode+ await clickOn('[data-tid=mcfModeCopy]');+ await expectElementExist('[data-tid=confirmCopyFiles]', true, 5000);+ await expectElementExist('[data-tid=confirmMoveFiles]', false, 1500);++ // Back to Move+ await clickOn('[data-tid=mcfModeMove]');+ await expectElementExist('[data-tid=confirmMoveFiles]', true, 5000);++ await closeMoveCopyDialog();+ });++ test('TST1002 - Search filters the folder list [web,s3,electron]', async () => {+ await openMoveCopyDialogForEmptyFolder();++ // The picker should list empty_folder as a target at root+ await expectElementExist('[data-tid=MoveTargetempty_folder]', true, 5000);++ // Typing a non-matching query filters it out+ await setInputValue(+ '[data-tid=folderBrowserSearch]',+ 'no-such-folder-name-xyz',+ );+ await expectElementExist('[data-tid=MoveTargetempty_folder]', false, 3000);++ // Clearing brings it back+ await setInputValue('[data-tid=folderBrowserSearch]', '');+ await expectElementExist('[data-tid=MoveTargetempty_folder]', true, 3000);++ await closeMoveCopyDialog();+ });++ test('TST1003 - Up button returns to the parent folder [web,s3,electron]', async () => {+ await openMoveCopyDialogForEmptyFolder();++ // Descend into empty_folder via the picker+ await expectElementExist('[data-tid=MoveTargetempty_folder]', true, 5000);+ await clickOn('[data-tid=MoveTargetempty_folder]');++ // Now we're inside empty_folder — empty_folder itself is no longer a row+ await expectElementExist('[data-tid=MoveTargetempty_folder]', false, 3000);++ // Click Up+ await clickOn('[data-tid=navigateToParentTID]');++ // empty_folder reappears at root+ await expectElementExist('[data-tid=MoveTargetempty_folder]', true, 5000);++ await closeMoveCopyDialog();+ });++ test('TST1004 - Mode toggle is persisted across dialog opens [web,s3,electron]', async () => {+ // Open dialog and switch to Copy mode+ await openMoveCopyDialogForEmptyFolder();+ await clickOn('[data-tid=mcfModeCopy]');+ await expectElementExist('[data-tid=confirmCopyFiles]', true, 5000);+ await closeMoveCopyDialog();++ // Reopen — should default to Copy mode now (persisted via lastMoveCopyMode setting)+ await openContextEntryMenu(+ '[data-tid=fsEntryName_empty_folder]',+ 'fileMenuMoveCopyDirectoryTID',+ );+ await expectElementExist('[data-tid=confirmCopyFiles]', true, 10000);++ // Reset to Move for subsequent tests+ await clickOn('[data-tid=mcfModeMove]');+ await closeMoveCopyDialog();+ });++ test('TST1005 - Location picker opens with grouped locations [web,s3,electron]', async () => {+ await openMoveCopyDialogForEmptyFolder();++ // The LocationPicker trigger sits inside the destination row+ await expectElementExist(+ '[data-tid=folderBrowserLocationPicker]',+ true,+ 5000,+ );++ // Click to open the menu and verify the current location is in the menu+ await clickOn('[data-tid=folderBrowserLocationPicker]');+ await expectElementExist(+ '[data-tid=folderBrowserLocationItem_' + defaultLocationName + ']',+ true,+ 5000,+ );++ // Close the menu — press Escape+ await global.client.keyboard.press('Escape');+ await closeMoveCopyDialog();+ });++ test('TST1006 - Search + Copy commits the operation [electron,_pro]', async () => {+ // Use a pre-existing file from the test data root (same pattern as TST0114)+ // — avoids a create-then-wait-for-refresh dance.+ const fileName = 'sample.txt';++ // Open the dialog from the file's context menu+ await openContextEntryMenu(+ getGridFileSelector(fileName),+ 'fileMenuMoveCopyFile',+ );+ await expectElementExist('[data-tid=confirmMoveFiles]', true, 10000);++ // Filter to a folder via search+ await setInputValue('[data-tid=folderBrowserSearch]', 'empty');+ await expectElementExist('[data-tid=MoveTargetempty_folder]', true, 5000);++ // Pick the destination (descends into it — targetPath becomes empty_folder)+ await clickOn('[data-tid=MoveTargetempty_folder]');++ // Switch to Copy mode and commit+ await clickOn('[data-tid=mcfModeCopy]');+ await clickOn('[data-tid=confirmCopyFiles]');+ await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');++ // Source file should still be at the root+ await clickOn('[data-tid=location_' + defaultLocationName + ']');+ await expectElementExist(getGridFileSelector(fileName), true, 5000);++ // Destination folder should contain the copy+ await global.client.dblclick(getGridFileSelector('empty_folder'));+ await expectElementExist(getGridFileSelector(fileName), true, 5000);+ });++ test('TST1007 - Cyclic move guard disables primary CTA [web,s3,electron]', async () => {+ // Open the dialog on a folder; the source is `empty_folder` itself.+ await openContextEntryMenu(+ '[data-tid=fsEntryName_empty_folder]',+ 'fileMenuMoveCopyDirectoryTID',+ );+ await expectElementExist('[data-tid=confirmMoveFiles]', true, 10000);++ // Descend INTO empty_folder via the picker — target now equals the source+ // folder, which is the cyclic case validity guards against.+ await clickOn('[data-tid=MoveTargetempty_folder]');++ // Inline error row appears with the stable id used by aria-describedby.+ await expectElementExist('#mcf-validity-error', true, 5000);++ // And the Move primary is disabled.+ const moveBtn = global.client.locator('[data-tid=confirmMoveFiles]');+ expect(await moveBtn.isDisabled()).toBe(true);++ await closeMoveCopyDialog();+ });+});diff --git a/tests/e2e/perspective-grid-right-button.pw.e2e.js b/tests/e2e/perspective-grid-right-button.pw.e2e.jsindex 996a03590..c1ba4e6c0 100644--- a/tests/e2e/perspective-grid-right-button.pw.e2e.js+++ b/tests/e2e/perspective-grid-right-button.pw.e2e.js@@ -350,6 +350,7 @@ test.describe('TST50** - Right button on a file', () => {// Copy file in parent directoryawait openContextEntryMenu(fileSelector, 'fileMenuMoveCopyFile');await clickOn('[data-tid=navigateToParentTID]');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');diff --git a/tests/e2e/perspective-grid.pw.e2e.js b/tests/e2e/perspective-grid.pw.e2e.jsindex d24344def..fce276753 100644--- a/tests/e2e/perspective-grid.pw.e2e.js+++ b/tests/e2e/perspective-grid.pw.e2e.js@@ -165,6 +165,7 @@ test.describe('TST50 - Perspective Grid', () => {// open Copy/Move File Dialogawait clickOn('[data-tid=gridPerspectiveCopySelectedFiles]');await clickOn('[data-tid=MoveTargetempty_folder]');+ await clickOn('[data-tid=mcfModeCopy]');await clickOn('[data-tid=confirmCopyFiles]');await clickOnIfVisible('[data-tid=uploadCloseAndClearTID]');