TagSpaces is an offline, open source, document manager with tagging support
separate DirTreeView component
Stanimirda78d14c97f9
diff --git a/app/components/DirectoryTreeView.tsx b/app/components/DirectoryTreeView.tsxnew file mode 100644index 000000000..25ce80492--- /dev/null+++ b/app/components/DirectoryTreeView.tsx@@ -0,0 +1,322 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)+ *+ * 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 React, { useState, forwardRef, useImperativeHandle } from 'react';+import Table from 'rc-table';+import FolderIcon from '@material-ui/icons/FolderOpen';+import { Location } from '-/reducers/locations';+import TargetMoveFileBox from './TargetMoveFileBox';+import DragItemTypes from '-/components/DragItemTypes';+import AppConfig from '-/config';+import PlatformIO from '-/services/platform-io';++interface Props {+ classes: any;+ loadDirectoryContent: (path: string) => void;+ location: Location;+ data?: any;+ isReadOnlyMode?: boolean;+ showUnixHiddenEntries: boolean;+ showNotification?: (+ text: string,+ notificationType: string,+ autohide: boolean+ ) => void;+ handleFileMoveDrop: (item, monitor) => void;+}++const DirectoryTreeView = forwardRef((props: Props, ref) => {+ const [data, setData] = useState(undefined);+ const [isExpanded, setExpanded] = useState(false);++ useImperativeHandle(ref, () => ({+ changeLocation(location: Location) {+ if (isExpanded && data[location.uuid] !== undefined) {+ /*const dirsTree = data;+ dirsTree[location.uuid] = undefined;+ setData(dirsTree);*/+ //setData(undefined);+ setExpanded(false);+ } else {+ loadSubDirectories(location, 1);+ }+ },+ closeLocation() {+ setData(undefined);+ }+ }));++ /*const changeLocation = (location: Location) => {+ const dirsTree = data;+ dirsTree[location.uuid] = undefined;+ setData(dirsTree);+ };*/++ const renderBodyCell = props => (+ <td {...props}>+ <TargetMoveFileBox+ // @ts-ignore+ accepts={[DragItemTypes.FILE]}+ onDrop={props.handleFileMoveDrop}+ >+ {props.children}+ </TargetMoveFileBox>+ </td>+ );++ const renderNameColumnAction = field => {+ const children = (+ <span style={{ fontSize: 15, marginLeft: 5 }} title={field}>+ <FolderIcon+ style={{ marginTop: 0, marginBottom: -8 }}+ className={props.classes.icon}+ />+ {field && field.length > 25 ? field.substr(0, 25) + '...' : field}+ </span>+ );+ return {+ children,+ props: {}+ };+ };++ const handleCellClick = (record, index) => ({+ /* onContextMenu: (e) => {+ this.handleFileContextMenu(e, record.path);+ }, */+ onClick: () => {+ onRowClick(record);+ }+ /* onDoubleClick: (e) => {+ this.onRowClick(record, index, e);+ } */+ });++ /*const onExpand = (expanded, record) => {+ // console.log('onExpand', expanded + JSON.stringify(record));+ if (expanded) {+ // this.onRowClick(record);+ loadSubDirectories(record, 1);+ }+ };*/++ const onRowClick = subDir => {+ loadSubDirectories(subDir, 1);+ props.loadDirectoryContent(subDir.path);+ };++ const columns = [+ {+ title: undefined,+ dataIndex: 'name',+ key: 'name',+ width: '80%',+ render: renderNameColumnAction,+ onCell: handleCellClick+ }+ ];++ const loadSubDirectories = (location: Location, deepLevel: number) => {+ const subFolder = {+ uuid: location.uuid,+ name: location.name,+ path: location.path || location.paths[0]+ };+ getDirectoriesTree(subFolder, deepLevel)+ .then(children => {+ if (children instanceof Array) {+ if (location.uuid) {+ const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this+ if (location.path === undefined) {+ // location+ dirsTree[location.uuid] = children;+ } else {+ const dirsCopy = getMergedDirsCopy(location.path, children);+ if (dirsCopy) {+ dirsTree[location.uuid] = dirsCopy;+ } else {+ // eslint-disable-next-line no-param-reassign+ location.children = children;+ dirsTree[location.uuid] = [location];+ }+ }+ setData(dirsTree);+ setExpanded(true);+ }+ } else if (location.path === undefined) {+ // if is Location+ //setData({});+ }+ return true;+ })+ .catch(error => {+ console.log('loadSubDirectories', error);+ });+ };++ type SubFolder = {+ uuid: string;+ name: string;+ path: string;+ children?: Array<SubFolder>;+ };++ const getDirectoriesTree = (subFolder: SubFolder, deepLevel: number) =>+ // const { settings } = getState();+ PlatformIO.listDirectoryPromise(subFolder.path, false)+ // @ts-ignore+ .then(dirEntries => {+ const directoryContent = [];+ dirEntries.map(entry => {+ if (+ entry.name === AppConfig.metaFolder ||+ entry.name.endsWith('/' + AppConfig.metaFolder) ||+ (!props.showUnixHiddenEntries && entry.name.startsWith('.'))+ ) {+ return true;+ }+ // const enhancedEntry = enhanceEntry(entry);+ if (!entry.isFile) {+ // eslint-disable-next-line no-param-reassign+ entry.uuid = subFolder.uuid;+ directoryContent.push(entry);+ }+ return true;+ });+ if (directoryContent.length > 0) {+ // eslint-disable-next-line no-param-reassign+ subFolder.children = directoryContent;+ if (deepLevel > 0) {+ const promisesArr = [];+ directoryContent.map(directory =>+ promisesArr.push(getDirectoriesTree(directory, deepLevel - 1))+ );+ return Promise.all(promisesArr);+ }+ }+ return subFolder;+ })+ .catch(error => {+ console.log('getDirectoriesTree', error);+ });++ /**+ * https://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure+ * Dynamically set property of nested object+ * */+ const getMergedDirsCopy = (path: string, arrChildren: Array<SubFolder>) => {+ const entries = Object.entries(data);+ for (const [uuid, arrSubDirs] of entries) {+ const arr: number = (arrSubDirs as Array<any>).length;+ let a;+ for (a = 0; a < arr; a += 1) {+ if (path === arrSubDirs[a].path) {+ const copyObj = [...data[uuid]];+ copyObj[a].children = arrChildren;+ return copyObj;+ }+ if (arrSubDirs[a].children !== undefined) {+ const stack = [+ {+ depth: 0,+ element: arrSubDirs[a],+ propPath: ''+ }+ ];+ let stackItem = 0;+ let current;+ let children;+ let depth;+ let stackPath;+ let propPath = a + '.children';++ while ((current = stack[stackItem++])) {+ // get the arguments+ stackPath = current.propPath;+ depth = current.depth;+ current = current.element;+ children = current.children;+ if (children !== undefined) {+ const len = children.length;+ for (let i = 0; i < len; i++) {+ if (path === children[i].path) {+ propPath =+ propPath ++ '.' ++ (stackPath ? stackPath + '.' : '') ++ i ++ '.children';+ const copyObj = [...data[uuid]];++ let schema = copyObj; // a moving reference to internal objects within obj+ const pList = propPath.split('.');+ const leng = pList.length;+ for (let c = 0; c < leng - 1; c++) {+ const elem = pList[c];+ if (!schema[elem]) schema[elem] = {};+ schema = schema[elem];+ }+ schema[pList[leng - 1]] = arrChildren;+ return copyObj;+ }++ stack.push({+ // pass args via object or array+ element: children[i],+ depth: depth + 1,+ propPath: (stackPath ? stackPath + '.' : '') + i + '.children'+ });+ }+ }+ }+ }+ }+ }+ };++ if (isExpanded && data != undefined) {+ return (+ // @ts-ignore+ <Table+ //key={props.location.uuid}+ // defaultExpandAllRows+ // className={classes.locationListArea}+ components={{+ // header: { cell: this.renderHeaderRow },+ body: { cell: renderBodyCell }+ }}+ showHeader={false}+ // className="table"+ rowKey="path"+ data={data[props.location.uuid]}+ columns={columns}+ className="table"+ // expandedRowRender={this.expandedRowRender}+ //onExpand={onExpand}+ // expandIcon={this.CustomExpandIcon}+ // expandIconAsCell+ /* onRow={(record, index) => ({+ onClick: this.onRowClick.bind(null, record, index),+ })} */+ />+ );+ }+ return null;+});++export default DirectoryTreeView;diff --git a/app/components/LocationManager.tsx b/app/components/LocationManager.tsxindex 0629f738f..53a063dd0 100644--- a/app/components/LocationManager.tsx+++ b/app/components/LocationManager.tsx@@ -67,16 +67,14 @@ import {isReadOnlyMode} from '../reducers/app';import { actions as LocationIndexActions } from '../reducers/location-index';-import {- getPerspectives,- getShowUnixHiddenEntries-} from '../reducers/settings';+import { getPerspectives, getShowUnixHiddenEntries } from '-/reducers/settings';import i18n from '../services/i18n';import AppConfig from '../config';import PlatformIO from '../services/platform-io';import TargetMoveFileBox from './TargetMoveFileBox';import DragItemTypes from './DragItemTypes';import IOActions from '../reducers/io-actions';+import DirectoryTreeView from '-/components/DirectoryTreeView';const isLocationsReadOnly = window.ExtLocationsReadOnly;@@ -133,7 +131,7 @@ interface State {isCreateDirectoryDialogOpened?: boolean;locationManagerMenuOpened: boolean;locationManagerMenuAnchorEl: Object | null;- dirs?: Object;+ isExpanded: boolean;}type SubFolder = {@@ -144,6 +142,11 @@ type SubFolder = {};class LocationManager extends React.Component<Props, State> {+ constructor(props) {+ super(props);+ this.directoryTreeRef = [];+ }+state = {open: false,locationDirectoryContextMenuAnchorEl: null,@@ -162,7 +165,7 @@ class LocationManager extends React.Component<Props, State> {locationManagerMenuAnchorEl: null,createLocationDialogKey: uuidv1(),editLocationDialogKey: uuidv1(),- dirs: {}+ isExpanded: false};componentDidMount() {@@ -186,162 +189,6 @@ class LocationManager extends React.Component<Props, State> {}}- loadSubDirectories = (location: Location, deepLevel: number) => {- const subFolder = {- uuid: location.uuid,- name: location.name,- path: location.path || location.paths[0]- };- this.getDirectoriesTree(subFolder, deepLevel)- .then(children => {- if (children instanceof Array) {- if (location.uuid) {- const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this- if (location.path === undefined) {- // location- dirsTree[location.uuid] = children;- } else {- const dirsCopy = this.getMergedDirsCopy(location.path, children);- if (dirsCopy) {- dirsTree[location.uuid] = dirsCopy;- } else {- // eslint-disable-next-line no-param-reassign- location.children = children;- dirsTree[location.uuid] = [location];- }- }- this.setState({- dirs: dirsTree- });- }- } else if (location.path === undefined) {- // if is Location- this.setState({- dirs: {}- });- }- return true;- })- .catch(error => {- console.log('loadSubDirectories', error);- });- };-- getDirectoriesTree = (subFolder: SubFolder, deepLevel: number) =>- // const { settings } = getState();- PlatformIO.listDirectoryPromise(subFolder.path, false)- // @ts-ignore- .then(dirEntries => {- const directoryContent = [];- dirEntries.map(entry => {- if (- entry.name === AppConfig.metaFolder ||- entry.name.endsWith('/' + AppConfig.metaFolder) ||- (!this.props.showUnixHiddenEntries && entry.name.startsWith('.'))- ) {- return true;- }- // const enhancedEntry = enhanceEntry(entry);- if (!entry.isFile) {- // eslint-disable-next-line no-param-reassign- entry.uuid = subFolder.uuid;- directoryContent.push(entry);- }- return true;- });- if (directoryContent.length > 0) {- // eslint-disable-next-line no-param-reassign- subFolder.children = directoryContent;- if (deepLevel > 0) {- const promisesArr = [];- directoryContent.map(directory =>- promisesArr.push(- this.getDirectoriesTree(directory, deepLevel - 1)- )- );- return Promise.all(promisesArr);- }- }- return subFolder;- })- .catch(error => {- console.log('getDirectoriesTree', error);- });-- /**- * https://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure- * Dynamically set property of nested object- * */- getMergedDirsCopy = (path: string, arrChildren: Array<SubFolder>) => {- const entries = Object.entries(this.state.dirs);- for (const [uuid, arrSubDirs] of entries) {- const arr: number = (arrSubDirs as Array<any>).length;- let a;- for (a = 0; a < arr; a += 1) {- if (path === arrSubDirs[a].path) {- const copyObj = [...this.state.dirs[uuid]];- copyObj[a].children = arrChildren;- return copyObj;- }- if (arrSubDirs[a].children !== undefined) {- const stack = [- {- depth: 0,- element: arrSubDirs[a],- propPath: ''- }- ];- let stackItem = 0;- let current;- let children;- let depth;- let stackPath;- let propPath = a + '.children';-- while ((current = stack[stackItem++])) {- // get the arguments- stackPath = current.propPath;- depth = current.depth;- current = current.element;- children = current.children;- if (children !== undefined) {- const len = children.length;- for (let i = 0; i < len; i++) {- if (path === children[i].path) {- propPath =- propPath +- '.' +- (stackPath ? stackPath + '.' : '') +- i +- '.children';- const copyObj = [...this.state.dirs[uuid]];-- let schema = copyObj; // a moving reference to internal objects within obj- const pList = propPath.split('.');- const leng = pList.length;- for (let c = 0; c < leng - 1; c++) {- const elem = pList[c];- if (!schema[elem]) schema[elem] = {};- schema = schema[elem];- }- schema[pList[leng - 1]] = arrChildren;- return copyObj;- }-- stack.push({- // pass args via object or array- element: children[i],- depth: depth + 1,- propPath: (stackPath ? stackPath + '.' : '') + i + '.children'- });- }- }- }- }- }- }- };-handleCloseDialogs = () => {this.setState({isCreateLocationDialogOpened: false,@@ -403,9 +250,11 @@ class LocationManager extends React.Component<Props, State> {this.handleRequestCloseContextMenus();if (this.state.selectedLocation && this.state.selectedLocation.uuid) {this.props.closeLocation(this.state.selectedLocation.uuid);- this.setState({+ this.directoryTreeRef[this.state.selectedLocation.uuid] = undefined;+ //this.directoryTreeRef[this.state.selectedLocation.uuid].closeLocation();+ /*this.setState({dirs: {}- });+ });*/}};@@ -487,20 +336,15 @@ class LocationManager extends React.Component<Props, State> {});};+ //todo https://stackoverflow.com/questions/37949981/call-child-method-from-parent+ //const directoryTreeRef = useRef();+handleLocationClick = (location: Location) => {+ this.directoryTreeRef[location.uuid].changeLocation(location);if (location.uuid === this.props.currentLocationId) {- if (this.state.dirs[location.uuid] !== undefined) {- const dirsTree = this.state.dirs;- dirsTree[location.uuid] = undefined;- this.setState({- dirs: dirsTree- });- } else {- this.loadSubDirectories(location, 1);- }this.props.loadDirectoryContent(location.paths[0]);} else {- this.loadSubDirectories(location, 1);+ //this.directoryTreeRef[location.uuid].loadSubDir(location, 1);this.props.openLocation(location);this.state.locationRootPath = location.paths[0];if (this.props.hideDrawer) {@@ -529,11 +373,11 @@ class LocationManager extends React.Component<Props, State> {});};- renderNameColumnAction = field => {+ /*renderNameColumnAction = field => {const children = (- <span style={{ fontSize: 15, marginLeft: 5 }} title={field}>+ <span style={{fontSize: 15, marginLeft: 5}} title={field}><FolderIcon- style={{ marginTop: 0, marginBottom: -8 }}+ style={{marginTop: 0, marginBottom: -8}}className={this.props.classes.icon}/>{field && field.length > 25 ? field.substr(0, 25) + '...' : field}@@ -543,21 +387,21 @@ class LocationManager extends React.Component<Props, State> {children,props: {}};- };+ };*/- handleCellClick = (record, index) => ({- /* onContextMenu: (e) => {+ /*handleCellClick = (record, index) => ({+ /!* onContextMenu: (e) => {this.handleFileContextMenu(e, record.path);- }, */+ }, *!/onClick: () => {this.onRowClick(record);}- /* onDoubleClick: (e) => {+ /!* onDoubleClick: (e) => {this.onRowClick(record, index, e);- } */- });+ } *!/+ });*/- onExpand = (expanded, record) => {+ /*onExpand = (expanded, record) => {// console.log('onExpand', expanded + JSON.stringify(record));if (expanded) {// this.onRowClick(record);@@ -568,7 +412,7 @@ class LocationManager extends React.Component<Props, State> {onRowClick = subDir => {this.loadSubDirectories(subDir, 1);this.props.loadDirectoryContent(subDir.path);- };+ };*//*** https://github.com/react-component/table/blob/master/examples/react-dnd.js@@ -614,8 +458,8 @@ class LocationManager extends React.Component<Props, State> {}};- renderBodyCell = props => (- <td {...props} style={{ position: 'relative' }}>+ /*renderBodyCell = props => (+ <td {...props}><TargetMoveFileBox// @ts-ignoreaccepts={[DragItemTypes.FILE]}@@ -624,46 +468,15 @@ class LocationManager extends React.Component<Props, State> {{props.children}</TargetMoveFileBox></td>- );+ );*/// <Tooltip id="tooltip-icon" title={i18n.t('core:moreOperations')} placement="bottom"></Tooltip>renderLocation = (location: Location) => {- let table;+ /* if (this.directoryTreeRef[location.uuid] === undefined) {+ this.directoryTreeRef[location.uuid] = React.createRef();+ }*/const isCloudLocation = location.type === locationType.TYPE_CLOUD;- if (this.state.dirs[location.uuid] !== undefined) {- const columns = [- {- title: undefined,- dataIndex: 'name',- key: 'name',- width: '80%',- render: this.renderNameColumnAction,- onCell: this.handleCellClick- }- ];- table = (- <Table- // defaultExpandAllRows- // className={classes.locationListArea}- components={{- // header: { cell: this.renderHeaderRow },- body: { cell: this.renderBodyCell }- }}- showHeader={false}- // className="table"- rowKey="path"- data={this.state.dirs[location.uuid]}- columns={columns}- // expandedRowRender={this.expandedRowRender}- onExpand={this.onExpand}- // expandIcon={this.CustomExpandIcon}- // expandIconAsCell- /* onRow={(record, index) => ({- onClick: this.onRowClick.bind(null, record, index),- })} */- />- );- }+return (<div key={location.uuid}><ListItem@@ -753,7 +566,15 @@ class LocationManager extends React.Component<Props, State> {</ListItemSecondaryAction>)}</ListItem>- {table}+ <DirectoryTreeView+ ref={dirTree => (this.directoryTreeRef[location.uuid] = dirTree)}+ classes={this.props.classes}+ loadDirectoryContent={this.props.loadDirectoryContent}+ location={location}+ showUnixHiddenEntries={this.props.showUnixHiddenEntries}+ moveFiles={this.props.moveFiles}+ handleFileMoveDrop={this.handleFileMoveDrop}+ /></div>);};