diff --git a/frontend/src/app/useWorkspaceSelection.js b/frontend/src/app/useWorkspaceSelection.js new file mode 100644 index 0000000..db31f4b --- /dev/null +++ b/frontend/src/app/useWorkspaceSelection.js @@ -0,0 +1,109 @@ +import { useCallback, useMemo } from 'react'; +import { useDocumentSelection } from './useDocumentSelection'; + +const identity = (value) => value; + +export const useWorkspaceSelection = ({ + resolveDocumentRowKey, + resolveFolderRowKey, + isDocumentRowKey, + isFolderRowKey, + getRowId, + onInspectDocument = identity, + onInspectFolder = identity, +} = {}) => { + const selection = useDocumentSelection({ + resolveDocumentRowKey, + resolveFolderRowKey, + isDocumentRowKey, + isFolderRowKey, + getRowId, + }); + + const { + selectedEntries, + setSelectedEntries, + selectionOrder, + setSelectionOrder, + selectionOrderRef, + selectionAnchorRef, + selectionInitializedRef, + focusedDocumentId, + setFocusedDocumentId, + focusedRowKey, + setFocusedRowKey, + applySelection, + clearSelection, + handleEntrySelection, + promoteSelectionOrder, + configureSelectionEnvironment, + } = selection; + + const selectedDocumentIds = useMemo( + () => + selectedEntries + .filter((entry) => isDocumentRowKey(entry)) + .map((entry) => getRowId(entry)) + .filter(Boolean), + [selectedEntries, isDocumentRowKey, getRowId], + ); + + const selectedFolderIds = useMemo( + () => + selectedEntries + .filter((entry) => isFolderRowKey(entry)) + .map((entry) => getRowId(entry)) + .filter(Boolean), + [selectedEntries, isFolderRowKey, getRowId], + ); + + const selectEntry = useCallback( + (entry, event) => { + const rowKey = typeof entry === 'string' ? entry : entry?.rowKey; + if (!rowKey) return; + handleEntrySelection(rowKey, event); + }, + [handleEntrySelection], + ); + + const inspectDocument = useCallback( + (documentId) => { + if (!documentId) return; + onInspectDocument(documentId); + }, + [onInspectDocument], + ); + + const inspectFolder = useCallback( + (folderId) => { + if (!folderId) return; + onInspectFolder(folderId); + }, + [onInspectFolder], + ); + + return { + selectedEntries, + selectedDocumentIds, + selectedFolderIds, + selectionOrder, + selectionOrderRef, + selectionAnchorRef, + selectionInitializedRef, + focusedDocumentId, + setFocusedDocumentId, + focusedRowKey, + setFocusedRowKey, + applySelection, + clearSelection, + handleEntrySelection: selectEntry, + promoteSelectionOrder, + configureSelectionEnvironment, + setSelectedEntries, + setSelectionOrder, + inspectDocument, + inspectFolder, + }; +}; + +export default useWorkspaceSelection;