From 8c01716b0d1539a62accdbc38d79a84c9c19c4ac Mon Sep 17 00:00:00 2001 From: Joshua May Date: Sun, 11 Feb 2024 01:16:17 +0100 Subject: eslint --fix --- src/web/craco.config.js | 6 +- src/web/package.json | 54 +- src/web/src/components/App.jsx | 679 +++++++++++++-------- src/web/src/components/AppContext.js | 2 +- src/web/src/components/Browse/Browse.jsx | 364 ++++++----- src/web/src/components/Browse/Directory.jsx | 147 +++-- src/web/src/components/Browse/DirectoryTree.jsx | 38 +- src/web/src/components/Chat/Chat.jsx | 259 +++++--- src/web/src/components/Chat/ChatMenu.jsx | 52 +- src/web/src/components/Chat/SendMessageModal.jsx | 29 +- src/web/src/components/LoginForm.jsx | 147 +++-- src/web/src/components/Rooms/RoomJoinModal.jsx | 115 ++-- src/web/src/components/Rooms/RoomMenu.jsx | 41 +- src/web/src/components/Rooms/RoomUserList.jsx | 51 +- src/web/src/components/Rooms/Rooms.jsx | 301 +++++---- .../src/components/Search/Detail/SearchDetail.jsx | 234 ++++--- .../Search/Detail/SearchDetailHeader.jsx | 95 +-- .../components/Search/List/SearchActionIcon.jsx | 41 +- src/web/src/components/Search/List/SearchList.jsx | 83 ++- .../src/components/Search/List/SearchListRow.jsx | 46 +- src/web/src/components/Search/Response.jsx | 234 ++++--- src/web/src/components/Search/SearchStatusIcon.jsx | 77 ++- src/web/src/components/Search/Searches.jsx | 181 +++--- src/web/src/components/Shared/CodeEditor.jsx | 24 +- src/web/src/components/Shared/Div.jsx | 6 +- src/web/src/components/Shared/ErrorSegment.jsx | 21 +- src/web/src/components/Shared/FileList.jsx | 168 ++--- src/web/src/components/Shared/LoaderSegment.jsx | 21 +- src/web/src/components/Shared/Logo.jsx | 10 +- src/web/src/components/Shared/Nbsp.jsx | 2 +- .../src/components/Shared/PlaceholderSegment.jsx | 22 +- src/web/src/components/Shared/ShrinkableButton.jsx | 20 +- .../components/Shared/ShrinkableDropdownButton.jsx | 45 +- src/web/src/components/Shared/Switch.jsx | 6 +- src/web/src/components/Shared/index.js | 2 +- src/web/src/components/System/Data/index.jsx | 35 +- src/web/src/components/System/Files/Explorer.jsx | 256 +++++--- src/web/src/components/System/Files/index.jsx | 37 +- src/web/src/components/System/Info/index.jsx | 107 ++-- src/web/src/components/System/Logs/index.jsx | 66 +- .../src/components/System/Options/DebugModal.jsx | 46 +- .../src/components/System/Options/EditModal.jsx | 118 ++-- src/web/src/components/System/Options/index.jsx | 92 +-- .../src/components/System/Shares/ContentsModal.jsx | 65 +- .../components/System/Shares/ExclusionTable.jsx | 45 +- .../src/components/System/Shares/ShareTable.jsx | 66 +- src/web/src/components/System/Shares/index.jsx | 151 ++--- src/web/src/components/System/System.jsx | 174 ++++-- src/web/src/components/Transfers/TransferGroup.jsx | 191 +++--- src/web/src/components/Transfers/TransferList.jsx | 215 ++++--- src/web/src/components/Transfers/Transfers.jsx | 98 +-- .../src/components/Transfers/TransfersHeader.jsx | 185 +++--- src/web/src/components/Users/User.jsx | 89 +-- src/web/src/components/Users/Users.jsx | 119 ++-- src/web/src/config.js | 17 +- src/web/src/index.jsx | 8 +- src/web/src/lib/api.js | 43 +- src/web/src/lib/application.js | 5 +- src/web/src/lib/chat.js | 7 +- src/web/src/lib/files.js | 13 +- src/web/src/lib/hubFactory.js | 26 +- src/web/src/lib/options.js | 2 +- src/web/src/lib/relay.js | 2 +- src/web/src/lib/rooms.js | 15 +- src/web/src/lib/searches.js | 182 ++++-- src/web/src/lib/searches.test.js | 140 ++--- src/web/src/lib/server.js | 6 +- src/web/src/lib/session.js | 19 +- src/web/src/lib/shares.js | 2 +- src/web/src/lib/transfers.js | 25 +- src/web/src/lib/users.js | 8 +- src/web/src/lib/util.js | 94 +-- src/web/src/lib/util.test.js | 6 +- 73 files changed, 3865 insertions(+), 2533 deletions(-) (limited to 'src') diff --git a/src/web/craco.config.js b/src/web/craco.config.js index 54024b07..26ffce2b 100644 --- a/src/web/craco.config.js +++ b/src/web/craco.config.js @@ -1,3 +1,5 @@ +const CracoLessPlugin = require('@semantic-ui-react/craco-less'); + module.exports = { - plugins: [{ plugin: require('@semantic-ui-react/craco-less') }], -} \ No newline at end of file + plugins: [{ plugin: CracoLessPlugin }], +}; diff --git a/src/web/package.json b/src/web/package.json index 7a438a28..49990771 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -1,17 +1,17 @@ { - "name": "web", - "version": "0.1.0", - "private": true, - "homepage": ".", - "scripts": { - "start": "craco start", - "build": "craco build", - "test": "craco test", - "test-unattended": "craco test --watchAll false --passWithNoTests", - "eject": "craco eject", - "postinstall": "semantic-ui-css-patch", - "lint": "eslint .", - "lint:fix": "eslint --fix ." + "browserslist": { + "development": [ + ">0.3%", + "not ie 11", + "not dead", + "not op_mini all" + ], + "production": [ + ">0.3%", + "not ie 11", + "not dead", + "not op_mini all" + ] }, "dependencies": { "@codemirror/language": "^6.0.0", @@ -40,23 +40,23 @@ "eslint-config-canonical": "^42.8.1", "react-scripts": "^5.0.0" }, + "homepage": ".", + "name": "web", "overrides": { "@craco/craco": "^7.0.0", "css-select": "^3.1.0", "css-what": "^5.0.1" }, - "browserslist": { - "production": [ - ">0.3%", - "not ie 11", - "not dead", - "not op_mini all" - ], - "development": [ - ">0.3%", - "not ie 11", - "not dead", - "not op_mini all" - ] - } + "private": true, + "scripts": { + "build": "craco build", + "eject": "craco eject", + "lint": "eslint .", + "lint:fix": "eslint --fix .", + "postinstall": "semantic-ui-css-patch", + "start": "craco start", + "test": "craco test", + "test-unattended": "craco test --watchAll false --passWithNoTests" + }, + "version": "0.1.0" } diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 6231fdac..cb906871 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -1,96 +1,104 @@ -import React, { Component } from 'react'; -import { Route, Link, Switch, Redirect } from 'react-router-dom'; - -import { ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; - -import * as session from '../lib/session'; -import * as relayAPI from '../lib/relay'; -import { connect, disconnect } from '../lib/server'; +import './App.css'; import { urlBase } from '../config'; - import { createApplicationHubConnection } from '../lib/hubFactory'; - -import './App.css'; -import Searches from './Search/Searches'; +import * as relayAPI from '../lib/relay'; +import { connect, disconnect } from '../lib/server'; +import * as session from '../lib/session'; +import AppContext from './AppContext'; import Browse from './Browse/Browse'; -import Users from './Users/Users'; -import Transfers from './Transfers/Transfers'; import Chat from './Chat/Chat'; -import System from './System/System'; import LoginForm from './LoginForm'; - -import AppContext from './AppContext'; - -import { - Sidebar, - Segment, - Menu, - Icon, - Modal, - Header, +import Rooms from './Rooms/Rooms'; +import Searches from './Search/Searches'; +import ErrorSegment from './Shared/ErrorSegment'; +import System from './System/System'; +import Transfers from './Transfers/Transfers'; +import Users from './Users/Users'; +import React, { Component } from 'react'; +import { Link, Redirect, Route, Switch } from 'react-router-dom'; +import { ToastContainer } from 'react-toastify'; +import { Button, + Header, + Icon, Loader, + Menu, + Modal, + Segment, + Sidebar, } from 'semantic-ui-react'; -import Rooms from './Rooms/Rooms'; -import ErrorSegment from './Shared/ErrorSegment'; const initialState = { + applicationOptions: {}, + applicationState: {}, + error: false, + initialized: false, login: { - pending: false, error: undefined, + pending: false, }, - applicationState: {}, - applicationOptions: {}, - initialized: false, - error: false, retriesExhausted: false, }; class App extends Component { state = initialState; - componentDidMount = () => { - window.matchMedia('(prefers-color-scheme: dark)') - .addEventListener('change', (e) => e.matches && this.setState({theme: 'dark'})); - window.matchMedia('(prefers-color-scheme: light)') - .addEventListener('change', (e) => e.matches && this.setState({theme:'light'})); + componentDidMount() { + window + .matchMedia('(prefers-color-scheme: dark)') + .addEventListener( + 'change', + (e) => e.matches && this.setState({ theme: 'dark' }), + ); + window + .matchMedia('(prefers-color-scheme: light)') + .addEventListener( + 'change', + (e) => e.matches && this.setState({ theme: 'light' }), + ); this.init(); - }; + } init = async () => { this.setState({ initialized: false }, async () => { try { const securityEnabled = await session.getSecurityEnabled(); - + if (!securityEnabled) { console.debug('application security is not enabled, per api call'); session.enablePassthrough(); } - + if (await session.check()) { const appHub = createApplicationHubConnection(); appHub.on('state', (state) => { this.setState({ applicationState: state }); }); - + appHub.on('options', (options) => { this.setState({ applicationOptions: options }); }); - appHub.onreconnecting(() => this.setState({ error: true, retriesExhausted: false })); - appHub.onclose(() => this.setState({ error: true, retriesExhausted: true })); - appHub.onreconnected(() => this.setState({ error: false, retriesExhausted: false })); + appHub.onreconnecting(() => + this.setState({ error: true, retriesExhausted: false }), + ); + appHub.onclose(() => + this.setState({ error: true, retriesExhausted: true }), + ); + appHub.onreconnected(() => + this.setState({ error: false, retriesExhausted: false }), + ); await appHub.start(); } - + this.setState({ error: false, }); - } catch (err) { - console.error(err); + } catch (error) { + console.error(error); this.setState({ error: true, retriesExhausted: true }); } finally { this.setState({ initialized: true }); @@ -99,19 +107,27 @@ class App extends Component { }; login = (username, password, rememberMe) => { - this.setState({ login: { ...this.state.login, pending: true, error: undefined }}, async () => { - try { - await session.login({ username, password, rememberMe }); - this.setState({ login: { ...this.state.login, pending: false, error: false }}, () => this.init()); - } catch (error) { - this.setState({ login: { ...this.state.login, pending: false, error }}); - } - }); + this.setState( + { login: { ...this.state.login, error: undefined, pending: true } }, + async () => { + try { + await session.login({ password, rememberMe, username }); + this.setState( + { login: { ...this.state.login, error: false, pending: false } }, + () => this.init(), + ); + } catch (error) { + this.setState({ + login: { ...this.state.login, error, pending: false }, + }); + } + }, + ); }; - + logout = () => { session.logout(); - this.setState({ login: { ...initialState.login }}); + this.setState({ login: { ...initialState.login } }); }; withTokenCheck = (component) => { @@ -119,98 +135,147 @@ class App extends Component { return { ...component }; }; - render = () => { - const { - login, - applicationState = {}, - applicationOptions = {}, - error, - initialized, - retriesExhausted, - theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light', + render() { + const { + applicationOptions = {}, + applicationState = {}, + error, + initialized, + login, + retriesExhausted, + theme = window.matchMedia('(prefers-color-scheme: dark)').matches + ? 'dark' + : 'light', } = this.state; - const { - version = {}, - relay = {}, - server, + const { pendingReconnect, pendingRestart, + relay = {}, + server, shares = {}, user, + version = {}, } = applicationState; - const { isUpdateAvailable, current, latest } = version; + const { current, isUpdateAvailable, latest } = version; const { scanPending: pendingShareRescan } = shares; - const { mode, controller } = relay; + const { controller, mode } = relay; if (!initialized) { - return ; + return ( + + ); } if (error) { - return - - Lost connection to slskd
{(retriesExhausted ? 'Refresh to reconnect' : 'Retrying...')} - - - }/>; + return ( + + Lost connection to slskd +
+ + {retriesExhausted ? 'Refresh to reconnect' : 'Retrying...'} + + + } + icon="attention" + suppressPrefix + /> + ); } if (!session.isLoggedIn() && !session.isPassthroughEnabled()) { return ( - ); } - - const ModeSpecificConnectButton = ({ mode, server, controller = {} }) => { + + const ModeSpecificConnectButton = ({ controller = {}, mode, server }) => { if (mode === 'Agent') { const isConnected = controller?.state === 'Connected'; - const isTransitioning = ['Connecting', 'Reconnecting'].includes(controller?.state); + const isTransitioning = ['Connecting', 'Reconnecting'].includes( + controller?.state, + ); - return <> + return ( isConnected ? relayAPI.disconnect() : relayAPI.connect()} + onClick={() => + isConnected ? relayAPI.disconnect() : relayAPI.connect() + } > - - + - {!isConnected && } - Controller {controller?.state} + {!isConnected && ( + + )} + + Controller {controller?.state} - ; + ); } else { - return <> - {server?.isConnected && disconnect()} - > - - - {user?.privileges?.isPrivileged && - } - Connected - } - {(!server?.isConnected) && connect()} - > - - - - Disconnected - } - ; + return ( + <> + {server?.isConnected && ( + disconnect()}> + + + {user?.privileges?.isPrivileged && ( + + )} + + Connected + + )} + {!server?.isConnected && ( + connect()}> + + + + + Disconnected + + )} + + ); } }; @@ -224,178 +289,314 @@ class App extends Component { return ( <> - + - {version.isCanary && - Canary - } - {isAgent ? - Agent Mode - : + {version.isCanary && ( + + + Canary + + )} + {isAgent ? ( + + + Agent Mode + + ) : ( <> - Search + + Search - Downloads + + Downloads - Uploads + + Uploads - Rooms + + Rooms - Chat + + Chat - Users + + Users - Browse + + Browse - } - - this.setState({'theme': theme === 'dark' ? 'light' : 'dark'})}> - Theme - - - {(pendingReconnect || pendingRestart || pendingShareRescan) && - - - - - Pending Action - } - {isUpdateAvailable && - - - New Version! - } - centered - closeIcon - size='mini' + + )} + + + this.setState({ theme: theme === 'dark' ? 'light' : 'dark' }) + } > - New Version! - -

- You are currently running version {current} - while version {latest} is available. -

-
- - - - } + + Theme +
+ + {(pendingReconnect || pendingRestart || pendingShareRescan) && ( + + + + + + + Pending Action + + )} + {isUpdateAvailable && ( + + + + + New Version! + + } + > + New Version! + +

+ You are currently running version{' '} + {current} + while version {latest} is available. +

+
+ + + +
+ )} - System + + System - {session.isLoggedIn() && - Log Out - - } - centered - size='mini' - header={
} - content='Are you sure you want to log out?' - actions={['Cancel', { key: 'done', content: 'Log Out', negative: true, onClick: this.logout }]} - />} + {session.isLoggedIn() && ( + + } + size="mini" + trigger={ + + + Log Out + + } + /> + )}
- - - {isAgent ? - this.withTokenCheck( - - ) - }/> - - : + + + {isAgent ? ( - - this.withTokenCheck(
- -
)} + + this.withTokenCheck( + , + ) + } + /> + +
+ ) : ( + + + this.withTokenCheck( +
+ +
, + ) + } + /> + + this.withTokenCheck() + } + /> + + this.withTokenCheck() + } + /> + + this.withTokenCheck( + , + ) + } /> - this.withTokenCheck()}/> - - this.withTokenCheck()} + + this.withTokenCheck() + } /> - - this.withTokenCheck()} + + this.withTokenCheck( +
+ +
, + ) + } + /> + + this.withTokenCheck( +
+ +
, + ) + } + /> + + this.withTokenCheck( + , + ) + } + /> + - this.withTokenCheck()}/> - - this.withTokenCheck(
) - }/> - - this.withTokenCheck(
- -
) - }/> - this.withTokenCheck( - - ) - }/> -
- } + )}
); - }; + } } -export default App; \ No newline at end of file +export default App; diff --git a/src/web/src/components/AppContext.js b/src/web/src/components/AppContext.js index 2095b2ab..e4dab109 100644 --- a/src/web/src/components/AppContext.js +++ b/src/web/src/components/AppContext.js @@ -2,4 +2,4 @@ import React from 'react'; const AppContext = React.createContext(); -export default AppContext; \ No newline at end of file +export default AppContext; diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx index e090851b..412dd7e2 100644 --- a/src/web/src/components/Browse/Browse.jsx +++ b/src/web/src/components/Browse/Browse.jsx @@ -1,86 +1,92 @@ -import React, { Component } from 'react'; -import * as lzString from 'lz-string'; -import * as users from '../../lib/users'; - import './Browse.css'; - -import DirectoryTree from './DirectoryTree'; - -import { - Segment, - Input, - Loader, - Card, - Icon, -} from 'semantic-ui-react'; - -import Directory from './Directory'; +import * as users from '../../lib/users'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; +import Directory from './Directory'; +import DirectoryTree from './DirectoryTree'; +import * as lzString from 'lz-string'; +import React, { Component } from 'react'; +import { Card, Icon, Input, Loader, Segment } from 'semantic-ui-react'; -const initialState = { - username: '', - browseState: 'idle', - browseStatus: 0, +const initialState = { browseError: undefined, - interval: undefined, - selectedDirectory: {}, - selectedFiles: [], - tree: [], - separator: '\\', + browseState: 'idle', + browseStatus: 0, info: { directories: 0, files: 0, lockedDirectories: 0, lockedFiles: 0, }, + interval: undefined, + selectedDirectory: {}, + selectedFiles: [], + separator: '\\', + tree: [], + username: '', }; class Browse extends Component { state = initialState; browse = () => { - let username = this.inputtext.inputRef.current.value; - - this.setState({ username , browseState: 'pending', browseError: undefined }, () => { - users.browse({ username }) - .then(response => { - let { directories, lockedDirectories } = response; - - // we need to know the directory separator. assume it is \ to start - let separator = undefined; - - const directoryCount = directories.length; - const fileCount = directories.reduce((acc, dir) => { - // examine each directory as we process it to see if it contains \ or /, and set separator accordingly - if (!separator) { - if (dir.name.includes('\\')) separator = '\\'; - else if (dir.name.includes('/')) separator = '/'; - } + const username = this.inputtext.inputRef.current.value; - return acc += dir.fileCount; - }, 0); - - const lockedDirectoryCount = lockedDirectories.length; - const lockedFileCount = lockedDirectories.reduce((acc, dir) => acc += dir.fileCount, 0); - - directories = directories.concat(lockedDirectories.map(d => ({ ...d, locked: true }))); - - this.setState({ - tree: this.getDirectoryTree({ directories, separator }), - separator, - info: { - directories: directoryCount, - files: fileCount, - lockedDirectories: lockedDirectoryCount, - lockedFiles: lockedFileCount, - }, - }); - }) - .then(() => this.setState({ browseState: 'complete', browseError: undefined }, () => { - this.saveState(); - })) - .catch(err => this.setState({ browseState: 'error', browseError: err })); - }); + this.setState( + { browseError: undefined, browseState: 'pending', username }, + () => { + users + .browse({ username }) + .then((response) => { + let { directories, lockedDirectories } = response; + + // we need to know the directory separator. assume it is \ to start + let separator; + + const directoryCount = directories.length; + const fileCount = directories.reduce((accumulator, dir) => { + // examine each directory as we process it to see if it contains \ or /, and set separator accordingly + if (!separator) { + if (dir.name.includes('\\')) separator = '\\'; + else if (dir.name.includes('/')) separator = '/'; + } + + return (accumulator += dir.fileCount); + }, 0); + + const lockedDirectoryCount = lockedDirectories.length; + const lockedFileCount = lockedDirectories.reduce( + (accumulator, dir) => (accumulator += dir.fileCount), + 0, + ); + + directories = directories.concat( + lockedDirectories.map((d) => ({ ...d, locked: true })), + ); + + this.setState({ + info: { + directories: directoryCount, + files: fileCount, + lockedDirectories: lockedDirectoryCount, + lockedFiles: lockedFileCount, + }, + separator, + tree: this.getDirectoryTree({ directories, separator }), + }); + }) + .then(() => + this.setState( + { browseError: undefined, browseState: 'complete' }, + () => { + this.saveState(); + }, + ), + ) + .catch((error) => + this.setState({ browseError: error, browseState: 'error' }), + ); + }, + ); }; clear = () => { @@ -90,7 +96,7 @@ class Browse extends Component { }); }; - keyUp = (event) => event.key === 'Escape' ? this.clear() : ''; + keyUp = (event) => (event.key === 'Escape' ? this.clear() : ''); onUsernameChange = (event, data) => { this.setState({ username: data.value }); @@ -98,15 +104,20 @@ class Browse extends Component { saveState = () => { this.inputtext.inputRef.current.value = this.state.username; - this.inputtext.inputRef.current.disabled = this.state.browseState !== 'idle'; + this.inputtext.inputRef.current.disabled = + this.state.browseState !== 'idle'; const storeToLocalStorage = () => { try { - localStorage.setItem('soulseek-example-browse-state', lzString.compress(JSON.stringify(this.state))); + localStorage.setItem( + 'soulseek-example-browse-state', + lzString.compress(JSON.stringify(this.state)), + ); } catch (error) { console.error(error); } }; + // Shifting the compression and safe out of the current render loop to speed up responsiveness // requestIdleCallback is not supported in Safari hence we push to next tick using Promise.resolve if (window.requestIdleCallback) { @@ -118,36 +129,45 @@ class Browse extends Component { loadState = () => { this.setState( - JSON.parse(lzString.decompress(localStorage.getItem('soulseek-example-browse-state') || '')) || initialState); + JSON.parse( + lzString.decompress( + localStorage.getItem('soulseek-example-browse-state') || '', + ), + ) || initialState, + ); }; - componentDidMount = () => { + componentDidMount() { this.fetchStatus(); this.loadState(); - this.setState({ - interval: window.setInterval(this.fetchStatus, 500), - }, () => this.saveState()); - + this.setState( + { + interval: window.setInterval(this.fetchStatus, 500), + }, + () => this.saveState(), + ); + document.addEventListener('keyup', this.keyUp, false); - }; - - componentWillUnmount = () => { + } + + componentWillUnmount() { clearInterval(this.state.interval); this.setState({ interval: undefined }); document.removeEventListener('keyup', this.keyUp, false); - }; + } fetchStatus = () => { const { browseState, username } = this.state; if (browseState === 'pending') { - users.getBrowseStatus({ username }) - .then(response => this.setState({ + users.getBrowseStatus({ username }).then((response) => + this.setState({ browseStatus: response.data, - })); + }), + ); } }; - getDirectoryTree = ({directories, separator}) => { + getDirectoryTree = ({ directories, separator }) => { if (directories.length === 0 || directories[0].name === undefined) { return []; } @@ -157,114 +177,176 @@ class Browse extends Component { // - do the split once // - future look ups are done from the Map const depthMap = new Map(); - directories.forEach(d => { + for (const d of directories) { const depth = d.name.split(separator).length; if (!depthMap.has(depth)) { depthMap.set(depth, []); } + depthMap.get(depth).push(d); - }); + } const depth = Math.min.apply(Math, Array.from(depthMap.keys())); - return depthMap.get(depth).map(directory => this.getChildDirectories(depthMap, directory, separator, depth + 1)); + return depthMap + .get(depth) + .map((directory) => + this.getChildDirectories(depthMap, directory, separator, depth + 1), + ); }; getChildDirectories = (depthMap, root, separator, depth) => { if (!depthMap.has(depth)) { - return { ...root, children: []}; + return { ...root, children: [] }; } - const children = depthMap.get(depth).filter(d => d.name.startsWith(root.name)); - return { ...root, children: children.map(c => this.getChildDirectories(depthMap, c, separator, depth + 1)) }; + const children = depthMap + .get(depth) + .filter((d) => d.name.startsWith(root.name)); + + return { + ...root, + children: children.map((c) => + this.getChildDirectories(depthMap, c, separator, depth + 1), + ), + }; }; selectDirectory = (directory) => { - this.setState({ selectedDirectory: { ...directory, children: [] }}, () => this.saveState()); + this.setState({ selectedDirectory: { ...directory, children: [] } }, () => + this.saveState(), + ); }; deselectDirectory = () => { - this.setState({ selectedDirectory: initialState.selectedDirectory }, () => this.saveState()); + this.setState({ selectedDirectory: initialState.selectedDirectory }, () => + this.saveState(), + ); }; - render = () => { - const { browseState, browseStatus, browseError, tree, separator, selectedDirectory, username, info } = this.state; - const { name, locked } = selectedDirectory; + render() { + const { + browseError, + browseState, + browseStatus, + info, + selectedDirectory, + separator, + tree, + username, + } = this.state; + const { locked, name } = selectedDirectory; const pending = browseState === 'pending'; const emptyTree = !(tree && tree.length > 0); - const files = (selectedDirectory.files || []) - .map(f => ({ ...f, filename: `${name}${separator}${f.filename}` })); + const files = (selectedDirectory.files || []).map((f) => ({ + ...f, + filename: `${name}${separator}${f.filename}`, + })); return ( -
- -
+
+ +
+ +
} - size='big' - ref={input => this.inputtext = input} - loading={pending} + action={ + !pending && + (browseState === 'idle' + ? { icon: 'search', onClick: this.browse } + : { color: 'red', icon: 'x', onClick: this.clear }) + } + className="search-input" disabled={pending} - className='search-input' + input={ + + } + loading={pending} + onKeyUp={(e) => (e.key === 'Enter' ? this.browse() : '')} placeholder="Username" - action={!pending && (browseState === 'idle' - ? { icon: 'search', onClick: this.browse } - : { icon: 'x', color: 'red', onClick: this.clear })} - onKeyUp={(e) => e.key === 'Enter' ? this.browse() : ''} + ref={(input) => (this.inputtext = input)} + size="big" />
- {pending ? - - Downloaded {Math.round(browseStatus.percentComplete || 0)}% of Response + Downloaded {Math.round(browseStatus.percentComplete || 0)}% of + Response - : + ) : (
- {browseError ? - Failed to browse {username} : -
- {emptyTree ? - : - + {browseError ? ( + Failed to browse {username} + ) : ( +
+ {emptyTree ? ( + + ) : ( + - + {username} - + - {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`} {/* eslint-disable-line max-len */} + {`${info.files + info.lockedFiles} files in ${info.directories + info.lockedDirectories} directories (including ${info.lockedFiles} files in ${info.lockedDirectories} locked directories)`}{' '} + {/* eslint-disable-line max-len */} - - + this.selectDirectory(value)} + selectedDirectoryName={name} + tree={tree} /> - } - {name && } + + )} + {name && ( + + )}
- } -
} + )} +
+ )}
); - }; + } } export default Browse; diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx index ed179e87..891db608 100644 --- a/src/web/src/components/Browse/Directory.jsx +++ b/src/web/src/components/Browse/Directory.jsx @@ -1,101 +1,132 @@ -import React, { Component } from 'react'; import * as transfers from '../../lib/transfers'; - import { formatBytes } from '../../lib/util'; - import FileList from '../Shared/FileList'; - -import { - Button, - Card, - Icon, - Label, -} from 'semantic-ui-react'; +import React, { Component } from 'react'; +import { Button, Card, Icon, Label } from 'semantic-ui-react'; const initialState = { - downloadRequest: undefined, downloadError: '', + downloadRequest: undefined, }; class Directory extends Component { - state = { + state = { ...initialState, - files: this.props.files.map(f => ({ selected: false, ...f })), + files: this.props.files.map((f) => ({ selected: false, ...f })), }; onFileSelectionChange = (file, state) => { file.selected = state; - this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }); + this.setState({ + downloadError: '', + downloadRequest: undefined, + tree: this.state.tree, + }); }; download = (username, files) => { this.setState({ downloadRequest: 'inProgress' }, async () => { try { - const requests = (files || []).map(({ filename, size }) => ({ filename, size })); - await transfers.download({ username, files: requests }); + const requests = (files || []).map(({ filename, size }) => ({ + filename, + size, + })); + await transfers.download({ files: requests, username }); this.setState({ downloadRequest: 'complete' }); - } catch (err) { - this.setState({ downloadRequest: 'error', downloadError: err.response }); + } catch (error) { + this.setState({ + downloadError: error.response, + downloadRequest: 'error', + }); } }); }; - componentDidUpdate = (prevProps) => { - if (this.props.name !== prevProps.name) { - this.setState({ files: this.props.files.map(f => ({ selected: false, ...f }))}); + componentDidUpdate(previousProps) { + if (this.props.name !== previousProps.name) { + this.setState({ + files: this.props.files.map((f) => ({ selected: false, ...f })), + }); } - }; + } - render = () => { - let { username, name, locked, marginTop, onClose } = this.props; - let { files, downloadRequest, downloadError } = this.state; + render() { + const { locked, marginTop, name, onClose, username } = this.props; + const { downloadError, downloadRequest, files } = this.state; - let selectedFiles = files - .filter(f => f.selected); + const selectedFiles = files.filter((f) => f.selected); - let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0)); + const selectedSize = formatBytes( + selectedFiles.reduce((total, f) => total + f.size, 0), + ); return ( - + -
- +
- {selectedFiles.length > 0 && - - + } - centered - size='small' {...rest} /> @@ -41,4 +55,4 @@ const ChatMenu = ({ conversations, active, onConversationChange, ...rest }) => { ); }; -export default ChatMenu; \ No newline at end of file +export default ChatMenu; diff --git a/src/web/src/components/Chat/SendMessageModal.jsx b/src/web/src/components/Chat/SendMessageModal.jsx index 45b85d23..8effb05e 100644 --- a/src/web/src/components/Chat/SendMessageModal.jsx +++ b/src/web/src/components/Chat/SendMessageModal.jsx @@ -1,9 +1,6 @@ -import React, { useEffect } from 'react'; import './Chat.css'; - -import { - Icon, Button, Modal, Form, Header, Input, -} from 'semantic-ui-react'; +import React, { useEffect } from 'react'; +import { Button, Form, Header, Icon, Input, Modal } from 'semantic-ui-react'; const usernameRef = React.createRef(); @@ -34,42 +31,44 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => { return ( setOpen(false)} onOpen={() => setOpen(true)} + open={open} {...rest} >
- + Send Private Message
setUsername(data.value)} + placeholder="Username" + ref={usernameRef} /> setMessage(data.value)} + placeholder="Message" />
- + onClick={() => sendMessage()} + positive + > + Send +
); }; -export default SendMessageModal; \ No newline at end of file +export default SendMessageModal; diff --git a/src/web/src/components/LoginForm.jsx b/src/web/src/components/LoginForm.jsx index faa0fc93..978e1417 100644 --- a/src/web/src/components/LoginForm.jsx +++ b/src/web/src/components/LoginForm.jsx @@ -1,19 +1,31 @@ -import React, { useState, useEffect, useMemo, useRef } from 'react'; -import { Button, Form, Input, Grid, Header, Icon, Segment, Checkbox, Message } from 'semantic-ui-react'; - import Logos from './Shared/Logo'; +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { + Button, + Checkbox, + Form, + Grid, + Header, + Icon, + Input, + Message, + Segment, +} from 'semantic-ui-react'; const initialState = { - username: '', password: '', rememberMe: true, + username: '', }; -const LoginForm = ({ onLoginAttempt, loading, error }) => { +const LoginForm = ({ error, loading, onLoginAttempt }) => { const usernameInput = useRef(); const [state, setState] = useState(initialState); const [ready, setReady] = useState(false); - const logo = useMemo(() => Logos[Math.floor(Math.random() * Logos.length)], []); + const logo = useMemo( + () => Logos[Math.floor(Math.random() * Logos.length)], + [], + ); useEffect(() => { if (state.username !== '' && state.password !== '') { @@ -34,68 +46,81 @@ const LoginForm = ({ onLoginAttempt, loading, error }) => { }); }; - const { username, password, rememberMe } = state; + const { password, rememberMe, username } = state; return ( - <> - - -
+ +
- {logo} -
-
- - handleChange('username', event.target.value)} - disabled={loading} - ref={usernameInput} - /> - handleChange('password', event.target.value)} - disabled={loading} - /> - handleChange('rememberMe', !rememberMe)} - checked={rememberMe} - disabled={loading} - /> - -
+ + + handleChange('username', event.target.value)} + placeholder="Username" + ref={usernameInput} + /> + handleChange('password', event.target.value)} + placeholder="Password" + type="password" + /> + handleChange('rememberMe', !rememberMe)} + /> + + + {error && ( + - - Login - - {error && - + {error.message} - } - -
-
- + + )} + + + ); }; -export default LoginForm; \ No newline at end of file +export default LoginForm; diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx index f1c8aad4..34e3dd78 100644 --- a/src/web/src/components/Rooms/RoomJoinModal.jsx +++ b/src/web/src/components/Rooms/RoomJoinModal.jsx @@ -1,9 +1,15 @@ -import React, { useEffect, useState, useMemo } from 'react'; -import * as rooms from '../../lib/rooms'; import './Rooms.css'; - +import * as rooms from '../../lib/rooms'; +import React, { useEffect, useMemo, useState } from 'react'; import { - Icon, Button, Modal, Table, Header, Input, Loader, Dimmer, + Button, + Dimmer, + Header, + Icon, + Input, + Loader, + Modal, + Table, } from 'semantic-ui-react'; const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { @@ -27,26 +33,26 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { }, [open]); const sortedAvailable = useMemo(() => { - const sorted = [...available].filter(room => room.name.includes(filter)); + const sorted = [...available].filter((room) => room.name.includes(filter)); sorted.sort((a, b) => { if (sortOrder === 'asc') { - if (typeof(a[sortBy]) === 'string') { + if (typeof a[sortBy] === 'string') { return b[sortBy].localeCompare(a[sortBy]); } return a[sortBy] - b[sortBy]; } - if (typeof(a[sortBy]) === 'string') { + if (typeof a[sortBy] === 'string') { return a[sortBy].localeCompare(b[sortBy]); } return b[sortBy] - a[sortBy]; }); - + return sorted; - }, [available, sortBy, sortOrder, filter]); + }, [available, filter, sortBy, sortOrder]); const joinRoom = async () => { await parentJoinRoom(selected); @@ -66,77 +72,108 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { return ( close()} onOpen={() => setOpen(true)} + open={open} {...modalOptions} >
- + Join Room
- {loading ? : + {loading ? ( + + + + ) : ( <> - setFilter(e.value)} - placeholder='Room Filter' - icon='filter' + placeholder="Room Filter" /> - +
setSortBy('name')}> - Name - setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + name={ + sortBy === 'name' && + (sortOrder === 'asc' ? 'chevron up' : 'chevron down') + } + onClick={() => + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc') + } /> setSortBy('userCount')}> - Users - setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')} + name={ + sortBy === 'userCount' && + (sortOrder === 'asc' ? 'chevron up' : 'chevron down') + } + onClick={() => + setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc') + } /> - {sortedAvailable.map((room, index) => + {sortedAvailable.map((room, index) => ( setSelected(room.name)} + style={isSelected(room) ? { fontWeight: 'bold' } : {}} > - {isSelected(room) && } - {room.isPrivate && } - {room.isOwned && } - {room.isModerated && } + {isSelected(room) && ( + + )} + {room.isPrivate && } + {room.isOwned && } + {room.isModerated && } {room.name} {room.userCount} - )} + ))}
- } + + )}
- + onClick={() => joinRoom()} + positive + > + Join +
); }; -export default RoomJoinModal; \ No newline at end of file +export default RoomJoinModal; diff --git a/src/web/src/components/Rooms/RoomMenu.jsx b/src/web/src/components/Rooms/RoomMenu.jsx index b785c66c..d76afdaa 100644 --- a/src/web/src/components/Rooms/RoomMenu.jsx +++ b/src/web/src/components/Rooms/RoomMenu.jsx @@ -1,36 +1,45 @@ -import React from 'react'; import './Rooms.css'; - -import { - Icon, Button, Menu, -} from 'semantic-ui-react'; import RoomJoinModal from './RoomJoinModal'; +import React from 'react'; +import { Button, Icon, Menu } from 'semantic-ui-react'; -const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => { +const RoomMenu = ({ active, joined, onRoomChange, ...rest }) => { const names = [...joined]; const isActive = (name) => active === name; return ( - - {names.map((name, index) => + + {names.map((name, index) => ( onRoomChange(name)} > - + {name} - )} - + ))} + + } - centered - size='small' {...rest} /> @@ -38,4 +47,4 @@ const RoomMenu = ({ joined, active, onRoomChange, ...rest }) => { ); }; -export default RoomMenu; \ No newline at end of file +export default RoomMenu; diff --git a/src/web/src/components/Rooms/RoomUserList.jsx b/src/web/src/components/Rooms/RoomUserList.jsx index 663961e8..fc37625b 100644 --- a/src/web/src/components/Rooms/RoomUserList.jsx +++ b/src/web/src/components/Rooms/RoomUserList.jsx @@ -1,15 +1,18 @@ -import React, { useMemo } from 'react'; import './Rooms.css'; - -import { - Icon, Flag, List, Popup, -} from 'semantic-ui-react'; +import React, { useMemo } from 'react'; +import { Flag, Icon, List, Popup } from 'semantic-ui-react'; const RoomUserList = ({ users }) => { const getFlag = (user) => { - if (!(user || {}).countryCode) return ; - - return ; + if (!(user || {}).countryCode) + return ( + + ); + + return ; }; const getDetails = (user) => { @@ -19,26 +22,38 @@ const RoomUserList = ({ users }) => { const sortedUsers = useMemo(() => { const filtered = [...users] .sort((a, b) => a.username.localeCompare(b.username)) - .reduce((acc, user) => { - (user.status === 'Online' ? acc.online : acc.offline).push(user); - return acc; - }, { online: [], offline: []}); + .reduce( + (accumulator, user) => { + (user.status === 'Online' + ? accumulator.online + : accumulator.offline + ).push(user); + return accumulator; + }, + { offline: [], online: [] }, + ); return [...filtered.online, ...filtered.offline]; }, [users]); return ( - {sortedUsers.map((user, index) => - - - + {sortedUsers.map((user, index) => ( + + + {user.username} - )} + ))} ); }; -export default RoomUserList; \ No newline at end of file +export default RoomUserList; diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 066c0ab1..e4d17d7c 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -1,53 +1,65 @@ -import React, { Component, createRef } from 'react'; -import * as rooms from '../../lib/rooms'; import { activeRoomKey } from '../../config'; - -import { Segment, Card, Icon, Input, Ref, List, Loader, Dimmer } from 'semantic-ui-react'; - +import * as rooms from '../../lib/rooms'; +import PlaceholderSegment from '../Shared/PlaceholderSegment'; import RoomMenu from './RoomMenu'; import RoomUserList from './RoomUserList'; -import PlaceholderSegment from '../Shared/PlaceholderSegment'; +import React, { Component, createRef } from 'react'; +import { + Card, + Dimmer, + Icon, + Input, + List, + Loader, + Ref, + Segment, +} from 'semantic-ui-react'; const initialState = { active: '', + intervals: { + messages: undefined, + rooms: undefined, + }, joined: [], + loading: false, room: { messages: [], users: [], }, - intervals: { - rooms: undefined, - messages: undefined, - }, - loading: false, }; class Rooms extends Component { state = initialState; + messageRef = undefined; + listRef = createRef(); - componentDidMount = async () => { - this.setState({ - intervals: { - rooms: window.setInterval(this.fetchJoinedRooms, 500), - messages: window.setInterval(this.fetchActiveRoom, 1000), + componentDidMount() { + this.setState( + { + active: sessionStorage.getItem(activeRoomKey) || '', + intervals: { + messages: window.setInterval(this.fetchActiveRoom, 1_000), + rooms: window.setInterval(this.fetchJoinedRooms, 500), + }, }, - active: sessionStorage.getItem(activeRoomKey) || '', - }, async () => { - await this.fetchJoinedRooms(); - this.selectRoom(this.state.active || this.getFirstRoom()); - }); - }; + async () => { + await this.fetchJoinedRooms(); + this.selectRoom(this.state.active || this.getFirstRoom()); + }, + ); + } - componentWillUnmount = () => { - const { rooms, messages } = this.state.intervals; + componentWillUnmount() { + const { messages, rooms } = this.state.intervals; clearInterval(rooms); clearInterval(messages); this.setState({ intervals: initialState.intervals }); - }; + } getFirstRoom = () => { return this.state.joined.length > 0 ? this.state.joined[0] : ''; @@ -55,13 +67,16 @@ class Rooms extends Component { fetchJoinedRooms = async () => { const joined = await rooms.getJoined(); - this.setState({ - joined, - }, () => { - if (!this.state.joined.includes(this.state.active)) { - this.selectRoom(this.getFirstRoom()); - } - }); + this.setState( + { + joined, + }, + () => { + if (!this.state.joined.includes(this.state.active)) { + this.selectRoom(this.getFirstRoom()); + } + }, + ); }; fetchActiveRoom = async () => { @@ -74,31 +89,34 @@ class Rooms extends Component { this.setState({ room: { - users, messages, + users, }, }); }; selectRoom = async (roomName) => { - this.setState({ - active: roomName, - room: initialState.room, - loading: true, - }, async () => { - const { active } = this.state; - - sessionStorage.setItem(activeRoomKey, active); - - await this.fetchActiveRoom(); - this.setState({ loading: false }, () => { - try { - this.listRef.current.lastChild.scrollIntoView(); - } catch { - // no-op - } - }); - }); + this.setState( + { + active: roomName, + loading: true, + room: initialState.room, + }, + async () => { + const { active } = this.state; + + sessionStorage.setItem(activeRoomKey, active); + + await this.fetchActiveRoom(); + this.setState({ loading: false }, () => { + try { + this.listRef.current.lastChild.scrollIntoView(); + } catch { + // no-op + } + }); + }, + ); }; joinRoom = async (roomName) => { @@ -114,20 +132,25 @@ class Rooms extends Component { }; validInput = () => - (this.state.active || '').length > 0 - && ((this.messageRef && this.messageRef.current && this.messageRef.current.value) || '').length > 0; - + (this.state.active || '').length > 0 && + ( + (this.messageRef && + this.messageRef.current && + this.messageRef.current.value) || + '' + ).length > 0; + focusInput = () => { this.messageRef.current.focus(); }; formatTimestamp = (timestamp) => { const date = new Date(timestamp); - const dtfUS = new Intl.DateTimeFormat('en', { - month: 'numeric', + const dtfUS = new Intl.DateTimeFormat('en', { day: 'numeric', hour: 'numeric', minute: '2-digit', + month: 'numeric', }); return dtfUS.format(date); @@ -141,85 +164,135 @@ class Rooms extends Component { return; } - await rooms.sendMessage({ roomName: active, message }); + await rooms.sendMessage({ message, roomName: active }); this.messageRef.current.value = ''; }; - render = () => { - const { joined = [], active = [], room, loading } = this.state; + render() { + const { active = [], joined = [], loading, room } = this.state; return ( -
- -
+
+ +
+ +
this.selectRoom(name)} joinRoom={this.joinRoom} + joined={joined} + onRoomChange={(name) => this.selectRoom(name)} />
- {!active ? - : - + {!active ? ( + + ) : ( + this.focusInput()}> - + {active} - this.leaveRoom(active)} /> -
- {loading ? : <> - - - - - {room.messages.map((message, index) => - - {this.formatTimestamp(message.timestamp)} - {message.username}: - {message.message} - - )} - - - - - - } - ref={input => this.messageRef = input && input.inputRef} - action={{ - icon: , - className: 'room-message-button', onClick: this.sendMessage, - disabled: !this.validInput(), - }} - onKeyUp={(e) => e.key === 'Enter' ? this.sendMessage() : ''} - /> +
+ {loading ? ( + + + + ) : ( + <> + + + + + {room.messages.map((message, index) => ( + + + {this.formatTimestamp(message.timestamp)} + + + {message.username}:{' '} + + + {message.message} + + + ))} + + + + + + + ), + onClick: this.sendMessage, + }} + fluid + input={ + + } + onKeyUp={(e) => + e.key === 'Enter' ? this.sendMessage() : '' + } + ref={(input) => + (this.messageRef = input && input.inputRef) + } + transparent + /> + + + + - - - - - } + + )}
- } + + )}
); - }; + } } -export default Rooms; \ No newline at end of file +export default Rooms; diff --git a/src/web/src/components/Search/Detail/SearchDetail.jsx b/src/web/src/components/Search/Detail/SearchDetail.jsx index 99175bd0..488affc3 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.jsx +++ b/src/web/src/components/Search/Detail/SearchDetail.jsx @@ -1,28 +1,42 @@ -import React, { useEffect, useState, useMemo } from 'react'; - import { - Checkbox, - Input, - Segment, - Dropdown, - Button, -} from 'semantic-ui-react'; - + filterResponse, + getResponses, + parseFiltersFromString, +} from '../../../lib/searches'; import { sleep } from '../../../lib/util'; -import Switch from '../../Shared/Switch'; import ErrorSegment from '../../Shared/ErrorSegment'; -import Response from '../Response'; -import { getResponses, parseFiltersFromString, filterResponse } from '../../../lib/searches'; import LoaderSegment from '../../Shared/LoaderSegment'; +import Switch from '../../Shared/Switch'; +import Response from '../Response'; import SearchDetailHeader from './SearchDetailHeader'; +import React, { useEffect, useMemo, useState } from 'react'; +import { Button, Checkbox, Dropdown, Input, Segment } from 'semantic-ui-react'; const sortDropdownOptions = [ - { key: 'uploadSpeed', text: 'Upload Speed (Fastest to Slowest)', value: 'uploadSpeed' }, - { key: 'queueLength', text: 'Queue Depth (Least to Most)', value: 'queueLength' }, + { + key: 'uploadSpeed', + text: 'Upload Speed (Fastest to Slowest)', + value: 'uploadSpeed', + }, + { + key: 'queueLength', + text: 'Queue Depth (Least to Most)', + value: 'queueLength', + }, ]; -const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate, onStop, onRemove }) => { - const { id, state, isComplete, fileCount, lockedFileCount, responseCount } = search; +const SearchDetail = ({ + creating, + disabled, + onCreate, + onRemove, + onStop, + removing, + search, + stopping, +}) => { + const { fileCount, id, isComplete, lockedFileCount, responseCount, state } = + search; const [loading, setLoading] = useState(false); const [error, setError] = useState(undefined); @@ -48,7 +62,7 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate // the results may not be ready yet. this is very rare, but // if it happens the search will complete with no results. await sleep(500); - + const responses = await getResponses({ id }); setResults(responses); setLoading(false); @@ -67,8 +81,8 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate // sets, so memoize it. const sortedAndFilteredResults = useMemo(() => { const sortOptions = { - uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, queueLength: { field: 'queueLength', order: 'asc' }, + uploadSpeed: { field: 'uploadSpeed', order: 'desc' }, }; const { field, order } = sortOptions[resultSort]; @@ -76,16 +90,17 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate const filters = parseFiltersFromString(resultFilters); return results - .filter(r => !hiddenResults.includes(r.username)) - .map(r => { + .filter((r) => !hiddenResults.includes(r.username)) + .map((r) => { if (hideLocked) { return { ...r, lockedFileCount: 0, lockedFiles: [] }; } + return r; }) - .map(response => filterResponse({ response, filters })) - .filter(r => r.fileCount + r.lockedFileCount > 0) - .filter(r => !(hideNoFreeSlots && !r.hasFreeUploadSlot)) + .map((response) => filterResponse({ filters, response })) + .filter((r) => r.fileCount + r.lockedFileCount > 0) + .filter((r) => !(hideNoFreeSlots && !r.hasFreeUploadSlot)) .sort((a, b) => { if (order === 'asc') { return a[field] - b[field]; @@ -93,8 +108,14 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate return b[field] - a[field]; }); - - }, [results, hideLocked, hideNoFreeSlots, resultFilters, resultSort, hiddenResults]); + }, [ + hiddenResults, + hideLocked, + hideNoFreeSlots, + resultFilters, + resultSort, + results, + ]); // when a user uses the action buttons, we will *probably* re-use this component, // but with a new search ID. clear everything to prepare for the transition @@ -106,9 +127,9 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate setDisplayCount(5); }; - const create = async ({ search, navigate }) => { - reset(); - onCreate({ search, navigate }); + const create = async ({ navigate, search }) => { + reset(); + onCreate({ navigate, search }); }; const remove = async () => { @@ -118,109 +139,136 @@ const SearchDetail = ({ search, creating, stopping, removing, disabled, onCreate const filteredCount = results?.length - sortedAndFilteredResults.length; const remainingCount = sortedAndFilteredResults.length - displayCount; - const loaded = (!removing && !creating && !loading && results); + const loaded = !removing && !creating && !loading && results; if (error) { - return (); + return ; } return ( <> - - {state === 'InProgress' - ? `Found ${fileCount} files ${lockedFileCount > 0 - ? `(plus ${lockedFileCount} locked) ` - : ''}from ${responseCount} users` - : 'Loading results...'} - + } + searching={ + !isComplete && ( + + {state === 'InProgress' + ? `Found ${fileCount} files ${ + lockedFileCount > 0 + ? `(plus ${lockedFileCount} locked) ` + : '' + }from ${responseCount} users` + : 'Loading results...'} + + ) } - loading={loading && } > - {loaded && - + {loaded && ( + setResultSort(value)} - text={sortDropdownOptions.find(o => o.value === resultSort).text} + options={sortDropdownOptions} + text={ + sortDropdownOptions.find((o) => o.value === resultSort).text + } /> -
+
setHideLocked(!hideLocked)} checked={hideLocked} - label='Hide Locked Results' + className="search-options-hide-locked" + label="Hide Locked Results" + onChange={() => setHideLocked(!hideLocked)} + toggle /> setHideNoFreeSlots(!hideNoFreeSlots)} checked={hideNoFreeSlots} - label='Hide Results with No Free Slots' + className="search-options-hide-no-slots" + label="Hide Results with No Free Slots" + onChange={() => setHideNoFreeSlots(!hideNoFreeSlots)} + toggle /> setFoldResults(!foldResults)} checked={foldResults} - label='Fold Results' + className="search-options-fold-results" + label="Fold Results" + onChange={() => setFoldResults(!foldResults)} + toggle />
- setResultFilters(''), + } + } + className="search-filter" + label={{ content: 'Filter', icon: 'filter' }} + onChange={(e, data) => setResultFilters(data.value)} + placeholder=" lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minbitdepth:24 minfilesize:10 minfilesinfolder:8 minlength:5000 - ' - label={{ icon: 'filter', content: 'Filter' }} + " value={resultFilters} - onChange={(e, data) => setResultFilters(data.value)} - action={!!resultFilters && { icon: 'x', color: 'red', onClick: () => setResultFilters('')}} /> - } - {loaded && sortedAndFilteredResults.slice(0, displayCount).map((r, i) => - setHiddenResults([...hiddenResults, r.username])} - isInitiallyFolded={foldResults} - /> )} - {loaded && (remainingCount > 0 ? - - : filteredCount > 0 ? - : '')} + {loaded && + sortedAndFilteredResults.slice(0, displayCount).map((r, index) => ( + setHiddenResults([...hiddenResults, r.username])} + response={r} + /> + ))} + {loaded && + (remainingCount > 0 ? ( + + ) : filteredCount > 0 ? ( + + ) : ( + '' + ))} ); }; -export default SearchDetail; \ No newline at end of file +export default SearchDetail; diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx index 2071540f..25c5789b 100644 --- a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx @@ -1,30 +1,24 @@ +import SearchStatusIcon from '../SearchStatusIcon'; import React from 'react'; import { useMediaQuery } from 'react-responsive'; - -import { - Segment, - Button, - Header, - Icon, -} from 'semantic-ui-react'; -import SearchStatusIcon from '../SearchStatusIcon'; +import { Button, Header, Icon, Segment } from 'semantic-ui-react'; const SearchDetailHeader = ({ - search, - loading, - loaded, creating, - removing, - stopping, disabled, + loaded, + loading, onCreate, - onStop, onRemove, + onStop, + removing, + search, + stopping, }) => { const isSmallScreen = useMediaQuery({ query: '(max-width: 899px)' }); - const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)'}); + const isTinyScreen = useMediaQuery({ query: '(max-width: 684px)' }); - const { searchText, isComplete, state } = search; + const { isComplete, searchText, state } = search; const working = loading || creating || removing || stopping; const stopOrRemove = () => { @@ -35,49 +29,62 @@ const SearchDetailHeader = ({ } }; - const RefreshButton = () => loaded && - ; + const RefreshButton = () => + loaded && ( + + ); - const StopOrDeleteButton = () => - ; + + {(!isSmallScreen || isTinyScreen) && + (loaded && isComplete ? 'Delete' : 'Stop')} + + ); // if the screen is full width, display the header and action buttons in the same segment, with full // button text. if the screen is between 684 and 899 pixels, display the buttons with no text. // if the screen is less than 684 pixels, display the action buttons in a new segment, with full text. return ( <> - +
- {searchText} + + {searchText}
- {!isTinyScreen &&
- - -
} + {!isTinyScreen && ( +
+ + +
+ )}
- {isTinyScreen && - - - } + {isTinyScreen && ( + + + + + )} ); }; -export default SearchDetailHeader; \ No newline at end of file +export default SearchDetailHeader; diff --git a/src/web/src/components/Search/List/SearchActionIcon.jsx b/src/web/src/components/Search/List/SearchActionIcon.jsx index baec2ccc..59a59987 100644 --- a/src/web/src/components/Search/List/SearchActionIcon.jsx +++ b/src/web/src/components/Search/List/SearchActionIcon.jsx @@ -1,27 +1,36 @@ import React from 'react'; - import { Icon } from 'semantic-ui-react'; -const SearchActionIcon = ({ search, loading, onRemove, onStop,...props }) => { +const SearchActionIcon = ({ loading, onRemove, onStop, search, ...props }) => { if (loading) { - return (); + return ( + + ); } if (search.state.includes('Completed')) { - return ( onRemove()} - style={{ cursor: 'pointer' }} - />); + return ( + onRemove()} + style={{ cursor: 'pointer' }} + /> + ); } - return ( onStop()} - style={{ cursor: 'pointer' }} - />); + return ( + onStop()} + style={{ cursor: 'pointer' }} + /> + ); }; -export default SearchActionIcon; \ No newline at end of file +export default SearchActionIcon; diff --git a/src/web/src/components/Search/List/SearchList.jsx b/src/web/src/components/Search/List/SearchList.jsx index b78c7919..e5843972 100644 --- a/src/web/src/components/Search/List/SearchList.jsx +++ b/src/web/src/components/Search/List/SearchList.jsx @@ -1,52 +1,73 @@ -import React from 'react'; - -import SearchListRow from './SearchListRow'; import ErrorSegment from '../../Shared/ErrorSegment'; import Switch from '../../Shared/Switch'; - -import { - Card, - Table, - Icon, - Loader, -} from 'semantic-ui-react'; +import SearchListRow from './SearchListRow'; +import React from 'react'; +import { Card, Icon, Loader, Table } from 'semantic-ui-react'; const SearchList = ({ connecting = false, error = undefined, + onRemove = () => {}, + onStop = () => {}, searches = {}, - onRemove = () => { }, - onStop = () => { }, }) => { return ( - + -
+
} + connecting={ + connecting && ( + + ) + } error={error && } > - +
- - Search - Files - Locked - Responses - Ended - + + + + + Search + + + Files + + + Locked + + + Responses + + + Ended + + {Object.values(searches) - .sort((a, b) => (new Date(b.startedAt) - new Date(a.startedAt))) - .map((search, index) => )} + .sort((a, b) => new Date(b.startedAt) - new Date(a.startedAt)) + .map((search, index) => ( + + ))}
@@ -56,4 +77,4 @@ const SearchList = ({ ); }; -export default SearchList; \ No newline at end of file +export default SearchList; diff --git a/src/web/src/components/Search/List/SearchListRow.jsx b/src/web/src/components/Search/List/SearchListRow.jsx index feffdcea..32b21797 100644 --- a/src/web/src/components/Search/List/SearchListRow.jsx +++ b/src/web/src/components/Search/List/SearchListRow.jsx @@ -1,27 +1,18 @@ -import React, { useState } from 'react'; - -import { - Link, - useRouteMatch, -} from 'react-router-dom'; - -import { - Table, - Icon, -} from 'semantic-ui-react'; - import SearchStatusIcon from '../SearchStatusIcon'; import SearchActionIcon from './SearchActionIcon'; +import React, { useState } from 'react'; +import { Link, useRouteMatch } from 'react-router-dom'; +import { Icon, Table } from 'semantic-ui-react'; -const SearchListRow = ({ search, onRemove, onStop }) => { +const SearchListRow = ({ onRemove, onStop, search }) => { const [working, setWorking] = useState(false); const match = useRouteMatch(); - const invoke = async (func) => { + const invoke = async (function_) => { setWorking(true); try { - await func(); + await function_(); } catch (error) { console.error(error); } finally { @@ -35,21 +26,30 @@ const SearchListRow = ({ search, onRemove, onStop }) => { style={{ cursor: working ? 'wait' : undefined }} > - + + + + {search.searchText} - {search.searchText} {search.fileCount} - {search.lockedFileCount} + + + {search.lockedFileCount} + {search.responseCount} - {search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'} + + {search.endedAt ? new Date(search.endedAt).toLocaleTimeString() : '-'} + invoke(() => onRemove(search))} onStop={() => invoke(() => onStop(search))} + search={search} style={{ cursor: 'pointer' }} /> @@ -57,4 +57,4 @@ const SearchListRow = ({ search, onRemove, onStop }) => { ); }; -export default SearchListRow; \ No newline at end of file +export default SearchListRow; diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx index babfc22b..ce857bf3 100644 --- a/src/web/src/components/Search/Response.jsx +++ b/src/web/src/components/Search/Response.jsx @@ -1,63 +1,70 @@ -import React, { Component } from 'react'; import * as transfers from '../../lib/transfers'; -import { toast } from 'react-toastify'; - +import { getDirectoryContents } from '../../lib/users'; import { formatBytes, getDirectoryName } from '../../lib/util'; - import FileList from '../Shared/FileList'; - -import { - Button, - Card, - Icon, - Label, -} from 'semantic-ui-react'; -import { getDirectoryContents } from '../../lib/users'; +import React, { Component } from 'react'; +import { toast } from 'react-toastify'; +import { Button, Card, Icon, Label } from 'semantic-ui-react'; const buildTree = (response) => { let { files = [], lockedFiles = [] } = response; - files = files.concat(lockedFiles.map(file => ({ ...file, locked: true }))); + files = files.concat(lockedFiles.map((file) => ({ ...file, locked: true }))); return files.reduce((dict, file) => { - let dir = getDirectoryName(file.filename); - let selectable = { selected: false, ...file }; - dict[dir] = dict[dir] === undefined ? [ selectable ] : dict[dir].concat(selectable); + const dir = getDirectoryName(file.filename); + const selectable = { selected: false, ...file }; + dict[dir] = + dict[dir] === undefined ? [selectable] : dict[dir].concat(selectable); return dict; }, {}); }; class Response extends Component { - state = { - tree: buildTree(this.props.response), - downloadRequest: undefined, + state = { downloadError: '', + downloadRequest: undefined, fetchingDirectoryContents: false, isFolded: this.props.isInitiallyFolded, + tree: buildTree(this.props.response), }; - componentDidUpdate = (prevProps) => { - if (JSON.stringify(this.props.response) !== JSON.stringify(prevProps.response)) { + componentDidUpdate(previousProps) { + if ( + JSON.stringify(this.props.response) !== + JSON.stringify(previousProps.response) + ) { this.setState({ tree: buildTree(this.props.response) }); } - if (this.props.isInitiallyFolded !== prevProps.isInitiallyFolded) { + + if (this.props.isInitiallyFolded !== previousProps.isInitiallyFolded) { this.setState({ isFolded: this.props.isInitiallyFolded }); } - }; + } onFileSelectionChange = (file, state) => { file.selected = state; - this.setState({ tree: this.state.tree, downloadRequest: undefined, downloadError: '' }); + this.setState({ + downloadError: '', + downloadRequest: undefined, + tree: this.state.tree, + }); }; download = (username, files) => { this.setState({ downloadRequest: 'inProgress' }, async () => { try { - const requests = (files || []).map(({ filename, size }) => ({ filename, size })); - await transfers.download({ username, files: requests }); + const requests = (files || []).map(({ filename, size }) => ({ + filename, + size, + })); + await transfers.download({ files: requests, username }); this.setState({ downloadRequest: 'complete' }); - } catch (err) { - this.setState({ downloadRequest: 'error', downloadError: err.response }); + } catch (error) { + this.setState({ + downloadError: error.response, + downloadRequest: 'error', + }); } }); }; @@ -69,15 +76,20 @@ class Response extends Component { const oldTree = { ...this.state.tree }; const oldFiles = oldTree[directory]; - const { name, files } = await getDirectoryContents({ username, directory }); + const { files, name } = await getDirectoryContents({ + directory, + username, + }); // the api returns file names only, so we need to prepend the directory // to make it look like a search result. we also need to preserve // any file selections, so check the old files and assign accordingly - const fixedFiles = files.map(file => ({ + const fixedFiles = files.map((file) => ({ ...file, filename: `${directory}\\${file.filename}`, - selected: oldFiles.find(f => f.filename === `${directory}\\${file.filename}`)?.selected ?? false, + selected: + oldFiles.find((f) => f.filename === `${directory}\\${file.filename}`) + ?.selected ?? false, })); oldTree[name] = fixedFiles; @@ -94,20 +106,31 @@ class Response extends Component { this.setState({ isFolded: !this.state.isFolded }); }; - render = () => { - let {response} = this.props; - let free = response.hasFreeUploadSlot; + render() { + const { response } = this.props; + const free = response.hasFreeUploadSlot; - let { tree, downloadRequest, downloadError, isFolded, fetchingDirectoryContents } = this.state; + const { + downloadError, + downloadRequest, + fetchingDirectoryContents, + isFolded, + tree, + } = this.state; - let selectedFiles = Object.keys(tree) + const selectedFiles = Object.keys(tree) .reduce((list, dict) => list.concat(tree[dict]), []) - .filter(f => f.selected); + .filter((f) => f.selected); - let selectedSize = formatBytes(selectedFiles.reduce((total, f) => total + f.size, 0)); + const selectedSize = formatBytes( + selectedFiles.reduce((total, f) => total + f.size, 0), + ); return ( - + - + {response.username} - this.props.onHide()} /> - + - Upload Speed: {formatBytes(response.uploadSpeed)}/s, - Free Upload Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength} + Upload Speed: {formatBytes(response.uploadSpeed)}/s, Free Upload + Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength} + - {((!isFolded && Object.keys(tree)) || []).map((dir, i) => - ( + file.locked)} - files={tree[dir]} disabled={downloadRequest === 'inProgress'} + files={tree[dir]} + footer={ + + } + key={index} + locked={tree[dir].find((file) => file.locked)} onSelectionChange={this.onFileSelectionChange} - footer={} /> - )} + ))} - {selectedFiles.length > 0 && - - ); @@ -19,12 +21,18 @@ const ShrinkableButton = ({ icon, loading, mediaQuery, children, ...rest }) => { - + } /> ); }; -export default ShrinkableButton; \ No newline at end of file +export default ShrinkableButton; diff --git a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx index bdf6b3a1..008e93bd 100644 --- a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx +++ b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx @@ -1,23 +1,18 @@ -import React from 'react'; - -import { - Button, - Dropdown, -} from 'semantic-ui-react'; - import ShrinkableButton from './ShrinkableButton'; +import React from 'react'; +import { Button, Dropdown } from 'semantic-ui-react'; -const ShrinkableDropdownButton = ({ - color, - icon, - mediaQuery, - disabled, - loading, - options, - onClick, - onChange, - hidden, +const ShrinkableDropdownButton = ({ children, + color, + disabled, + hidden, + icon, + loading, + mediaQuery, + onChange, + onClick, + options, }) => { if (hidden) { return <>; @@ -26,21 +21,23 @@ const ShrinkableDropdownButton = ({ return ( {children} + mediaQuery={mediaQuery} + onClick={onClick} + > + {children} + } /> ); }; -export default ShrinkableDropdownButton; \ No newline at end of file +export default ShrinkableDropdownButton; diff --git a/src/web/src/components/Shared/Switch.jsx b/src/web/src/components/Shared/Switch.jsx index 7dad342f..d0c0f1f3 100644 --- a/src/web/src/components/Shared/Switch.jsx +++ b/src/web/src/components/Shared/Switch.jsx @@ -1,11 +1,11 @@ const Switch = ({ children, ...rest }) => { const values = Object.values(rest); - for (let i = 0; i < values.length; i++) { - if (values[i]) return values[i]; + for (const value of values) { + if (value) return value; } return children; }; -export default Switch; \ No newline at end of file +export default Switch; diff --git a/src/web/src/components/Shared/index.js b/src/web/src/components/Shared/index.js index e9c9128d..0e36bc48 100644 --- a/src/web/src/components/Shared/index.js +++ b/src/web/src/components/Shared/index.js @@ -7,4 +7,4 @@ export { default as Nbsp } from './Nbsp'; export { default as PlaceholderSegment } from './PlaceholderSegment'; export { default as ShrinkableButton } from './ShrinkableButton'; export { default as ShrinkableDropdownButton } from './ShrinkableDropdownButton'; -export { default as Switch } from './Switch'; \ No newline at end of file +export { default as Switch } from './Switch'; diff --git a/src/web/src/components/System/Data/index.jsx b/src/web/src/components/System/Data/index.jsx index 742aa309..1df4f981 100644 --- a/src/web/src/components/System/Data/index.jsx +++ b/src/web/src/components/System/Data/index.jsx @@ -1,8 +1,7 @@ +import { clearCompleted } from '../../../lib/transfers'; import React, { useState } from 'react'; -import { Button, Divider, Header, Icon } from 'semantic-ui-react'; import { toast } from 'react-toastify'; - -import { clearCompleted } from '../../../lib/transfers'; +import { Button, Divider, Header, Icon } from 'semantic-ui-react'; const Data = () => { const [up, setUp] = useState(false); @@ -17,30 +16,38 @@ const Data = () => { return (
-
Transfer Data
- -

- The Uploads and Downloads pages can become unresponsive if too many transfers are displayed. If you're having - trouble with either page, try using the buttons below to remove completed transfers. -

+
+ Transfer Data +
+ +

+ + The Uploads and Downloads pages can become unresponsive if too many + transfers are displayed. If you're having trouble with either page, + try using the buttons below to remove completed transfers. + +

); }; -export default Data; \ No newline at end of file +export default Data; diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx index 77b2f958..6b677144 100644 --- a/src/web/src/components/System/Files/Explorer.jsx +++ b/src/web/src/components/System/Files/Explorer.jsx @@ -1,25 +1,18 @@ -import React, { useState, useEffect } from 'react'; - -import { - Table, - Icon, - Modal, - Header, -} from 'semantic-ui-react'; - -import { list, deleteDirectory, deleteFile } from '../../../lib/files'; +import { deleteDirectory, deleteFile, list } from '../../../lib/files'; import { formatBytes, formatDate } from '../../../lib/util'; import { LoaderSegment } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { Header, Icon, Modal, Table } from 'semantic-ui-react'; -const Explorer = ({ root, remoteFileManagement }) => { - const [directory, setDirectory] = useState({ files: [], directories: [] }); +const Explorer = ({ remoteFileManagement, root }) => { + const [directory, setDirectory] = useState({ directories: [], files: [] }); const [subdirectory, setSubdirectory] = useState([]); const [loading, setLoading] = useState(false); - + useEffect(() => { fetch(); }, [subdirectory]); // eslint-disable-line react-hooks/exhaustive-deps - + useEffect(() => { setSubdirectory([]); }, [root]); @@ -41,115 +34,188 @@ const Explorer = ({ root, remoteFileManagement }) => { setSubdirectory(copy); }; - const FileRow = ({ name, fullName, modifiedAt, length }) => - {name} - {modifiedAt ? formatDate(modifiedAt) : ''} - {length ? formatBytes(length) : ''} - - {remoteFileManagement - ? - } - centered - size='small' - header={
} - content={`Are you sure you want to delete file '${fullName}'?`} - actions={[ - 'Cancel', - { - key: 'done', - content: 'Delete', - negative: true, - onClick: async () => { - await deleteFile({ root, path: `${subdirectory.join('/')}/${fullName}`}); - fetch(); + const FileRow = ({ fullName, length, modifiedAt, name }) => ( + + + + {name} + + {modifiedAt ? formatDate(modifiedAt) : ''} + {length ? formatBytes(length) : ''} + + {remoteFileManagement ? ( + { + await deleteFile({ + path: `${subdirectory.join('/')}/${fullName}`, + root, + }); + fetch(); + }, }, - }, - ]}/> - : <>} - - ; + ]} + centered + content={`Are you sure you want to delete file '${fullName}'?`} + header={ +
+ } + size="small" + trigger={ + + } + /> + ) : ( + <> + )} + + + ); const DirectoryRow = ({ - name, + deletable = true, fullName, modifiedAt, + name, onClick = () => {}, - deletable = true, - }) => - {name} - {modifiedAt ? formatDate(modifiedAt) : ''} - - - {remoteFileManagement && deletable - ? - } - centered - size='small' - header={
} - content={`Are you sure you want to delete directory '${fullName}'?`} - actions={[ - 'Cancel', - { - key: 'done', - content: 'Delete', - negative: true, - onClick: async () => { - await deleteDirectory({ root, path: `${subdirectory.join('/')}/${fullName}`}); - fetch(); + }) => ( + + + + {name} + + {modifiedAt ? formatDate(modifiedAt) : ''} + + + {remoteFileManagement && deletable ? ( + { + await deleteDirectory({ + path: `${subdirectory.join('/')}/${fullName}`, + root, + }); + fetch(); + }, }, - }, - ]} - /> - : ''} - - ; + ]} + centered + content={`Are you sure you want to delete directory '${fullName}'?`} + header={ +
+ } + size="small" + trigger={ + + } + /> + ) : ( + '' + )} + + + ); if (loading) { - return ; + return ; } const total = directory?.directories?.length + directory?.files?.length ?? 0; return ( <> -
- {'/' + root + '/' + subdirectory.join('/')} +
+ + {'/' + root + '/' + subdirectory.join('/')}
- +
- Name - Date Modified - Size - + + Name + + + Date Modified + + + Size + + - {total === 0 - ? - + {total === 0 ? ( + + No files or directories - : <> - {subdirectory.length > 0 - && } - {directory?.directories?.map(d => select({ path: d.name })} {...d}/>)} - {directory?.files?.map(f => )} + ) : ( + <> + {subdirectory.length > 0 && ( + + )} + {directory?.directories?.map((d) => ( + select({ path: d.name })} + {...d} + /> + ))} + {directory?.files?.map((f) => ( + + ))} - } + )}
); }; -export default Explorer; \ No newline at end of file +export default Explorer; diff --git a/src/web/src/components/System/Files/index.jsx b/src/web/src/components/System/Files/index.jsx index a7a90aba..5b177452 100644 --- a/src/web/src/components/System/Files/index.jsx +++ b/src/web/src/components/System/Files/index.jsx @@ -1,32 +1,43 @@ -import React from 'react'; -import { Tab } from 'semantic-ui-react'; - import './Files.css'; import Explorer from './Explorer'; +import React from 'react'; +import { Tab } from 'semantic-ui-react'; const Files = ({ options } = {}) => { const { remoteFileManagement } = options; const panes = [ - { - route: 'downloads', + { menuItem: 'Downloads', - render: () => , + render: () => ( + + + + ), + route: 'downloads', }, - { - route: 'incomplete', + { menuItem: 'Incomplete', - render: () => , + render: () => ( + + + + ), + route: 'incomplete', }, ]; return (
- +
); }; -export default Files; \ No newline at end of file +export default Files; diff --git a/src/web/src/components/System/Info/index.jsx b/src/web/src/components/System/Info/index.jsx index 2793ee0d..8672b5df 100644 --- a/src/web/src/components/System/Info/index.jsx +++ b/src/web/src/components/System/Info/index.jsx @@ -1,23 +1,22 @@ -import React, { useState, useEffect } from 'react'; -import YAML from 'yaml'; - -import { restart, shutdown, getVersion } from '../../../lib/application'; - -import { Modal, Header, Divider } from 'semantic-ui-react'; - +import { getVersion, restart, shutdown } from '../../../lib/application'; import { CodeEditor, LoaderSegment, ShrinkableButton, Switch, } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { Divider, Header, Modal } from 'semantic-ui-react'; +import YAML from 'yaml'; const Info = ({ state, theme }) => { const [contents, setContents] = useState(); useEffect(() => { setTimeout(() => { - setContents(YAML.stringify(state, { simpleKeys: true, sortMapEntries: false })); + setContents( + YAML.stringify(state, { simpleKeys: true, sortMapEntries: false }), + ); }, 250); }, [state]); @@ -25,77 +24,105 @@ const Info = ({ state, theme }) => { return ( <> -
-
+
+
getVersion({ forceCheck: true })} + primary > Check for Updates - window.open(`http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`, '_blank')} + icon="star" + mediaQuery="(max-width: 686px)" + onClick={() => + window.open( + `http://www.slsknet.org/qtlogin.php?username=${state?.user?.username}`, + '_blank', + ) + } > Get Privileges
+ } + size="mini" trigger={ Shut Down } - centered - size='mini' - header={
} - content="Are you sure you want to shut the application down? You'll need to manually start it again." - actions={['Cancel', { key: 'done', content: 'Shut Down', negative: true, onClick: shutdown }]} /> + } + size="mini" trigger={ Restart } - centered - size='mini' - header={
} - content='Are you sure you want restart the application?' - actions={['Cancel', { key: 'done', content: 'Restart', negative: true, onClick: restart }]} />
- - } - > + + }> ); }; -export default Info; \ No newline at end of file +export default Info; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx index b30b0a43..3c199f42 100644 --- a/src/web/src/components/System/Logs/index.jsx +++ b/src/web/src/components/System/Logs/index.jsx @@ -1,21 +1,19 @@ -import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; - +import '../System.css'; import { createLogsHubConnection } from '../../../lib/hubFactory'; import { LoaderSegment } from '../../Shared'; - -import '../System.css'; +import React, { Component } from 'react'; +import { Table } from 'semantic-ui-react'; const initialState = { - logs: [], connected: false, + logs: [], }; const levels = { - 'Debug': 'DBG', - 'Warning': 'WRN', - 'Error': 'ERR', - 'Information': 'INF', + Debug: 'DBG', + Error: 'ERR', + Information: 'INF', + Warning: 'WRN', }; const maxLogs = 500; @@ -23,15 +21,21 @@ const maxLogs = 500; class Logs extends Component { state = initialState; - componentDidMount = () => { + componentDidMount() { const logsHub = createLogsHubConnection(); logsHub.on('buffer', (buffer) => { - this.setState({ connected: true, logs: buffer.reverse().slice(0, maxLogs) }); + this.setState({ + connected: true, + logs: buffer.reverse().slice(0, maxLogs), + }); }); logsHub.on('log', (log) => { - this.setState({ connected: true, logs: [log].concat(this.state.logs).slice(0, maxLogs) }); + this.setState({ + connected: true, + logs: [log].concat(this.state.logs).slice(0, maxLogs), + }); }); logsHub.onreconnecting(() => this.setState({ connected: false })); @@ -39,21 +43,24 @@ class Logs extends Component { logsHub.onreconnected(() => this.setState({ connected: true })); logsHub.start(); - }; + } formatTimestamp = (timestamp) => { const date = new Date(timestamp); return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len }; - render = () => { + render() { const { connected, logs } = this.state; return ( -
- {!connected && } - {connected && - +
+ {!connected && } + {connected && ( +
Timestamp @@ -61,24 +68,27 @@ class Logs extends Component { Message - - {logs.map((log, index) => + + {logs.map((log, index) => ( {this.formatTimestamp(log.timestamp)} {levels[log.level] || log.level} - {log.message} - )} + + {log.message} + + + ))}
- } + )}
); - }; + } } -export default Logs; \ No newline at end of file +export default Logs; diff --git a/src/web/src/components/System/Options/DebugModal.jsx b/src/web/src/components/System/Options/DebugModal.jsx index 02551f1b..2a1b8c5f 100644 --- a/src/web/src/components/System/Options/DebugModal.jsx +++ b/src/web/src/components/System/Options/DebugModal.jsx @@ -1,16 +1,10 @@ -import React, { useState, useEffect } from 'react'; -import { toast } from 'react-toastify'; - -import { - Modal, - Button, - Icon, -} from 'semantic-ui-react'; - import { getCurrentDebugView } from '../../../lib/options'; import { CodeEditor, PlaceholderSegment, Switch } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { toast } from 'react-toastify'; +import { Button, Icon, Modal } from 'semantic-ui-react'; -const DebugModal = ({ open, theme, onClose }) => { +const DebugModal = ({ onClose, open, theme }) => { const [loading, setLoading] = useState(true); const [debugView, setDebugView] = useState(); @@ -32,36 +26,36 @@ const DebugModal = ({ open, theme, onClose }) => { setLoading(false); } }; - - return ( + + return ( - + Options (Debug View) - - } - > + + }> - + - ); + + ); }; -export default DebugModal; \ No newline at end of file +export default DebugModal; diff --git a/src/web/src/components/System/Options/EditModal.jsx b/src/web/src/components/System/Options/EditModal.jsx index c3f54114..f2a23e4a 100644 --- a/src/web/src/components/System/Options/EditModal.jsx +++ b/src/web/src/components/System/Options/EditModal.jsx @@ -1,18 +1,24 @@ -import React, { useState, useEffect } from 'react'; - -import { Button, Icon, Message, Modal } from 'semantic-ui-react'; -import CodeEditor from '../../Shared/CodeEditor'; - -import { getYamlLocation, getYaml, validateYaml, updateYaml } from '../../../lib/options'; import { - PlaceholderSegment, - Switch, - Div, -} from '../../Shared'; + getYaml, + getYamlLocation, + updateYaml, + validateYaml, +} from '../../../lib/options'; +import { Div, PlaceholderSegment, Switch } from '../../Shared'; +import CodeEditor from '../../Shared/CodeEditor'; +import React, { useEffect, useState } from 'react'; +import { Button, Icon, Message, Modal } from 'semantic-ui-react'; -const EditModal = ({ open, theme, onClose }) => { - const [{ loading, error }, setLoading] = useState({ loading: true, error: false }); - const [{ location, yaml, isDirty }, setYaml] = useState({ location: undefined, yaml: undefined, isDirty: false }); +const EditModal = ({ onClose, open, theme }) => { + const [{ error, loading }, setLoading] = useState({ + error: false, + loading: true, + }); + const [{ isDirty, location, yaml }, setYaml] = useState({ + isDirty: false, + location: undefined, + yaml: undefined, + }); const [yamlError, setYamlError] = useState(); const [updateError, setUpdateError] = useState(); @@ -23,20 +29,23 @@ const EditModal = ({ open, theme, onClose }) => { }, [open]); const get = async () => { - setLoading({ loading: true, error: false }); + setLoading({ error: false, loading: true }); try { - const [location, yaml] = await Promise.all([getYamlLocation(), getYaml()]); + const [location, yaml] = await Promise.all([ + getYamlLocation(), + getYaml(), + ]); - setYaml({ location, yaml, isDirty: false }); - setLoading({ loading: false, error: false }); + setYaml({ isDirty: false, location, yaml }); + setLoading({ error: false, loading: false }); } catch (error) { - setLoading({ loading: false, error: error.message }); + setLoading({ error: error.message, loading: false }); } }; const update = async (yaml) => { - setYaml({ location, yaml, isDirty: true }); + setYaml({ isDirty: true, location, yaml }); validate(yaml); }; @@ -52,8 +61,7 @@ const EditModal = ({ open, theme, onClose }) => { try { await updateYaml({ yaml }); onClose(); - } - catch (error) { + } catch (error) { setUpdateError(error.response.data); } } @@ -61,46 +69,76 @@ const EditModal = ({ open, theme, onClose }) => { return ( - + Edit Options - + } - error={error && } + error={error && } + loading={loading && } > -
update(value)} + style={{ minHeight: 500 }} theme={theme} + value={yaml} />
- {(yamlError || updateError) && - - {(yamlError ?? '') + (updateError ?? '')} - } - - + {(yamlError || updateError) && ( + + + {(yamlError ?? '') + (updateError ?? '')} + + )} + +
); }; -export default EditModal; \ No newline at end of file +export default EditModal; diff --git a/src/web/src/components/System/Options/index.jsx b/src/web/src/components/System/Options/index.jsx index cf6f49ab..9e842fc9 100644 --- a/src/web/src/components/System/Options/index.jsx +++ b/src/web/src/components/System/Options/index.jsx @@ -1,16 +1,14 @@ -import React, { useState, useEffect } from 'react'; -import YAML from 'yaml'; - -import DebugModal from './DebugModal'; -import EditModal from './EditModal'; - -import { Divider } from 'semantic-ui-react'; import { CodeEditor, LoaderSegment, ShrinkableButton, Switch, } from '../../Shared'; +import DebugModal from './DebugModal'; +import EditModal from './EditModal'; +import React, { useEffect, useState } from 'react'; +import { Divider } from 'semantic-ui-react'; +import YAML from 'yaml'; const Index = ({ options, theme }) => { const [debugModal, setDebugModal] = useState(false); @@ -19,72 +17,82 @@ const Index = ({ options, theme }) => { useEffect(() => { setTimeout(() => { - setContents(YAML.stringify(options, { simpleKeys: true, sortMapEntries: false })); + setContents( + YAML.stringify(options, { simpleKeys: true, sortMapEntries: false }), + ); }, 250); }, [options]); - - const { remoteConfiguration, debug } = options; + + const { debug, remoteConfiguration } = options; const DebugButton = ({ ...props }) => { if (!remoteConfiguration || !debug) return <>; - - return setDebugModal(true)} - {...props} - > - Debug View - ; + + return ( + setDebugModal(true)} + {...props} + > + Debug View + + ); }; const EditButton = ({ ...props }) => { if (!remoteConfiguration) { - return Remote Configuration Disabled; + return ( + + Remote Configuration Disabled + + ); } - return setEditModal(true)} - {...props} - >Edit; + return ( + setEditModal(true)} + primary + {...props} + > + Edit + + ); }; return ( <> -
- - +
+ +
- - } - > + + }> setDebugModal(false)} open={debugModal} theme={theme} - onClose={() => setDebugModal(false)} /> setEditModal(false)} open={editModal} theme={theme} - onClose={() => setEditModal(false)} /> ); }; -export default Index; \ No newline at end of file +export default Index; diff --git a/src/web/src/components/System/Shares/ContentsModal.jsx b/src/web/src/components/System/Shares/ContentsModal.jsx index f0642ef8..45030672 100644 --- a/src/web/src/components/System/Shares/ContentsModal.jsx +++ b/src/web/src/components/System/Shares/ContentsModal.jsx @@ -1,19 +1,10 @@ -import React, { useEffect, useState } from 'react'; -import { orderBy } from 'lodash'; - import { browse } from '../../../lib/shares'; +import { CodeEditor, LoaderSegment, Switch } from '../../Shared'; +import { orderBy } from 'lodash'; +import React, { useEffect, useState } from 'react'; +import { Button, Icon, Modal } from 'semantic-ui-react'; -import { - Modal, - Button, - Icon, -} from 'semantic-ui-react'; - -import { - CodeEditor, LoaderSegment, Switch, -} from '../../Shared'; - -const ContentsModal = ({ share, onClose, theme }) => { +const ContentsModal = ({ onClose, share, theme }) => { const [loading, setLoading] = useState(true); const [contents, setContents] = useState(); @@ -22,21 +13,21 @@ const ContentsModal = ({ share, onClose, theme }) => { useEffect(() => { const fetch = async () => { setLoading(true); - + const contents = await browse({ id }); - - var directories = contents.map(directory => { + + const directories = contents.map((directory) => { const lines = [directory.name.replace(remotePath, localPath)]; - - orderBy(directory.files, 'filename').forEach(file => { + + for (const file of orderBy(directory.files, 'filename')) { lines.push('\t' + file.filename.replace(remotePath, '')); - }); - + } + lines.push(''); - + return lines.join('\n'); }); - + setContents(directories.join('\n')); setLoading(false); }; @@ -51,31 +42,33 @@ const ContentsModal = ({ share, onClose, theme }) => { return ( - {localPath} - - } - > + + + {localPath} + + + }> - + ); }; -export default ContentsModal; \ No newline at end of file +export default ContentsModal; diff --git a/src/web/src/components/System/Shares/ExclusionTable.jsx b/src/web/src/components/System/Shares/ExclusionTable.jsx index 5e010e30..dc94e98d 100644 --- a/src/web/src/components/System/Shares/ExclusionTable.jsx +++ b/src/web/src/components/System/Shares/ExclusionTable.jsx @@ -1,11 +1,6 @@ -import React from 'react'; - -import { - Table, - Icon, -} from 'semantic-ui-react'; - import { Switch } from '../../Shared'; +import React from 'react'; +import { Icon, Table } from 'semantic-ui-react'; const ExclusionTable = ({ exclusions = [] } = {}) => { return ( @@ -17,19 +12,37 @@ const ExclusionTable = ({ exclusions = [] } = {}) => { - - No exclusions configured - - } + empty={ + exclusions.length === 0 && ( + + + No exclusions configured + + + ) + } > - {exclusions.map((share, index) => ( - {share.localPath} - ))} + {exclusions.map((share, index) => ( + + + + {share.localPath} + + + ))} ); }; -export default ExclusionTable; \ No newline at end of file +export default ExclusionTable; diff --git a/src/web/src/components/System/Shares/ShareTable.jsx b/src/web/src/components/System/Shares/ShareTable.jsx index eed7a148..18d0f06b 100644 --- a/src/web/src/components/System/Shares/ShareTable.jsx +++ b/src/web/src/components/System/Shares/ShareTable.jsx @@ -1,49 +1,61 @@ +import { Switch } from '../../Shared'; import React from 'react'; - -import { - Table, - Icon, -} from 'semantic-ui-react'; - import { Link } from 'react-router-dom'; -import { Switch } from '../../Shared'; +import { Icon, Table } from 'semantic-ui-react'; -const ShareTable = ({ shares, onClick }) => { +const ShareTable = ({ onClick, shares }) => { return ( Host Local Path - Directories - Files + + Directories + + + Files + Alias Remote Path - - No shares configured - - } + empty={ + shares.length === 0 && ( + + + No shares configured + + + ) + } > - {shares.map((share, index) => ( - {share.host} - onClick(share)}> - - {share.localPath} - - {share.directories ?? '?'} - {share.files ?? '?'} - {share.alias} - {share.remotePath} - ))} + {shares.map((share, index) => ( + + {share.host} + onClick(share)}> + + {share.localPath} + + {share.directories ?? '?'} + {share.files ?? '?'} + {share.alias} + {share.remotePath} + + ))}
); }; -export default ShareTable; \ No newline at end of file +export default ShareTable; diff --git a/src/web/src/components/System/Shares/index.jsx b/src/web/src/components/System/Shares/index.jsx index 3d5b1858..d629230e 100644 --- a/src/web/src/components/System/Shares/index.jsx +++ b/src/web/src/components/System/Shares/index.jsx @@ -1,21 +1,11 @@ -import React, { useState, useEffect } from 'react'; -import { toast } from 'react-toastify'; - -import * as sharesLib from '../../../lib/shares'; -import { - LoaderSegment, - ShrinkableButton, - Switch, -} from '../../Shared'; - +import * as sharesLibrary from '../../../lib/shares'; +import { LoaderSegment, ShrinkableButton, Switch } from '../../Shared'; import ContentsModal from './ContentsModal'; - -import { - Divider, -} from 'semantic-ui-react'; - import ExclusionTable from './ExclusionTable'; import ShareTable from './ShareTable'; +import React, { useEffect, useState } from 'react'; +import { toast } from 'react-toastify'; +import { Divider } from 'semantic-ui-react'; const Index = ({ state = {} } = {}) => { const [loading, setLoading] = useState(true); @@ -23,7 +13,7 @@ const Index = ({ state = {} } = {}) => { const [shares, setShares] = useState([]); const [modal, setModal] = useState(false); - const { scanning, scanProgress, scanPending, directories, files } = state; + const { directories, files, scanPending, scanProgress, scanning } = state; useEffect(() => { getAll(); @@ -33,21 +23,26 @@ const Index = ({ state = {} } = {}) => { getAll({ quiet: true }); if (!scanning) { - // the state change out of scanning can fire before + // the state change out of scanning can fire before // shares are updated, which leaves them stale. wait a second // and fetch again. - setTimeout(() => getAll({ quiet: true }), 1000); + setTimeout(() => getAll({ quiet: true }), 1_000); } - }, [scanning, scanPending]); + }, [scanPending, scanning]); const getAll = async ({ quiet } = { quiet: false }) => { try { if (!quiet) setLoading(true); - const sharesByHost = await sharesLib.getAll(); - const flattened = Object.entries(sharesByHost).reduce((acc, [host, shares]) => { - return acc.concat(shares.map(share => ({ host, ...share }))); - }, []); + const sharesByHost = await sharesLibrary.getAll(); + const flattened = Object.entries(sharesByHost).reduce( + (accumulator, [host, shares]) => { + return accumulator.concat( + shares.map((share) => ({ host, ...share })), + ); + }, + [], + ); setShares(flattened); } catch (error) { @@ -61,7 +56,7 @@ const Index = ({ state = {} } = {}) => { const rescan = async () => { try { setWorking(true); - await sharesLib.rescan(); + await sharesLibrary.rescan(); } catch (error) { console.error(error); toast.error(error?.response?.data ?? error?.message ?? error); @@ -73,63 +68,83 @@ const Index = ({ state = {} } = {}) => { const cancel = async () => { try { setWorking(true); - await sharesLib.cancel(); + await sharesLibrary.cancel(); } catch (error) { console.error(error); - toast.error(error?.response?.data ?? error?.message ?? error ?? 'Failed to cancel the scan'); + toast.error( + error?.response?.data ?? + error?.message ?? + error ?? + 'Failed to cancel the scan', + ); } finally { - setWorking(false); + setWorking(false); } }; - const ScanButton = () => rescan()} - >Rescan Shares; + const ScanButton = () => ( + rescan()} + primary={!scanPending} + > + Rescan Shares + + ); - const CancelButton = () => cancel()} - >Cancel Scan; + const CancelButton = () => ( + cancel()} + > + Cancel Scan + + ); - const shared = shares.filter(share => !share.isExcluded); - const excluded = shares.filter(share => share.isExcluded); + const shared = shares.filter((share) => !share.isExcluded); + const excluded = shares.filter((share) => share.isExcluded); return ( - <> + }> +
+ }> + + +
+ } + filling={ + scanning && ( + +
+
{Math.round(scanProgress * 100)}%
+
+ Found {files} files in {directories} directories +
+
+
+ ) + } > -
- } - > - - -
- - -
-
{Math.round(scanProgress * 100)}%
-
Found {files} files in {directories} directories
-
} - > - - -
- setModal(false)}/> + +
- + setModal(false)} + share={modal} + /> +
); }; -export default Index; \ No newline at end of file +export default Index; diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx index 2baba767..02420d9c 100644 --- a/src/web/src/components/System/System.jsx +++ b/src/web/src/components/System/System.jsx @@ -1,107 +1,161 @@ -import React from 'react'; -import { useRouteMatch, useHistory, Redirect } from 'react-router-dom'; - -import { Segment, Tab, Menu, Icon } from 'semantic-ui-react'; - import './System.css'; - import { Switch } from '../Shared'; +import Data from './Data'; +import Files from './Files'; import Info from './Info'; import Logs from './Logs'; import Options from './Options'; import Shares from './Shares'; -import Files from './Files'; -import Data from './Data'; +import React from 'react'; +import { Redirect, useHistory, useRouteMatch } from 'react-router-dom'; +import { Icon, Menu, Segment, Tab } from 'semantic-ui-react'; -const System = ({ state = {}, theme, options = {} }) => { - const { params: { tab }, ...route } = useRouteMatch(); +const System = ({ options = {}, state = {}, theme }) => { + const { + params: { tab }, + ...route + } = useRouteMatch(); const history = useHistory(); const panes = [ - { + { + menuItem: ( + + + ) + } + > + + + Info + + ), + render: () => ( + + + + ), route: 'info', - menuItem: ( - } - > - - - Info - ), - render: () => , }, { - route: 'options', - menuItem: { - key: 'options', - icon: 'options', - content: 'Options', - }, - render: () => , + menuItem: { + content: 'Options', + icon: 'options', + key: 'options', + }, + render: () => ( + + + + ), + route: 'options', }, { - route: 'shares', - menuItem: ( - } - > - - - Shares - ), - render: () => , + menuItem: ( + + + ) + } + > + + + Shares + + ), + render: () => ( + + + + ), + route: 'shares', }, { - route: 'files', menuItem: { - key: 'files', - icon: 'folder open', content: 'Files', + icon: 'folder open', + key: 'files', }, - render: () => , + render: () => ( + + + + ), + route: 'files', }, { - route: 'data', menuItem: { - key: 'data', - icon: 'database', content: 'Data', + icon: 'database', + key: 'data', }, - render: () => , + render: () => ( + + + + ), + route: 'data', }, - { - route: 'logs', - menuItem: { - key: 'logs', - icon: 'file outline', - content: 'Logs', - }, - render: () => , + { + menuItem: { + content: 'Logs', + icon: 'file outline', + key: 'logs', + }, + render: () => ( + + + + ), + route: 'logs', }, ]; - const activeIndex = panes.findIndex(pane => pane.route === tab); + const activeIndex = panes.findIndex((pane) => pane.route === tab); const onTabChange = (e, { activeIndex }) => { history.push(panes[activeIndex].route); }; if (tab === undefined) { - return ; + return ; } return ( -
+
-1 ? activeIndex : 0} - panes={panes} + activeIndex={activeIndex > -1 ? activeIndex : 0} onTabChange={onTabChange} + panes={panes} />
); }; -export default System; \ No newline at end of file +export default System; diff --git a/src/web/src/components/Transfers/TransferGroup.jsx b/src/web/src/components/Transfers/TransferGroup.jsx index ad4ab969..4f2dbb7c 100644 --- a/src/web/src/components/Transfers/TransferGroup.jsx +++ b/src/web/src/components/Transfers/TransferGroup.jsx @@ -1,48 +1,49 @@ -import React, { Component } from 'react'; import * as transfers from '../../lib/transfers'; - -import { - Card, - Button, - Icon, -} from 'semantic-ui-react'; - import TransferList from './TransferList'; +import React, { Component } from 'react'; +import { Button, Card, Icon } from 'semantic-ui-react'; class TransferGroup extends Component { state = { - selections: new Set(), isFolded: false, + selections: new Set(), }; onSelectionChange = (directoryName, file, selected) => { - const {selections} = this.state; - const obj = JSON.stringify({ directory: directoryName, filename: file.filename }); - selected ? selections.add(obj) : selections.delete(obj); + const { selections } = this.state; + const object = JSON.stringify({ + directory: directoryName, + filename: file.filename, + }); + selected ? selections.add(object) : selections.delete(object); this.setState({ selections }); }; - isSelected = (directoryName, file) => - this.state.selections.has(JSON.stringify({ directory: directoryName, filename: file.filename })); + isSelected = (directoryName, file) => + this.state.selections.has( + JSON.stringify({ directory: directoryName, filename: file.filename }), + ); getSelectedFiles = () => { const { user } = this.props; - + return Array.from(this.state.selections) - .map(s => JSON.parse(s)) - .map(s => user.directories - .find(d => d.directory === s.directory) - .files.find(f => f.filename === s.filename) - ).filter(s => s !== undefined); + .map((s) => JSON.parse(s)) + .map((s) => + user.directories + .find((d) => d.directory === s.directory) + .files.find((f) => f.filename === s.filename), + ) + .filter((s) => s !== undefined); }; removeFileSelection = (file) => { - const {selections} = this.state; + const { selections } = this.state; const match = Array.from(selections) - .map(s => JSON.parse(s)) - .find(s => s.filename === file.filename); + .map((s) => JSON.parse(s)) + .find((s) => s.filename === file.filename); if (match) { selections.delete(JSON.stringify(match)); @@ -51,56 +52,74 @@ class TransferGroup extends Component { }; retryAll = async (selected) => { - await Promise.all(selected.map(file => this.retry(file))); + await Promise.all(selected.map((file) => this.retry(file))); }; cancelAll = async (direction, username, selected) => { - await Promise.all(selected.map(file => transfers.cancel({ direction, username, id: file.id}))); + await Promise.all( + selected.map((file) => + transfers.cancel({ direction, id: file.id, username }), + ), + ); }; removeAll = async (direction, username, selected) => { - await Promise.all(selected.map(file => - transfers.cancel({ direction, username, id: file.id, remove: true }) - .then(() => this.removeFileSelection(file)))); + await Promise.all( + selected.map((file) => + transfers + .cancel({ direction, id: file.id, remove: true, username }) + .then(() => this.removeFileSelection(file)), + ), + ); }; retry = async (file) => { - const { username, filename, size } = file; - + const { filename, size, username } = file; + try { - await transfers.download({username, files: [{filename, size }] }); + await transfers.download({ files: [{ filename, size }], username }); } catch (error) { console.error(error); } }; fetchPlaceInQueue = async (file) => { - const { username, id } = file; + const { id, username } = file; try { - await transfers.getPlaceInQueue({ username, id }); + await transfers.getPlaceInQueue({ id, username }); } catch (error) { console.error(error); } }; toggleFolded = () => { - this.setState({'isFolded': !this.state.isFolded}); + this.setState({ isFolded: !this.state.isFolded }); }; - render = () => { - const { user, direction } = this.props; - const {isFolded} = this.state; + render() { + const { direction, user } = this.props; + const { isFolded } = this.state; const selected = this.getSelectedFiles(); const all = selected.length > 1 ? ' Selected' : ''; - - const allRetryable = selected.filter(f => transfers.isStateRetryable(f.state)).length === selected.length; - const anyCancellable = selected.filter(f => transfers.isStateCancellable(f.state)).length > 0; - const allRemovable = selected.filter(f => transfers.isStateRemovable(f.state)).length === selected.length; + + const allRetryable = + selected.filter((f) => transfers.isStateRetryable(f.state)).length === + selected.length; + const anyCancellable = selected.some((f) => + transfers.isStateCancellable(f.state), + ); + const allRemovable = + selected.filter((f) => transfers.isStateRemovable(f.state)).length === + selected.length; return ( - + {user.username} - {user.directories && !isFolded && user.directories - .map((dir, index) => - ({ ...f, selected: this.isSelected(dir.directory, f) }))} - onSelectionChange={this.onSelectionChange} + {user.directories && + !isFolded && + user.directories.map((dir, index) => ( + ({ + ...f, + selected: this.isSelected(dir.directory, f), + }))} + key={index} onPlaceInQueueRequested={this.fetchPlaceInQueue} onRetryRequested={this.retry} + onSelectionChange={this.onSelectionChange} + username={user.username} /> - )} + ))} - {selected && selected.length > 0 && - - { - {allRetryable && -