TagSpaces is an offline, open source, document manager with tagging support
Integrate drag for selecting files in grid and list perspectvie (#2242)
Stanimir0db0e8a04f1b
diff --git a/src/renderer/components/DragItemTypes.tsx b/src/renderer/components/DragItemTypes.tsxindex c20df67db..86e41d6b9 100644--- a/src/renderer/components/DragItemTypes.tsx+++ b/src/renderer/components/DragItemTypes.tsx@@ -20,4 +20,5 @@ export default {TAG: 'tag',TAG_GROUP: 'tag_group',FILE: 'file_move',+ SELECTION: 'selection',};diff --git a/src/renderer/components/drag/SelectionArea.tsx b/src/renderer/components/drag/SelectionArea.tsxnew file mode 100644index 000000000..a875f2a00--- /dev/null+++ b/src/renderer/components/drag/SelectionArea.tsx@@ -0,0 +1,75 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2025-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/>.+ *+ */++// **********************************************************************+// Selection Area Component+// **********************************************************************+//+// This component covers the full area where selection is enabled.+// It uses React DnD’s useDrag so that a drag gesture anywhere in the+// container will produce the selection rectangle. When the drag ends,+// it computes the rectangle (in viewport coordinates) and passes it+// to an onSelect callback.+//+import DragItemTypes from '-/components/DragItemTypes';+import React, { useEffect } from 'react';+import { useDrag } from 'react-dnd';+import { getEmptyImage } from 'react-dnd-html5-backend';++interface SelectionAreaProps {+ onSelect: (rect: DOMRect) => void;+ children: React.ReactNode;+}++export const SelectionArea: React.FC<SelectionAreaProps> = ({+ onSelect,+ children,+}) => {+ // useDrag returns a ref that you attach to the element that should capture+ // drag events. Here we use it on the container.+ const [, drag, preview] = useDrag({+ type: DragItemTypes.SELECTION,+ // No payload is needed here+ item: {},+ end: (_, monitor) => {+ const initialOffset = monitor.getInitialClientOffset();+ const dropOffset = monitor.getClientOffset();+ if (initialOffset && dropOffset) {+ // Compute rectangle coordinates based on the drag's start and end points+ const x = Math.min(initialOffset.x, dropOffset.x);+ const y = Math.min(initialOffset.y, dropOffset.y);+ const width = Math.abs(initialOffset.x - dropOffset.x);+ const height = Math.abs(initialOffset.y - dropOffset.y);+ // Create a DOMRect-like object (DOMRect constructor is available in modern browsers)+ const rect = new DOMRect(x, y, width, height);+ onSelect(rect);+ }+ },+ });++ // Disable the default drag preview by using an empty image.+ useEffect(() => {+ preview(getEmptyImage(), { captureDraggingState: true });+ }, [preview]);++ return (+ <div ref={drag} style={{ height: '100%' }}>+ {children}+ </div>+ );+};diff --git a/src/renderer/components/drag/SelectionDragLayer.tsx b/src/renderer/components/drag/SelectionDragLayer.tsxnew file mode 100644index 000000000..7801a4718--- /dev/null+++ b/src/renderer/components/drag/SelectionDragLayer.tsx@@ -0,0 +1,86 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2025-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/>.+ *+ */++// **********************************************************************+// Custom Drag Layer for Rendering the Selection Rectangle+// **********************************************************************+//+// This component uses useDragLayer to tap into the current drag state+// and renders a rectangle that goes from the initial drag point to the+// current pointer location.+//+import DragItemTypes from '-/components/DragItemTypes';+import { alpha, useTheme } from '@mui/material/styles';+import React from 'react';+import { useDragLayer } from 'react-dnd';++const SelectionDragLayer: React.FC = () => {+ const theme = useTheme();+ const { isDragging, itemType, initialOffset, currentOffset } = useDragLayer(+ (monitor) => ({+ isDragging: monitor.isDragging(),+ itemType: monitor.getItemType(),+ initialOffset: monitor.getInitialClientOffset(),+ currentOffset: monitor.getClientOffset(),+ }),+ );++ // Only render the selection rectangle when dragging with the selection type.+ if (+ !isDragging ||+ itemType !== DragItemTypes.SELECTION ||+ !initialOffset ||+ !currentOffset+ ) {+ return null;+ }++ // Compute rectangle geometry based on the initial and current pointer locations+ const x = Math.min(initialOffset.x, currentOffset.x);+ const y = Math.min(initialOffset.y, currentOffset.y);+ const width = Math.abs(initialOffset.x - currentOffset.x);+ const height = Math.abs(initialOffset.y - currentOffset.y);++ const layerStyle: React.CSSProperties = {+ position: 'fixed',+ pointerEvents: 'none',+ left: 0,+ top: 0,+ width: '100%',+ height: '100%',+ zIndex: 1000,+ };++ return (+ <div style={layerStyle}>+ <div+ style={{+ position: 'absolute',+ left: x,+ top: y,+ width,+ height,+ border: '1px dashed black',+ backgroundColor: alpha(theme.palette.primary.main, 0.1),+ }}+ />+ </div>+ );+};++export default SelectionDragLayer;diff --git a/src/renderer/perspectives/grid/components/GridPagination.tsx b/src/renderer/perspectives/grid/components/GridPagination.tsxindex 28c7cfce3..32f774ad6 100644--- a/src/renderer/perspectives/grid/components/GridPagination.tsx+++ b/src/renderer/perspectives/grid/components/GridPagination.tsx@@ -41,6 +41,8 @@ import GridCellsContainer from './GridCellsContainer';import { dataTidFormat } from '-/services/test';import CellView from '-/perspectives/common/CellView';import { useSortedDirContext } from '-/perspectives/grid/hooks/useSortedDirContext';+import SelectionDragLayer from '-/components/drag/SelectionDragLayer';+import { SelectionArea } from '-/components/drag/SelectionArea';interface Props {desktopMode: boolean;@@ -159,6 +161,41 @@ function GridPagination(props: Props) {folderSummary = selectedEntries.length + ' entries selected';}+ // **********************************************************************+ // Utility: Check if Two Rectangles Intersect+ // **********************************************************************+ const rectIntersects = (r1: DOMRect, r2: DOMRect): boolean => {+ return !(+ r2.left > r1.right ||+ r2.right < r1.left ||+ r2.top > r1.bottom ||+ r2.bottom < r1.top+ );+ };++ // Called when a selection drag ends. We look for any item elements whose+ // bounding rectangle intersects the drag rectangle.+ const handleSelect = (selectionRect: DOMRect) => {+ const container = containerEl.current;+ if (!container) return;++ const newlySelected: string[] = [];+ // Find all elements that represent items (we use the data-item attribute)+ const itemElements = container.querySelectorAll('[data-entry-id]');+ itemElements.forEach((el) => {+ const itemRect = el.getBoundingClientRect();+ if (rectIntersects(selectionRect, itemRect)) {+ const id = el.getAttribute('data-entry-id');+ newlySelected.push(id);+ }+ });+ if (newlySelected.length > 0) {+ setSelectedEntries(+ pageFiles.filter((e) => newlySelected.includes(e.uuid)),+ );+ }+ };+return (// eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-noninteractive-element-interactions,jsx-a11y/no-static-element-interactions<div@@ -168,259 +205,265 @@ function GridPagination(props: Props) {background: `${dirColor}`,}}>- <div- ref={containerEl}- onContextMenu={(event: React.MouseEvent<HTMLDivElement>) =>- props.onContextMenu(event)- }- onClick={(event: React.MouseEvent<HTMLDivElement>) =>- props.onClick(event)- }- style={{- height: '100%',- overflowY: 'auto',- backgroundImage: backgroundImage.current,- backgroundSize: 'cover',- backgroundRepeat: 'no-repeat',- }}- >- <Grid container spacing={2}>- <Grid item xs={12} style={{ height: 70 }} />- {showDetails && (- <Grid item xs={12}>- <div- style={{- marginLeft: 10,- marginRight: 10,- marginTop: 0,- marginBottom: 0,- height:- !showDescription &&- directoryMeta &&- directoryMeta.description- ? 150- : 110,- position: 'relative',- }}- >- {((folderName && folderName.length > 0) ||- (directoryMeta &&- directoryMeta.tags &&- directoryMeta.tags.length > 0)) && (+ <SelectionDragLayer />+ <SelectionArea onSelect={handleSelect}>+ <div+ ref={containerEl}+ onContextMenu={(event: React.MouseEvent<HTMLDivElement>) =>+ props.onContextMenu(event)+ }+ onClick={(event: React.MouseEvent<HTMLDivElement>) =>+ props.onClick(event)+ }+ style={{+ height: '100%',+ overflowY: 'auto',+ backgroundImage: backgroundImage.current,+ backgroundSize: 'cover',+ backgroundRepeat: 'no-repeat',+ }}+ >+ <Grid container spacing={2}>+ <Grid item xs={12} style={{ height: 70 }} />+ {showDetails && (+ <Grid item xs={12}>+ <div+ style={{+ marginLeft: 10,+ marginRight: 10,+ marginTop: 0,+ marginBottom: 0,+ height:+ !showDescription &&+ directoryMeta &&+ directoryMeta.description+ ? 150+ : 110,+ position: 'relative',+ }}+ >+ {((folderName && folderName.length > 0) ||+ (directoryMeta &&+ directoryMeta.tags &&+ directoryMeta.tags.length > 0)) && (+ <Box+ style={{+ display: 'flex',+ alignItems: 'center',+ overflow: 'auto',+ padding: 10,+ marginRight: 160,+ width: 'fit-content',+ borderRadius: 8,+ color: theme.palette.text.primary,+ }}+ >+ <Tooltip title={t('core:renameDirectory')}>+ <ButtonBase+ data-tid={'currentDir_' + dataTidFormat(folderName)}+ style={{+ fontSize: '1.5rem',+ filter: `drop-shadow(0px 0px 4px ${theme.palette.background.default})`,+ }}+ onClick={() => {+ setSelectedEntries([]);+ openRenameEntryDialog();+ }}+ >+ {folderName}+ </ButtonBase>+ </Tooltip>+ {showTags ? (+ <span style={{ paddingLeft: 5 }}>+ {directoryMeta?.tags?.map((tag: TS.Tag) => {+ return <TagContainer tag={tag} tagMode="display" />;+ })}+ </span>+ ) : (+ <TagsPreview tags={directoryMeta?.tags} />+ )}+ </Box>+ )}<Box+ data-tid={'allFilesCount' + files.length}style={{- display: 'flex',- alignItems: 'center',- overflow: 'auto',- padding: 10,+ paddingBottom: 5,+ marginTop: 10,marginRight: 160,+ padding: 10,+ borderRadius: 10,width: 'fit-content',- borderRadius: 8,color: theme.palette.text.primary,}}>- <Tooltip title={t('core:renameDirectory')}>- <ButtonBase- data-tid={'currentDir_' + dataTidFormat(folderName)}- style={{- fontSize: '1.5rem',- filter: `drop-shadow(0px 0px 4px ${theme.palette.background.default})`,- }}- onClick={() => {- setSelectedEntries([]);- openRenameEntryDialog();- }}- >- {folderName}- </ButtonBase>- </Tooltip>- {showTags ? (- <span style={{ paddingLeft: 5 }}>- {directoryMeta?.tags?.map((tag: TS.Tag) => {- return <TagContainer tag={tag} tagMode="display" />;- })}- </span>- ) : (- <TagsPreview tags={directoryMeta?.tags} />- )}+ <Typography+ style={{+ fontSize: '0.9rem',+ filter: `drop-shadow(0px 0px 4px ${theme.palette.background.default})`,+ }}+ >+ {folderSummary}+ </Typography>+ {!showDescription &&+ directoryMeta &&+ directoryMeta.description && (+ <Typography+ style={{+ fontSize: '0.8rem',+ wordBreak: 'break-all',+ filter: `drop-shadow(0px 0px 2px ${theme.palette.background.default})`,+ height: 45,+ overflowY: 'auto',+ }}+ >+ {getDescriptionPreview(+ directoryMeta.description,+ 200,+ )}+ </Typography>+ )}</Box>- )}- <Box- data-tid={'allFilesCount' + files.length}- style={{- paddingBottom: 5,- marginTop: 10,- marginRight: 160,- padding: 10,- borderRadius: 10,- width: 'fit-content',- color: theme.palette.text.primary,- }}- >- <Typography+ <div+ data-tid="folderThumbTID"style={{- fontSize: '0.9rem',- filter: `drop-shadow(0px 0px 4px ${theme.palette.background.default})`,+ borderRadius: 10,+ height: 100,+ width: 140,+ backgroundImage: thumbImage.current,+ backgroundSize: 'cover', // cover contain+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'center center',+ position: 'absolute',+ top: 0,+ right: 0,}}- >- {folderSummary}- </Typography>- {!showDescription &&- directoryMeta &&- directoryMeta.description && (- <Typography- style={{- fontSize: '0.8rem',- wordBreak: 'break-all',- filter: `drop-shadow(0px 0px 2px ${theme.palette.background.default})`,- height: 45,- overflowY: 'auto',- }}- >- {getDescriptionPreview(directoryMeta.description, 200)}- </Typography>- )}- </Box>- <div- data-tid="folderThumbTID"- style={{- borderRadius: 10,- height: 100,- width: 140,- backgroundImage: thumbImage.current,- backgroundSize: 'cover', // cover contain- backgroundRepeat: 'no-repeat',- backgroundPosition: 'center center',- position: 'absolute',- top: 0,- right: 0,- }}+ />+ </div>+ </Grid>+ )}+ {showDescription && directoryMeta && directoryMeta.description && (+ <Grid+ item+ xs={12}+ style={{+ backgroundColor: theme.palette.background.default,+ marginTop: showDetails ? 0 : 10,+ marginLeft: 25,+ marginRight: 10,+ padding: 10,+ borderRadius: 10,+ }}+ >+ <MilkdownEditor+ content={directoryMeta.description}+ readOnly={true}+ /*dark={theme.palette.mode === 'dark'}*/+ currentFolder={currentDirectoryPath}+ lightMode={true}/>- </div>- </Grid>- )}- {showDescription && directoryMeta && directoryMeta.description && (- <Grid- item- xs={12}- style={{- backgroundColor: theme.palette.background.default,- marginTop: showDetails ? 0 : 10,- marginLeft: 25,- marginRight: 10,- padding: 10,- borderRadius: 10,- }}- >- <MilkdownEditor- content={directoryMeta.description}- readOnly={true}- /*dark={theme.palette.mode === 'dark'}*/- currentFolder={currentDirectoryPath}- lightMode={true}+ </Grid>+ )}+ </Grid>+ <GridCellsContainer>+ {pageFiles.map((entry, index, dArray) => (+ <CellView+ fsEntry={entry}+ index={index}+ cellContent={getCellContent}+ setFileContextMenuAnchorEl={setFileContextMenuAnchorEl}+ setDirContextMenuAnchorEl={setDirContextMenuAnchorEl}+ isLast={index === dArray.length - 1}/>- </Grid>- )}- </Grid>- <GridCellsContainer>- {pageFiles.map((entry, index, dArray) => (- <CellView- fsEntry={entry}- index={index}- cellContent={getCellContent}- setFileContextMenuAnchorEl={setFileContextMenuAnchorEl}- setDirContextMenuAnchorEl={setDirContextMenuAnchorEl}- isLast={index === dArray.length - 1}- />- ))}- {pageFiles.length < 1 && (- <div style={{ textAlign: 'center' }}>- {!showDescription &&- directoryMeta &&- directoryMeta.description && (- <div- style={{- position: 'relative',- margin: 'auto',- maxWidth: 150,- }}- >- <EntryIcon isFile={false} />- </div>+ ))}+ {pageFiles.length < 1 && (+ <div style={{ textAlign: 'center' }}>+ {!showDescription &&+ directoryMeta &&+ directoryMeta.description && (+ <div+ style={{+ position: 'relative',+ margin: 'auto',+ maxWidth: 150,+ }}+ >+ <EntryIcon isFile={false} />+ </div>+ )}+ <Typography+ style={{ padding: 15, color: theme.palette.text.secondary }}+ >+ {t('core:noFileFolderFound')}+ </Typography>+ {!AppConfig.isCordova && (+ <Typography style={{ color: theme.palette.text.secondary }}>+ {t('core:dragAndDropToImport')}+ </Typography>)}- <Typography- style={{ padding: 15, color: theme.palette.text.secondary }}- >- {t('core:noFileFolderFound')}- </Typography>- {!AppConfig.isCordova && (- <Typography style={{ color: theme.palette.text.secondary }}>- {t('core:dragAndDropToImport')}+ </div>+ )}+ {files.length < 1 && dirs.length >= 1 && !showDirectories && (+ <div style={{ textAlign: 'center' }}>+ {!showDescription &&+ directoryMeta &&+ directoryMeta.description && (+ <div+ style={{+ position: 'relative',+ margin: 'auto',+ maxWidth: 150,+ }}+ >+ <EntryIcon isFile={false} />+ </div>+ )}+ <Typography+ style={{ padding: 15, color: theme.palette.text.secondary }}+ >+ {t('core:noFileButFoldersFound')}</Typography>- )}- </div>- )}- {files.length < 1 && dirs.length >= 1 && !showDirectories && (- <div style={{ textAlign: 'center' }}>- {!showDescription &&- directoryMeta &&- directoryMeta.description && (- <div- style={{- position: 'relative',- margin: 'auto',- maxWidth: 150,- }}- >- <EntryIcon isFile={false} />- </div>+ {!AppConfig.isCordova && (+ <Typography style={{ color: theme.palette.text.secondary }}>+ {t('core:dragAndDropToImport')}+ </Typography>)}+ </div>+ )}+ </GridCellsContainer>+ {showPagination && (+ <Tooltip title={folderSummary}>+ <Pagination+ style={{+ left: 15,+ bottom: -40,+ zIndex: 1100,+ position: 'absolute',+ backgroundColor: theme.palette.background.default,+ opacity: 0.97,+ border: '1px solid lightgray',+ borderRadius: 5,+ padding: 3,+ }}+ count={paginationCount}+ page={page}+ onChange={handleChange}+ />+ </Tooltip>+ )}+ {!showDetails && !showPagination && pageFiles.length > 0 && (+ <div style={{ padding: 15, bottom: 10 }}><Typography- style={{ padding: 15, color: theme.palette.text.secondary }}+ style={{+ fontSize: '0.9rem',+ color: theme.palette.text.primary,+ }}>- {t('core:noFileButFoldersFound')}+ {folderSummary}</Typography>- {!AppConfig.isCordova && (- <Typography style={{ color: theme.palette.text.secondary }}>- {t('core:dragAndDropToImport')}- </Typography>- )}</div>)}- </GridCellsContainer>- {showPagination && (- <Tooltip title={folderSummary}>- <Pagination- style={{- left: 15,- bottom: -40,- zIndex: 1100,- position: 'absolute',- backgroundColor: theme.palette.background.default,- opacity: 0.97,- border: '1px solid lightgray',- borderRadius: 5,- padding: 3,- }}- count={paginationCount}- page={page}- onChange={handleChange}- />- </Tooltip>- )}- {!showDetails && !showPagination && pageFiles.length > 0 && (- <div style={{ padding: 15, bottom: 10 }}>- <Typography- style={{- fontSize: '0.9rem',- color: theme.palette.text.primary,- }}- >- {folderSummary}- </Typography>- </div>- )}- </div>+ </div>+ </SelectionArea></div>);}