diff options
Diffstat (limited to 'src')
45 files changed, 868 insertions, 676 deletions
diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index cb906871..83997b20 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -41,21 +41,111 @@ const initialState = { retriesExhausted: false, }; +const ModeSpecificConnectButton = ({ + controller = {}, + mode, + pendingReconnect, + server, + user, +}) => { + if (mode === 'Agent') { + const isConnected = controller?.state === 'Connected'; + const isTransitioning = ['Connecting', 'Reconnecting'].includes( + controller?.state, + ); + + return ( + <Menu.Item + onClick={() => + isConnected ? relayAPI.disconnect() : relayAPI.connect() + } + > + <Icon.Group className="menu-icon-group"> + <Icon + color={ + controller?.state === 'Connected' + ? 'green' + : isTransitioning + ? 'yellow' + : 'grey' + } + name="plug" + /> + {!isConnected && ( + <Icon + className="menu-icon-no-shadow" + color="red" + corner="bottom right" + name="close" + /> + )} + </Icon.Group> + Controller {controller?.state} + </Menu.Item> + ); + } else { + return ( + <> + {server?.isConnected && ( + <Menu.Item onClick={() => disconnect()}> + <Icon.Group className="menu-icon-group"> + <Icon + color={pendingReconnect ? 'yellow' : 'green'} + name="plug" + /> + {user?.privileges?.isPrivileged && ( + <Icon + className="menu-icon-no-shadow" + color="yellow" + corner + name="star" + /> + )} + </Icon.Group> + Connected + </Menu.Item> + )} + {!server?.isConnected && ( + <Menu.Item onClick={() => connect()}> + <Icon.Group className="menu-icon-group"> + <Icon + color="grey" + name="plug" + /> + <Icon + className="menu-icon-no-shadow" + color="red" + corner="bottom right" + name="close" + /> + </Icon.Group> + Disconnected + </Menu.Item> + )} + </> + ); + } +}; + class App extends Component { - state = initialState; + constructor(props) { + super(props); + + this.state = initialState; + } componentDidMount() { window .matchMedia('(prefers-color-scheme: dark)') .addEventListener( 'change', - (e) => e.matches && this.setState({ theme: 'dark' }), + (event) => event.matches && this.setState({ theme: 'dark' }), ); window .matchMedia('(prefers-color-scheme: light)') .addEventListener( 'change', - (e) => e.matches && this.setState({ theme: 'light' }), + (event) => event.matches && this.setState({ theme: 'light' }), ); this.init(); } @@ -106,20 +196,24 @@ class App extends Component { }); }; - login = (username, password, rememberMe) => { + handleLogin = (username, password, rememberMe) => { this.setState( - { login: { ...this.state.login, error: undefined, pending: true } }, + (previousState) => ({ + login: { ...previousState.login, error: undefined, pending: true }, + }), async () => { try { await session.login({ password, rememberMe, username }); this.setState( - { login: { ...this.state.login, error: false, pending: false } }, + (previousState) => ({ + login: { ...previousState.login, error: false, pending: false }, + }), () => this.init(), ); } catch (error) { - this.setState({ - login: { ...this.state.login, error, pending: false }, - }); + this.setState((previousState) => ({ + login: { ...previousState.login, error, pending: false }, + })); } }, ); @@ -194,91 +288,11 @@ class App extends Component { error={login.error} initialized={login.initialized} loading={login.pending} - onLoginAttempt={this.login} + onLoginAttempt={this.handleLogin} /> ); } - const ModeSpecificConnectButton = ({ controller = {}, mode, server }) => { - if (mode === 'Agent') { - const isConnected = controller?.state === 'Connected'; - const isTransitioning = ['Connecting', 'Reconnecting'].includes( - controller?.state, - ); - - return ( - <Menu.Item - onClick={() => - isConnected ? relayAPI.disconnect() : relayAPI.connect() - } - > - <Icon.Group className="menu-icon-group"> - <Icon - color={ - controller?.state === 'Connected' - ? 'green' - : isTransitioning - ? 'yellow' - : 'grey' - } - name="plug" - /> - {!isConnected && ( - <Icon - className="menu-icon-no-shadow" - color="red" - corner="bottom right" - name="close" - /> - )} - </Icon.Group> - Controller {controller?.state} - </Menu.Item> - ); - } else { - return ( - <> - {server?.isConnected && ( - <Menu.Item onClick={() => disconnect()}> - <Icon.Group className="menu-icon-group"> - <Icon - color={pendingReconnect ? 'yellow' : 'green'} - name="plug" - /> - {user?.privileges?.isPrivileged && ( - <Icon - className="menu-icon-no-shadow" - color="yellow" - corner - name="star" - /> - )} - </Icon.Group> - Connected - </Menu.Item> - )} - {!server?.isConnected && ( - <Menu.Item onClick={() => connect()}> - <Icon.Group className="menu-icon-group"> - <Icon - color="grey" - name="plug" - /> - <Icon - className="menu-icon-no-shadow" - color="red" - corner="bottom right" - name="close" - /> - </Icon.Group> - Disconnected - </Menu.Item> - )} - </> - ); - } - }; - const isAgent = mode === 'Agent'; if (theme === 'dark') { @@ -379,7 +393,9 @@ class App extends Component { <ModeSpecificConnectButton controller={controller} mode={mode} + pendingReconnect={pendingReconnect} server={server} + user={user} /> {(pendingReconnect || pendingRestart || pendingShareRescan) && ( <Menu.Item position="right"> @@ -469,6 +485,8 @@ class App extends Component { </Sidebar> <Sidebar.Pusher className="app-content"> <AppContext.Provider + // TODO: needs useMemo, but class component. yolo for now. + // eslint-disable-next-line react/jsx-no-constructed-context-values value={{ options: applicationOptions, state: applicationState }} > {isAgent ? ( diff --git a/src/web/src/components/Browse/Browse.jsx b/src/web/src/components/Browse/Browse.jsx index 412dd7e2..75c8fb53 100644 --- a/src/web/src/components/Browse/Browse.jsx +++ b/src/web/src/components/Browse/Browse.jsx @@ -1,3 +1,4 @@ +/* eslint-disable promise/prefer-await-to-then */ import './Browse.css'; import * as users from '../../lib/users'; import PlaceholderSegment from '../Shared/PlaceholderSegment'; @@ -26,7 +27,30 @@ const initialState = { }; class Browse extends Component { - state = initialState; + constructor(props) { + super(props); + + this.state = initialState; + } + + componentDidMount() { + this.fetchStatus(); + this.loadState(); + this.setState( + { + interval: window.setInterval(this.fetchStatus, 500), + }, + () => this.saveState(), + ); + + document.addEventListener('keyup', this.keyUp, false); + } + + componentWillUnmount() { + clearInterval(this.state.interval); + this.setState({ interval: undefined }); + document.removeEventListener('keyup', this.keyUp, false); + } browse = () => { const username = this.inputtext.inputRef.current.value; @@ -37,25 +61,26 @@ class Browse extends Component { users .browse({ username }) .then((response) => { - let { directories, lockedDirectories } = response; + let { directories } = response; + const { 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) => { + const fileCount = directories.reduce((accumulator, directory) => { // 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 = '/'; + if (directory.name.includes('\\')) separator = '\\'; + else if (directory.name.includes('/')) separator = '/'; } - return (accumulator += dir.fileCount); + return accumulator + directory.fileCount; }, 0); const lockedDirectoryCount = lockedDirectories.length; const lockedFileCount = lockedDirectories.reduce( - (accumulator, dir) => (accumulator += dir.fileCount), + (accumulator, directory) => accumulator + directory.fileCount, 0, ); @@ -98,10 +123,6 @@ class Browse extends Component { keyUp = (event) => (event.key === 'Escape' ? this.clear() : ''); - onUsernameChange = (event, data) => { - this.setState({ username: data.value }); - }; - saveState = () => { this.inputtext.inputRef.current.value = this.state.username; this.inputtext.inputRef.current.disabled = @@ -137,25 +158,6 @@ class Browse extends Component { ); }; - componentDidMount() { - this.fetchStatus(); - this.loadState(); - this.setState( - { - interval: window.setInterval(this.fetchStatus, 500), - }, - () => this.saveState(), - ); - - document.addEventListener('keyup', this.keyUp, false); - } - - componentWillUnmount() { - clearInterval(this.state.interval); - this.setState({ interval: undefined }); - document.removeEventListener('keyup', this.keyUp, false); - } - fetchStatus = () => { const { browseState, username } = this.state; if (browseState === 'pending') { @@ -178,15 +180,15 @@ class Browse extends Component { // - future look ups are done from the Map const depthMap = new Map(); for (const d of directories) { - const depth = d.name.split(separator).length; - if (!depthMap.has(depth)) { - depthMap.set(depth, []); + const directoryDepth = d.name.split(separator).length; + if (!depthMap.has(directoryDepth)) { + depthMap.set(directoryDepth, []); } - depthMap.get(depth).push(d); + depthMap.get(directoryDepth).push(d); } - const depth = Math.min.apply(Math, Array.from(depthMap.keys())); + const depth = Math.min(...Array.from(depthMap.keys())); return depthMap .get(depth) @@ -218,7 +220,7 @@ class Browse extends Component { ); }; - deselectDirectory = () => { + handleDeselectDirectory = () => { this.setState({ selectedDirectory: initialState.selectedDirectory }, () => this.saveState(), ); @@ -274,7 +276,7 @@ class Browse extends Component { /> } loading={pending} - onKeyUp={(e) => (e.key === 'Enter' ? this.browse() : '')} + onKeyUp={(event) => (event.key === 'Enter' ? this.browse() : '')} placeholder="Username" ref={(input) => (this.inputtext = input)} size="big" @@ -336,7 +338,7 @@ class Browse extends Component { locked={locked} marginTop={-20} name={name} - onClose={this.deselectDirectory} + onClose={this.handleDeselectDirectory} username={username} /> )} diff --git a/src/web/src/components/Browse/Directory.jsx b/src/web/src/components/Browse/Directory.jsx index 891db608..ed88f131 100644 --- a/src/web/src/components/Browse/Directory.jsx +++ b/src/web/src/components/Browse/Directory.jsx @@ -10,18 +10,30 @@ const initialState = { }; class Directory extends Component { - state = { - ...initialState, - files: this.props.files.map((f) => ({ selected: false, ...f })), - }; + constructor(props) { + super(props); + + this.state = { + ...initialState, + 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 })), + }); + } + } - onFileSelectionChange = (file, state) => { + handleFileSelectionChange = (file, state) => { file.selected = state; - this.setState({ + this.setState((previousState) => ({ downloadError: '', downloadRequest: undefined, - tree: this.state.tree, - }); + tree: previousState.tree, + })); }; download = (username, files) => { @@ -43,14 +55,6 @@ class Directory extends Component { }); }; - componentDidUpdate(previousProps) { - if (this.props.name !== previousProps.name) { - this.setState({ - files: this.props.files.map((f) => ({ selected: false, ...f })), - }); - } - } - render() { const { locked, marginTop, name, onClose, username } = this.props; const { downloadError, downloadRequest, files } = this.state; @@ -74,7 +78,7 @@ class Directory extends Component { files={files} locked={locked} onClose={onClose} - onSelectionChange={this.onFileSelectionChange} + onSelectionChange={this.handleFileSelectionChange} /> </div> </Card.Content> diff --git a/src/web/src/components/Browse/DirectoryTree.jsx b/src/web/src/components/Browse/DirectoryTree.jsx index af90ad5a..2c10ca0f 100644 --- a/src/web/src/components/Browse/DirectoryTree.jsx +++ b/src/web/src/components/Browse/DirectoryTree.jsx @@ -2,14 +2,14 @@ import React from 'react'; import { List } from 'semantic-ui-react'; const subtree = (root, selectedDirectoryName, onSelect) => { - return (root || []).map((d, index) => { + return (root || []).map((d) => { const selected = d.name === selectedDirectoryName; // const dimIfLocked = { opacity: d.locked ? 0.5 : 1 }; return ( <List className="browse-folderlist-list" - key={index} + key={d.name} > <List.Item> <List.Icon diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index b071ed55..23619bd1 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -23,11 +23,11 @@ const initialState = { }; class Chat extends Component { - state = initialState; + constructor(props) { + super(props); - messageRef = undefined; - - listRef = createRef(); + this.state = initialState; + } componentDidMount() { this.setState( @@ -49,6 +49,10 @@ class Chat extends Component { this.setState({ interval: undefined }); } + listRef = createRef(); + + messageRef = undefined; + getFirstConversation = () => { const names = Object.keys(this.state.conversations); return names.length > 0 ? names[0] : ''; @@ -218,7 +222,7 @@ class Chat extends Component { onConversationChange={(name) => this.selectConversation(name)} /> </Segment> - {!active ? ( + {Boolean(active) === false ? ( <PlaceholderSegment caption="No chats to display" icon="comment" @@ -256,10 +260,10 @@ class Chat extends Component { <Segment className="chat-history"> <Ref innerRef={this.listRef}> <List> - {messages.map((message, index) => ( + {messages.map((message) => ( <List.Content className={`chat-message ${message.direction === 'Out' ? 'chat-message-self' : ''}`} - key={index} + key={`${message.timestamp}+${message.message}`} > <span className="chat-message-time"> {this.formatTimestamp(message.timestamp)} @@ -301,8 +305,8 @@ class Chat extends Component { type="text" /> } - onKeyUp={(e) => - e.key === 'Enter' ? this.sendReply() : '' + onKeyUp={(event) => + event.key === 'Enter' ? this.sendReply() : '' } ref={(input) => (this.messageRef = input && input.inputRef) diff --git a/src/web/src/components/Chat/ChatMenu.jsx b/src/web/src/components/Chat/ChatMenu.jsx index 8317605c..41393543 100644 --- a/src/web/src/components/Chat/ChatMenu.jsx +++ b/src/web/src/components/Chat/ChatMenu.jsx @@ -12,11 +12,11 @@ const ChatMenu = ({ active, conversations, onConversationChange, ...rest }) => { className="conversation-menu" size="large" > - {names.map((name, index) => ( + {names.map((name) => ( <Menu.Item active={isActive(name)} className={`menu-item ${isActive(name) ? 'menu-active' : ''}`} - key={index} + key={name} name={name} onClick={() => onConversationChange(name)} > diff --git a/src/web/src/components/Chat/SendMessageModal.jsx b/src/web/src/components/Chat/SendMessageModal.jsx index 8effb05e..203b2d06 100644 --- a/src/web/src/components/Chat/SendMessageModal.jsx +++ b/src/web/src/components/Chat/SendMessageModal.jsx @@ -15,6 +15,10 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => { } }, [open]); + const validInput = () => { + return username.length > 0 && message.length > 0; + }; + const sendMessage = async () => { if (!validInput()) { usernameRef.current.focus(); @@ -25,10 +29,6 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => { setOpen(false); }; - const validInput = () => { - return username.length > 0 && message.length > 0; - }; - return ( <Modal onClose={() => setOpen(false)} @@ -44,14 +44,14 @@ const SendMessageModal = ({ initiateConversation, ...rest }) => { <Form> <Form.Field> <Input - onChange={(e, data) => setUsername(data.value)} + onChange={(_event, data) => setUsername(data.value)} placeholder="Username" ref={usernameRef} /> </Form.Field> <Form.Field> <Input - onChange={(e, data) => setMessage(data.value)} + onChange={(_event, data) => setMessage(data.value)} placeholder="Message" /> </Form.Field> diff --git a/src/web/src/components/Rooms/RoomJoinModal.jsx b/src/web/src/components/Rooms/RoomJoinModal.jsx index 34e3dd78..39c46248 100644 --- a/src/web/src/components/Rooms/RoomJoinModal.jsx +++ b/src/web/src/components/Rooms/RoomJoinModal.jsx @@ -24,8 +24,8 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { useEffect(() => { const getAvailableRooms = async () => { setLoading(true); - const available = await rooms.getAvailable(); - setAvailable(available); + const availableResult = await rooms.getAvailable(); + setAvailable(availableResult); setLoading(false); }; @@ -54,13 +54,6 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { return sorted; }, [available, filter, sortBy, sortOrder]); - const joinRoom = async () => { - await parentJoinRoom(selected); - close(); - }; - - const isSelected = (room) => selected === room.name; - const close = () => { setAvailable([]); setSelected(undefined); @@ -70,6 +63,13 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { setOpen(false); }; + const joinRoom = async () => { + await parentJoinRoom(selected); + close(); + }; + + const isSelected = (room) => selected === room.name; + return ( <Modal className="join-room-modal" @@ -98,7 +98,7 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { <Input fluid icon="filter" - onChange={(_, e) => setFilter(e.value)} + onChange={(_, event) => setFilter(event.value)} placeholder="Room Filter" /> <Table @@ -136,9 +136,9 @@ const RoomJoinModal = ({ joinRoom: parentJoinRoom, ...modalOptions }) => { </Table.Row> </Table.Header> <Table.Body> - {sortedAvailable.map((room, index) => ( + {sortedAvailable.map((room) => ( <Table.Row - key={index} + key={room.name} onClick={() => setSelected(room.name)} style={isSelected(room) ? { fontWeight: 'bold' } : {}} > diff --git a/src/web/src/components/Rooms/RoomMenu.jsx b/src/web/src/components/Rooms/RoomMenu.jsx index d76afdaa..7198c943 100644 --- a/src/web/src/components/Rooms/RoomMenu.jsx +++ b/src/web/src/components/Rooms/RoomMenu.jsx @@ -12,11 +12,11 @@ const RoomMenu = ({ active, joined, onRoomChange, ...rest }) => { className="room-menu" size="large" > - {names.map((name, index) => ( + {names.map((name) => ( <Menu.Item active={isActive(name)} className={`menu-item ${isActive(name) ? 'menu-active' : ''}`} - key={index} + key={name} name={name} onClick={() => onRoomChange(name)} > diff --git a/src/web/src/components/Rooms/RoomUserList.jsx b/src/web/src/components/Rooms/RoomUserList.jsx index fc37625b..7ce38ee6 100644 --- a/src/web/src/components/Rooms/RoomUserList.jsx +++ b/src/web/src/components/Rooms/RoomUserList.jsx @@ -2,6 +2,10 @@ import './Rooms.css'; import React, { useMemo } from 'react'; import { Flag, Icon, List, Popup } from 'semantic-ui-react'; +const getDetails = (user) => { + return user.countryCode ?? '?'; +}; + const RoomUserList = ({ users }) => { const getFlag = (user) => { if (!(user || {}).countryCode) @@ -15,10 +19,6 @@ const RoomUserList = ({ users }) => { return <Flag name={user.countryCode.toLowerCase()} />; }; - const getDetails = (user) => { - return user.countryCode || '?'; - }; - const sortedUsers = useMemo(() => { const filtered = [...users] .sort((a, b) => a.username.localeCompare(b.username)) @@ -38,10 +38,10 @@ const RoomUserList = ({ users }) => { return ( <List> - {sortedUsers.map((user, index) => ( + {sortedUsers.map((user) => ( <List.Item className={user.self ? 'room-user-self' : ''} - key={index} + key={user.username} > <List.Content style={{ opacity: user.status === 'Online' ? 1 : 0.5 }}> <Popup diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index e4d17d7c..002ecde3 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -30,11 +30,11 @@ const initialState = { }; class Rooms extends Component { - state = initialState; + constructor(props) { + super(props); - messageRef = undefined; - - listRef = createRef(); + this.state = initialState; + } componentDidMount() { this.setState( @@ -53,14 +53,19 @@ class Rooms extends Component { } componentWillUnmount() { - const { messages, rooms } = this.state.intervals; + const { messages: messagesInterval, rooms: roomsInterval } = + this.state.intervals; - clearInterval(rooms); - clearInterval(messages); + clearInterval(roomsInterval); + clearInterval(messagesInterval); this.setState({ intervals: initialState.intervals }); } + listRef = createRef(); + + messageRef = undefined; + getFirstRoom = () => { return this.state.joined.length > 0 ? this.state.joined[0] : ''; }; @@ -190,7 +195,7 @@ class Rooms extends Component { onRoomChange={(name) => this.selectRoom(name)} /> </Segment> - {!active ? ( + {active == null ? ( <PlaceholderSegment caption="No rooms to display" icon="comments" @@ -229,10 +234,10 @@ class Rooms extends Component { <Segment className="room-history"> <Ref innerRef={this.listRef}> <List> - {room.messages.map((message, index) => ( + {room.messages.map((message) => ( <List.Content className={`room-message ${message.self ? 'room-message-self' : ''}`} - key={index} + key={`${message.timestamp}+${message.message}`} > <span className="room-message-time"> {this.formatTimestamp(message.timestamp)} @@ -271,8 +276,8 @@ class Rooms extends Component { type="text" /> } - onKeyUp={(e) => - e.key === 'Enter' ? this.sendMessage() : '' + onKeyUp={(event) => + event.key === 'Enter' ? this.sendMessage() : '' } ref={(input) => (this.messageRef = input && input.inputRef) diff --git a/src/web/src/components/Search/Detail/SearchDetail.jsx b/src/web/src/components/Search/Detail/SearchDetail.jsx index 488affc3..1ec53849 100644 --- a/src/web/src/components/Search/Detail/SearchDetail.jsx +++ b/src/web/src/components/Search/Detail/SearchDetail.jsx @@ -66,8 +66,8 @@ const SearchDetail = ({ const responses = await getResponses({ id }); setResults(responses); setLoading(false); - } catch (error) { - setError(error); + } catch (getError) { + setError(getError); setLoading(false); } }; @@ -127,9 +127,9 @@ const SearchDetail = ({ setDisplayCount(5); }; - const create = async ({ navigate, search }) => { + const create = async ({ navigate, search: searchForCreate }) => { reset(); - onCreate({ navigate, search }); + onCreate({ navigate, searchForCreate }); }; const remove = async () => { @@ -186,7 +186,7 @@ const SearchDetail = ({ floating icon="sort" labeled - onChange={(e, { value }) => setResultSort(value)} + onChange={(_event, { value }) => setResultSort(value)} options={sortDropdownOptions} text={ sortDropdownOptions.find((o) => o.value === resultSort).text @@ -225,7 +225,7 @@ const SearchDetail = ({ } className="search-filter" label={{ content: 'Filter', icon: 'filter' }} - onChange={(e, data) => setResultFilters(data.value)} + onChange={(_event, data) => setResultFilters(data.value)} placeholder=" lackluster container -bothersome iscbr|isvbr islossless|islossy minbitrate:320 minbitdepth:24 minfilesize:10 minfilesinfolder:8 minlength:5000 @@ -235,11 +235,11 @@ const SearchDetail = ({ </Segment> )} {loaded && - sortedAndFilteredResults.slice(0, displayCount).map((r, index) => ( + sortedAndFilteredResults.slice(0, displayCount).map((r) => ( <Response disabled={disabled} isInitiallyFolded={foldResults} - key={index} + key={r.username} onHide={() => setHiddenResults([...hiddenResults, r.username])} response={r} /> diff --git a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx index 25c5789b..c117e271 100644 --- a/src/web/src/components/Search/Detail/SearchDetailHeader.jsx +++ b/src/web/src/components/Search/Detail/SearchDetailHeader.jsx @@ -3,6 +3,52 @@ import React from 'react'; import { useMediaQuery } from 'react-responsive'; import { Button, Header, Icon, Segment } from 'semantic-ui-react'; +const RefreshButton = ({ + creating, + disabled, + isSmallScreen, + isTinyScreen, + loaded, + onCreate, + searchText, + working, +}) => + loaded && ( + <Button + disabled={disabled || working} + icon={isSmallScreen && !isTinyScreen} + loading={creating} + onClick={() => onCreate({ navigate: true, search: searchText })} + > + <Icon name="refresh" /> + {(!isSmallScreen || isTinyScreen) && 'Search Again'} + </Button> + ); + +const StopOrDeleteButton = ({ + isComplete, + isSmallScreen, + isTinyScreen, + loaded, + removing, + stopOrRemove, + stopping, + working, +}) => ( + <Button + disabled={working} + floated={isTinyScreen ? 'right' : undefined} + icon={isSmallScreen && !isTinyScreen} + loading={removing || stopping} + negative + onClick={stopOrRemove} + > + <Icon name={isComplete ? 'trash alternate' : 'stop circle'} /> + {(!isSmallScreen || isTinyScreen) && + (loaded && isComplete ? 'Delete' : 'Stop')} + </Button> +); + const SearchDetailHeader = ({ creating, disabled, @@ -29,34 +75,6 @@ const SearchDetailHeader = ({ } }; - const RefreshButton = () => - loaded && ( - <Button - disabled={disabled || working} - icon={isSmallScreen && !isTinyScreen} - loading={creating} - onClick={() => onCreate({ navigate: true, search: searchText })} - > - <Icon name="refresh" /> - {(!isSmallScreen || isTinyScreen) && 'Search Again'} - </Button> - ); - - const StopOrDeleteButton = () => ( - <Button - disabled={working} - floated={isTinyScreen ? 'right' : undefined} - icon={isSmallScreen && !isTinyScreen} - loading={removing || stopping} - negative - onClick={stopOrRemove} - > - <Icon name={isComplete ? 'trash alternate' : 'stop circle'} /> - {(!isSmallScreen || isTinyScreen) && - (loaded && isComplete ? 'Delete' : 'Stop')} - </Button> - ); - // 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. @@ -72,15 +90,51 @@ const SearchDetailHeader = ({ </Header> {!isTinyScreen && ( <div className="search-detail-header-buttons"> - <RefreshButton /> - <StopOrDeleteButton /> + <RefreshButton + creating={creating} + disabled={disabled} + isSmallScreen={isSmallScreen} + isTinyScreen={isTinyScreen} + loaded={loaded} + onCreate={onCreate} + searchText={searchText} + working={working} + /> + <StopOrDeleteButton + isComplete={isComplete} + isSmallScreen={isSmallScreen} + isTinyScreen={isTinyScreen} + loaded={loaded} + removing={removing} + stopOrRemove={stopOrRemove} + stopping={stopping} + working={working} + /> </div> )} </Segment> {isTinyScreen && ( <Segment> - <RefreshButton /> - <StopOrDeleteButton /> + <RefreshButton + creating={creating} + disabled={disabled} + isSmallScreen={isSmallScreen} + isTinyScreen={isTinyScreen} + loaded={loaded} + onCreate={onCreate} + searchText={searchText} + working={working} + /> + <StopOrDeleteButton + isComplete={isComplete} + isSmallScreen={isSmallScreen} + isTinyScreen={isTinyScreen} + loaded={loaded} + removing={removing} + stopOrRemove={stopOrRemove} + stopping={stopping} + working={working} + /> </Segment> )} </> diff --git a/src/web/src/components/Search/List/SearchList.jsx b/src/web/src/components/Search/List/SearchList.jsx index e5843972..1f704423 100644 --- a/src/web/src/components/Search/List/SearchList.jsx +++ b/src/web/src/components/Search/List/SearchList.jsx @@ -60,9 +60,9 @@ const SearchList = ({ <Table.Body> {Object.values(searches) .sort((a, b) => new Date(b.startedAt) - new Date(a.startedAt)) - .map((search, index) => ( + .map((search) => ( <SearchListRow - key={index} + key={search.id} onRemove={onRemove} onStop={onStop} search={search} diff --git a/src/web/src/components/Search/Response.jsx b/src/web/src/components/Search/Response.jsx index ce857bf3..40029b0c 100644 --- a/src/web/src/components/Search/Response.jsx +++ b/src/web/src/components/Search/Response.jsx @@ -7,26 +7,33 @@ import { toast } from 'react-toastify'; import { Button, Card, Icon, Label } from 'semantic-ui-react'; const buildTree = (response) => { - let { files = [], lockedFiles = [] } = response; + let { files = [] } = response; + const { lockedFiles = [] } = response; files = files.concat(lockedFiles.map((file) => ({ ...file, locked: true }))); return files.reduce((dict, file) => { - const dir = getDirectoryName(file.filename); + const directory = getDirectoryName(file.filename); const selectable = { selected: false, ...file }; - dict[dir] = - dict[dir] === undefined ? [selectable] : dict[dir].concat(selectable); + dict[directory] = + dict[directory] === undefined + ? [selectable] + : dict[directory].concat(selectable); return dict; }, {}); }; class Response extends Component { - state = { - downloadError: '', - downloadRequest: undefined, - fetchingDirectoryContents: false, - isFolded: this.props.isInitiallyFolded, - tree: buildTree(this.props.response), - }; + constructor(props) { + super(props); + + this.state = { + downloadError: '', + downloadRequest: undefined, + fetchingDirectoryContents: false, + isFolded: this.props.isInitiallyFolded, + tree: buildTree(this.props.response), + }; + } componentDidUpdate(previousProps) { if ( @@ -41,13 +48,13 @@ class Response extends Component { } } - onFileSelectionChange = (file, state) => { + handleFileSelectionChange = (file, state) => { file.selected = state; - this.setState({ + this.setState((previousState) => ({ downloadError: '', downloadRequest: undefined, - tree: this.state.tree, - }); + tree: previousState.tree, + })); }; download = (username, files) => { @@ -102,8 +109,8 @@ class Response extends Component { } }; - toggleFolded = () => { - this.setState({ isFolded: !this.state.isFolded }); + handleToggleFolded = () => { + this.setState((previousState) => ({ isFolded: !previousState.isFolded })); }; render() { @@ -136,7 +143,7 @@ class Response extends Component { <Icon link name={isFolded ? 'chevron right' : 'chevron down'} - onClick={this.toggleFolded} + onClick={this.handleToggleFolded} /> <Icon color={free ? 'green' : 'yellow'} @@ -157,21 +164,24 @@ class Response extends Component { Slot: {free ? 'YES' : 'NO'}, Queue Length: {response.queueLength} </span> </Card.Meta> - {((!isFolded && Object.keys(tree)) || []).map((dir, index) => ( + {((!isFolded && Object.keys(tree)) || []).map((directory) => ( <FileList - directoryName={dir} + directoryName={directory} disabled={downloadRequest === 'inProgress'} - files={tree[dir]} + files={tree[directory]} footer={ <button disabled={fetchingDirectoryContents} - onClick={() => this.getFullDirectory(response.username, dir)} + onClick={() => + this.getFullDirectory(response.username, directory) + } style={{ backgroundColor: 'transparent', border: 'none', cursor: 'pointer', width: '100%', }} + type="button" > <Icon loading={fetchingDirectoryContents} @@ -180,9 +190,9 @@ class Response extends Component { Get Full Directory Contents </button> } - key={index} - locked={tree[dir].find((file) => file.locked)} - onSelectionChange={this.onFileSelectionChange} + key={directory} + locked={tree[directory].find((file) => file.locked)} + onSelectionChange={this.handleFileSelectionChange} /> ))} </Card.Content> diff --git a/src/web/src/components/Search/Searches.jsx b/src/web/src/components/Search/Searches.jsx index b7c67bf1..471f833d 100644 --- a/src/web/src/components/Search/Searches.jsx +++ b/src/web/src/components/Search/Searches.jsx @@ -36,9 +36,9 @@ const Searches = ({ server } = {}) => { setError(undefined); }; - const onConnectionError = (error) => { + const onConnectionError = (connectionError) => { setConnecting(false); - setError(error); + setError(connectionError); }; const onUpdate = (update) => { @@ -51,9 +51,9 @@ const Searches = ({ server } = {}) => { const searchHub = createSearchHubConnection(); - searchHub.on('list', (searches) => { + searchHub.on('list', (searchesEvent) => { onUpdate( - searches.reduce((accumulator, search) => { + searchesEvent.reduce((accumulator, search) => { accumulator[search.id] = search; return accumulator; }, {}), @@ -74,21 +74,21 @@ const Searches = ({ server } = {}) => { searchHub.on('create', () => {}); - searchHub.onreconnecting((error) => - onConnectionError(error?.message ?? 'Disconnected'), + searchHub.onreconnecting((connectionError) => + onConnectionError(connectionError?.message ?? 'Disconnected'), ); searchHub.onreconnected(() => onConnected()); - searchHub.onclose((error) => - onConnectionError(error?.message ?? 'Disconnected'), + searchHub.onclose((connectionError) => + onConnectionError(connectionError?.message ?? 'Disconnected'), ); const connect = async () => { try { onConnecting(); await searchHub.start(); - } catch (error) { - toast.error(error?.message ?? 'Failed to connect'); - onConnectionError(error?.message ?? 'Failed to connect'); + } catch (connectionError) { + toast.error(connectionError?.message ?? 'Failed to connect'); + onConnectionError(connectionError?.message ?? 'Failed to connect'); } }; @@ -122,9 +122,11 @@ const Searches = ({ server } = {}) => { if (navigate) { history.push(`${match.url.replace(`/${searchId}`, '')}/${id}`); } - } catch (error) { - console.error(error); - toast.error(error?.response?.data ?? error?.message ?? error); + } catch (createError) { + console.error(createError); + toast.error( + createError?.response?.data ?? createError?.message ?? createError, + ); setCreating(false); } }; @@ -154,9 +156,13 @@ const Searches = ({ server } = {}) => { setStopping(true); await library.stop({ id: search.id }); setStopping(false); - } catch (error) { - console.error(error); - toast.error(error?.response?.data ?? error?.message ?? error); + } catch (stoppingError) { + console.error(stoppingError); + toast.error( + stoppingError?.response?.data ?? + stoppingError?.message ?? + stoppingError, + ); setStopping(false); } }; @@ -235,7 +241,7 @@ const Searches = ({ server } = {}) => { /> } loading={creating} - onKeyUp={(e) => (e.key === 'Enter' ? create() : '')} + onKeyUp={(keyUpEvent) => (keyUpEvent.key === 'Enter' ? create() : '')} placeholder="Search phrase" ref={inputRef} size="big" diff --git a/src/web/src/components/Shared/CodeEditor.jsx b/src/web/src/components/Shared/CodeEditor.jsx index 53915153..8780bc31 100644 --- a/src/web/src/components/Shared/CodeEditor.jsx +++ b/src/web/src/components/Shared/CodeEditor.jsx @@ -16,7 +16,7 @@ const CodeEditor = ({ onChange = () => {}, theme, value, ...rest }) => { StreamLanguage.define(yaml), syntaxHighlighting(defaultHighlightStyle, { fallback: true }), ]} - onChange={(value, _) => onChange(value)} + onChange={(newValue) => onChange(newValue)} theme={theme} value={value} {...rest} diff --git a/src/web/src/components/Shared/Div.jsx b/src/web/src/components/Shared/Div.jsx index c88e646e..38be75c3 100644 --- a/src/web/src/components/Shared/Div.jsx +++ b/src/web/src/components/Shared/Div.jsx @@ -2,7 +2,7 @@ import React from 'react'; const Div = ({ children, hidden, ...rest }) => { if (hidden) { - return <></>; + return null; } return <div {...rest}>{children}</div>; diff --git a/src/web/src/components/Shared/FileList.jsx b/src/web/src/components/Shared/FileList.jsx index 977748dd..205eaaf6 100644 --- a/src/web/src/components/Shared/FileList.jsx +++ b/src/web/src/components/Shared/FileList.jsx @@ -77,8 +77,8 @@ const FileList = ({ <Table.Body> {files .sort((a, b) => (a.filename > b.filename ? 1 : -1)) - .map((f, index) => ( - <Table.Row key={index}> + .map((f) => ( + <Table.Row key={f.filename}> <Table.Cell className="filelist-selector"> <Checkbox checked={f.selected} diff --git a/src/web/src/components/Shared/Logo.jsx b/src/web/src/components/Shared/Logo.jsx index e9ee9d52..92e1753c 100644 --- a/src/web/src/components/Shared/Logo.jsx +++ b/src/web/src/components/Shared/Logo.jsx @@ -1,4 +1,4 @@ -const Logos = [ +const Logo = [ ` ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ @@ -13,4 +13,4 @@ const Logos = [ `, ]; -export default Logos; +export default Logo; diff --git a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx index 008e93bd..51b14225 100644 --- a/src/web/src/components/Shared/ShrinkableDropdownButton.jsx +++ b/src/web/src/components/Shared/ShrinkableDropdownButton.jsx @@ -15,7 +15,7 @@ const ShrinkableDropdownButton = ({ options, }) => { if (hidden) { - return <></>; + return null; } return ( @@ -34,7 +34,7 @@ const ShrinkableDropdownButton = ({ disabled={disabled} onChange={onChange} options={options} - trigger={<></>} + trigger={null} /> </Button.Group> ); diff --git a/src/web/src/components/System/Data/index.jsx b/src/web/src/components/System/Data/index.jsx index 1df4f981..8b6a99eb 100644 --- a/src/web/src/components/System/Data/index.jsx +++ b/src/web/src/components/System/Data/index.jsx @@ -3,17 +3,17 @@ import React, { useState } from 'react'; import { toast } from 'react-toastify'; import { Button, Divider, Header, Icon } from 'semantic-ui-react'; +const clear = async ({ direction, setState }) => { + setState(true); + await clearCompleted({ direction }); + setState(false); + toast.success(`Completed ${direction}s cleared!`); +}; + const Data = () => { const [up, setUp] = useState(false); const [down, setDown] = useState(false); - const clear = async ({ direction, setState }) => { - setState(true); - await clearCompleted({ direction }); - setState(false); - toast.success(`Completed ${direction}s cleared!`); - }; - return ( <div> <Header diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx index 6b677144..e577b31c 100644 --- a/src/web/src/components/System/Files/Explorer.jsx +++ b/src/web/src/components/System/Files/Explorer.jsx @@ -4,11 +4,139 @@ import { LoaderSegment } from '../../Shared'; import React, { useEffect, useState } from 'react'; import { Header, Icon, Modal, Table } from 'semantic-ui-react'; +const FileRow = ({ + fullName, + length, + modifiedAt, + name, + remoteFileManagement, + root, + subdirectory, +}) => ( + <Table.Row key={fullName}> + <Table.Cell> + <Icon name="file outline" /> + {name} + </Table.Cell> + <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> + <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell> + <Table.Cell> + {remoteFileManagement ? ( + <Modal + actions={[ + 'Cancel', + { + content: 'Delete', + key: 'done', + negative: true, + onClick: async () => { + await deleteFile({ + path: `${subdirectory.join('/')}/${fullName}`, + root, + }); + fetch(); + }, + }, + ]} + centered + content={`Are you sure you want to delete file '${fullName}'?`} + header={ + <Header + content="Confirm File Delete" + icon="trash alternate" + /> + } + size="small" + trigger={ + <Icon + color="red" + name="trash alternate" + style={{ cursor: 'pointer' }} + /> + } + /> + ) : null} + </Table.Cell> + </Table.Row> +); + +const DirectoryRow = ({ + deletable = true, + fullName, + modifiedAt, + name, + onClick = () => {}, + remoteFileManagement, + root, + subdirectory, +}) => ( + <Table.Row key={name}> + <Table.Cell + onClick={onClick} + style={{ cursor: 'pointer' }} + > + <Icon name="folder" /> + {name} + </Table.Cell> + <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> + <Table.Cell /> + <Table.Cell> + {remoteFileManagement && deletable ? ( + <Modal + actions={[ + 'Cancel', + { + content: 'Delete', + key: 'done', + negative: true, + onClick: async () => { + await deleteDirectory({ + path: `${subdirectory.join('/')}/${fullName}`, + root, + }); + fetch(); + }, + }, + ]} + centered + content={`Are you sure you want to delete directory '${fullName}'?`} + header={ + <Header + content="Confirm Directory Delete" + icon="trash alternate" + /> + } + size="small" + trigger={ + <Icon + color="red" + name="trash alternate" + style={{ cursor: 'pointer' }} + /> + } + /> + ) : ( + '' + )} + </Table.Cell> + </Table.Row> +); + const Explorer = ({ remoteFileManagement, root }) => { const [directory, setDirectory] = useState({ directories: [], files: [] }); const [subdirectory, setSubdirectory] = useState([]); const [loading, setLoading] = useState(false); + const fetch = async () => { + setLoading(true); + const directoryResult = await list({ + root, + subdirectory: subdirectory.join('/'), + }); + setDirectory(directoryResult); + setLoading(false); + }; + useEffect(() => { fetch(); }, [subdirectory]); // eslint-disable-line react-hooks/exhaustive-deps @@ -17,13 +145,6 @@ const Explorer = ({ remoteFileManagement, root }) => { setSubdirectory([]); }, [root]); - const fetch = async () => { - setLoading(true); - const dir = await list({ root, subdirectory: subdirectory.join('/') }); - setDirectory(dir); - setLoading(false); - }; - const select = ({ path }) => { setSubdirectory([...subdirectory, path]); }; @@ -34,115 +155,6 @@ const Explorer = ({ remoteFileManagement, root }) => { setSubdirectory(copy); }; - const FileRow = ({ fullName, length, modifiedAt, name }) => ( - <Table.Row key={fullName}> - <Table.Cell> - <Icon name="file outline" /> - {name} - </Table.Cell> - <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> - <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell> - <Table.Cell> - {remoteFileManagement ? ( - <Modal - actions={[ - 'Cancel', - { - content: 'Delete', - key: 'done', - negative: true, - onClick: async () => { - await deleteFile({ - path: `${subdirectory.join('/')}/${fullName}`, - root, - }); - fetch(); - }, - }, - ]} - centered - content={`Are you sure you want to delete file '${fullName}'?`} - header={ - <Header - content="Confirm File Delete" - icon="trash alternate" - /> - } - size="small" - trigger={ - <Icon - color="red" - name="trash alternate" - style={{ cursor: 'pointer' }} - /> - } - /> - ) : ( - <></> - )} - </Table.Cell> - </Table.Row> - ); - - const DirectoryRow = ({ - deletable = true, - fullName, - modifiedAt, - name, - onClick = () => {}, - }) => ( - <Table.Row key={name}> - <Table.Cell - onClick={onClick} - style={{ cursor: 'pointer' }} - > - <Icon name="folder" /> - {name} - </Table.Cell> - <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell> - <Table.Cell /> - <Table.Cell> - {remoteFileManagement && deletable ? ( - <Modal - actions={[ - 'Cancel', - { - content: 'Delete', - key: 'done', - negative: true, - onClick: async () => { - await deleteDirectory({ - path: `${subdirectory.join('/')}/${fullName}`, - root, - }); - fetch(); - }, - }, - ]} - centered - content={`Are you sure you want to delete directory '${fullName}'?`} - header={ - <Header - content="Confirm Directory Delete" - icon="trash alternate" - /> - } - size="small" - trigger={ - <Icon - color="red" - name="trash alternate" - style={{ cursor: 'pointer' }} - /> - } - /> - ) : ( - '' - )} - </Table.Cell> - </Table.Row> - ); - if (loading) { return <LoaderSegment />; } @@ -198,17 +210,29 @@ const Explorer = ({ remoteFileManagement, root }) => { fullName=".." name=".." onClick={upOneSubdirectory} + remoteFileManagement={remoteFileManagement} + root={root} + subdirectory={subdirectory} /> )} {directory?.directories?.map((d) => ( <DirectoryRow key={d.name} onClick={() => select({ path: d.name })} + remoteFileManagement={remoteFileManagement} + root={root} + subdirectory={subdirectory} {...d} /> ))} {directory?.files?.map((f) => ( - <FileRow {...f} /> + <FileRow + key={f.name} + remoteFileManagement={remoteFileManagement} + root={root} + subdirectory={subdirectory} + {...f} + /> ))} </> )} diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx index 3c199f42..f36258ec 100644 --- a/src/web/src/components/System/Logs/index.jsx +++ b/src/web/src/components/System/Logs/index.jsx @@ -19,7 +19,11 @@ const levels = { const maxLogs = 500; class Logs extends Component { - state = initialState; + constructor(props) { + super(props); + + this.state = initialState; + } componentDidMount() { const logsHub = createLogsHubConnection(); @@ -32,10 +36,10 @@ class Logs extends Component { }); logsHub.on('log', (log) => { - this.setState({ + this.setState((previousState) => ({ connected: true, - logs: [log].concat(this.state.logs).slice(0, maxLogs), - }); + logs: [log].concat(previousState.logs).slice(0, maxLogs), + })); }); logsHub.onreconnecting(() => this.setState({ connected: false })); @@ -69,10 +73,10 @@ class Logs extends Component { </Table.Row> </Table.Header> <Table.Body className="logs-table-body"> - {logs.map((log, index) => ( + {logs.map((log) => ( <Table.Row disabled={log.level === 'Debug'} - key={index} + key={log.timestamp} negative={log.level === 'Error'} warning={log.level === 'Warning'} > diff --git a/src/web/src/components/System/Options/DebugModal.jsx b/src/web/src/components/System/Options/DebugModal.jsx index 2a1b8c5f..e1f1b6bd 100644 --- a/src/web/src/components/System/Options/DebugModal.jsx +++ b/src/web/src/components/System/Options/DebugModal.jsx @@ -8,12 +8,6 @@ const DebugModal = ({ onClose, open, theme }) => { const [loading, setLoading] = useState(true); const [debugView, setDebugView] = useState(); - useEffect(() => { - if (open) { - get(); - } - }, [open]); - const get = async () => { setLoading(true); @@ -27,6 +21,12 @@ const DebugModal = ({ onClose, open, theme }) => { } }; + useEffect(() => { + if (open) { + get(); + } + }, [open]); + return ( <Modal onClose={onClose} diff --git a/src/web/src/components/System/Options/EditModal.jsx b/src/web/src/components/System/Options/EditModal.jsx index f2a23e4a..6fc2af69 100644 --- a/src/web/src/components/System/Options/EditModal.jsx +++ b/src/web/src/components/System/Options/EditModal.jsx @@ -10,10 +10,12 @@ import React, { useEffect, useState } from 'react'; import { Button, Icon, Message, Modal } from 'semantic-ui-react'; const EditModal = ({ onClose, open, theme }) => { + // eslint-disable-next-line react/hook-use-state const [{ error, loading }, setLoading] = useState({ error: false, loading: true, }); + // eslint-disable-next-line react/hook-use-state const [{ isDirty, location, yaml }, setYaml] = useState({ isDirty: false, location: undefined, @@ -22,51 +24,51 @@ const EditModal = ({ onClose, open, theme }) => { const [yamlError, setYamlError] = useState(); const [updateError, setUpdateError] = useState(); - useEffect(() => { - if (open) { - get(); - } - }, [open]); - const get = async () => { setLoading({ error: false, loading: true }); try { - const [location, yaml] = await Promise.all([ + const [locationResult, yamlResult] = await Promise.all([ getYamlLocation(), getYaml(), ]); - setYaml({ isDirty: false, location, yaml }); + setYaml({ isDirty: false, location: locationResult, yaml: yamlResult }); setLoading({ error: false, loading: false }); - } catch (error) { - setLoading({ error: error.message, loading: false }); + } catch (getError) { + setLoading({ error: getError.message, loading: false }); } }; - const update = async (yaml) => { - setYaml({ isDirty: true, location, yaml }); - validate(yaml); + const validate = async (newYaml) => { + const response = await validateYaml({ yaml: newYaml }); + setYamlError(response); }; - const validate = async (yaml) => { - const response = await validateYaml({ yaml }); - setYamlError(response); + const update = async (newYaml) => { + setYaml({ isDirty: true, location, yaml: newYaml }); + validate(newYaml); }; - const save = async (yaml) => { - await validate(yaml); + const save = async (newYaml) => { + await validate(newYaml); if (!yamlError) { try { - await updateYaml({ yaml }); + await updateYaml({ yaml: newYaml }); onClose(); - } catch (error) { - setUpdateError(error.response.data); + } catch (nextUpdateError) { + setUpdateError(nextUpdateError.response.data); } } }; + useEffect(() => { + if (open) { + get(); + } + }, [open]); + return ( <Modal onClose={onClose} diff --git a/src/web/src/components/System/Options/index.jsx b/src/web/src/components/System/Options/index.jsx index 9e842fc9..f834d8cf 100644 --- a/src/web/src/components/System/Options/index.jsx +++ b/src/web/src/components/System/Options/index.jsx @@ -10,7 +10,53 @@ import React, { useEffect, useState } from 'react'; import { Divider } from 'semantic-ui-react'; import YAML from 'yaml'; -const Index = ({ options, theme }) => { +const DebugButton = ({ + debug, + remoteConfiguration, + setDebugModal, + ...props +}) => { + if (!remoteConfiguration || !debug) return null; + + return ( + <ShrinkableButton + icon="bug" + mediaQuery="(max-width: 516px)" + onClick={() => setDebugModal(true)} + {...props} + > + Debug View + </ShrinkableButton> + ); +}; + +const EditButton = ({ remoteConfiguration, setEditModal, ...props }) => { + if (!remoteConfiguration) { + return ( + <ShrinkableButton + disabled + icon="lock" + mediaQuery="(max-width: 516px)" + > + Remote Configuration Disabled + </ShrinkableButton> + ); + } + + return ( + <ShrinkableButton + icon="edit" + mediaQuery="(max-width: 516px)" + onClick={() => setEditModal(true)} + primary + {...props} + > + Edit + </ShrinkableButton> + ); +}; + +const Options = ({ options, theme }) => { const [debugModal, setDebugModal] = useState(false); const [editModal, setEditModal] = useState(false); const [contents, setContents] = useState(); @@ -25,52 +71,20 @@ const Index = ({ options, theme }) => { const { debug, remoteConfiguration } = options; - const DebugButton = ({ ...props }) => { - if (!remoteConfiguration || !debug) return <></>; - - return ( - <ShrinkableButton - icon="bug" - mediaQuery="(max-width: 516px)" - onClick={() => setDebugModal(true)} - {...props} - > - Debug View - </ShrinkableButton> - ); - }; - - const EditButton = ({ ...props }) => { - if (!remoteConfiguration) { - return ( - <ShrinkableButton - disabled - icon="lock" - mediaQuery="(max-width: 516px)" - > - Remote Configuration Disabled - </ShrinkableButton> - ); - } - - return ( - <ShrinkableButton - icon="edit" - mediaQuery="(max-width: 516px)" - onClick={() => setEditModal(true)} - primary - {...props} - > - Edit - </ShrinkableButton> - ); - }; - return ( <> <div className="header-buttons"> - <DebugButton disabled={!contents} /> - <EditButton disabled={!contents} /> + <DebugButton + debug={debug} + disabled={!contents} + remoteConfiguration={remoteConfiguration} + setDebugModal={setDebugModal} + /> + <EditButton + disabled={!contents} + remoteConfiguration={remoteConfiguration} + setEditModal={setEditModal} + /> </div> <Divider /> <Switch loading={!contents && <LoaderSegment />}> @@ -95,4 +109,4 @@ const Index = ({ options, theme }) => { ); }; -export default Index; +export default Options; diff --git a/src/web/src/components/System/Shares/ContentsModal.jsx b/src/web/src/components/System/Shares/ContentsModal.jsx index 45030672..bb5b3fc9 100644 --- a/src/web/src/components/System/Shares/ContentsModal.jsx +++ b/src/web/src/components/System/Shares/ContentsModal.jsx @@ -14,9 +14,9 @@ const ContentsModal = ({ onClose, share, theme }) => { const fetch = async () => { setLoading(true); - const contents = await browse({ id }); + const result = await browse({ id }); - const directories = contents.map((directory) => { + const directories = result.map((directory) => { const lines = [directory.name.replace(remotePath, localPath)]; for (const file of orderBy(directory.files, 'filename')) { diff --git a/src/web/src/components/System/Shares/ExclusionTable.jsx b/src/web/src/components/System/Shares/ExclusionTable.jsx index dc94e98d..4533d7fe 100644 --- a/src/web/src/components/System/Shares/ExclusionTable.jsx +++ b/src/web/src/components/System/Shares/ExclusionTable.jsx @@ -28,8 +28,8 @@ const ExclusionTable = ({ exclusions = [] } = {}) => { ) } > - {exclusions.map((share, index) => ( - <Table.Row key={index}> + {exclusions.map((share) => ( + <Table.Row key={share.localPath}> <Table.Cell> <Icon color="red" diff --git a/src/web/src/components/System/Shares/ShareTable.jsx b/src/web/src/components/System/Shares/ShareTable.jsx index 18d0f06b..120d071e 100644 --- a/src/web/src/components/System/Shares/ShareTable.jsx +++ b/src/web/src/components/System/Shares/ShareTable.jsx @@ -39,8 +39,8 @@ const ShareTable = ({ onClick, shares }) => { ) } > - {shares.map((share, index) => ( - <Table.Row key={index}> + {shares.map((share) => ( + <Table.Row key={`${share.host}+${share.localPath}`}> <Table.Cell>{share.host}</Table.Cell> <Table.Cell onClick={() => onClick(share)}> <Icon name="folder" /> diff --git a/src/web/src/components/System/Shares/index.jsx b/src/web/src/components/System/Shares/index.jsx index d629230e..d7af5e5c 100644 --- a/src/web/src/components/System/Shares/index.jsx +++ b/src/web/src/components/System/Shares/index.jsx @@ -7,7 +7,33 @@ import React, { useEffect, useState } from 'react'; import { toast } from 'react-toastify'; import { Divider } from 'semantic-ui-react'; -const Index = ({ state = {} } = {}) => { +const ScanButton = ({ rescan, scanPending, working }) => ( + <ShrinkableButton + color={scanPending ? 'yellow' : undefined} + disabled={working} + icon="refresh" + loading={working} + mediaQuery="(max-width: 516px)" + onClick={() => rescan()} + primary={!scanPending} + > + Rescan Shares + </ShrinkableButton> +); + +const CancelButton = ({ cancel, working }) => ( + <ShrinkableButton + color="red" + disabled={working} + icon="x" + mediaQuery="(max-width: 516px)" + onClick={() => cancel()} + > + Cancel Scan + </ShrinkableButton> +); + +const Shares = ({ state = {} } = {}) => { const [loading, setLoading] = useState(true); const [working, setWorking] = useState(false); const [shares, setShares] = useState([]); @@ -15,30 +41,15 @@ const Index = ({ state = {} } = {}) => { const { directories, files, scanPending, scanProgress, scanning } = state; - useEffect(() => { - getAll(); - }, []); - - useEffect(() => { - getAll({ quiet: true }); - - if (!scanning) { - // 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 }), 1_000); - } - }, [scanPending, scanning]); - - const getAll = async ({ quiet } = { quiet: false }) => { + const getAll = async (quiet = false) => { try { if (!quiet) setLoading(true); const sharesByHost = await sharesLibrary.getAll(); const flattened = Object.entries(sharesByHost).reduce( - (accumulator, [host, shares]) => { + (accumulator, [host, sharesForHost]) => { return accumulator.concat( - shares.map((share) => ({ host, ...share })), + sharesForHost.map((share) => ({ host, ...share })), ); }, [], @@ -53,6 +64,21 @@ const Index = ({ state = {} } = {}) => { } }; + useEffect(() => { + getAll(); + }, []); + + useEffect(() => { + getAll(true); + + if (!scanning) { + // the state change out of scanning can fire before + // shares are updated, which leaves them stale. wait a second + // and fetch again. + setTimeout(() => getAll(true), 1_000); + } + }, [scanPending, scanning]); + const rescan = async () => { try { setWorking(true); @@ -82,40 +108,27 @@ const Index = ({ state = {} } = {}) => { } }; - const ScanButton = () => ( - <ShrinkableButton - color={scanPending ? 'yellow' : undefined} - disabled={working} - icon="refresh" - loading={working} - mediaQuery="(max-width: 516px)" - onClick={() => rescan()} - primary={!scanPending} - > - Rescan Shares - </ShrinkableButton> - ); - - const CancelButton = () => ( - <ShrinkableButton - color="red" - disabled={working} - icon="x" - mediaQuery="(max-width: 516px)" - onClick={() => cancel()} - > - Cancel Scan - </ShrinkableButton> - ); - const shared = shares.filter((share) => !share.isExcluded); const excluded = shares.filter((share) => share.isExcluded); return ( <Switch loading={loading && <LoaderSegment />}> <div className="header-buttons"> - <Switch scanning={scanning && <CancelButton />}> - <ScanButton /> + <Switch + scanning={ + scanning && ( + <CancelButton + cancel={cancel} + working={working} + /> + ) + } + > + <ScanButton + rescan={rescan} + scanPending={scanPending} + working={working} + /> </Switch> </div> <Divider /> @@ -147,4 +160,4 @@ const Index = ({ state = {} } = {}) => { ); }; -export default Index; +export default Shares; diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx index 02420d9c..8746cefe 100644 --- a/src/web/src/components/System/System.jsx +++ b/src/web/src/components/System/System.jsx @@ -137,8 +137,8 @@ const System = ({ options = {}, state = {}, theme }) => { const activeIndex = panes.findIndex((pane) => pane.route === tab); - const onTabChange = (e, { activeIndex }) => { - history.push(panes[activeIndex].route); + const onTabChange = (_event, { activeIndex: newActiveIndex }) => { + history.push(panes[newActiveIndex].route); }; if (tab === undefined) { diff --git a/src/web/src/components/Transfers/TransferGroup.jsx b/src/web/src/components/Transfers/TransferGroup.jsx index 4f2dbb7c..bdab5504 100644 --- a/src/web/src/components/Transfers/TransferGroup.jsx +++ b/src/web/src/components/Transfers/TransferGroup.jsx @@ -4,18 +4,27 @@ import React, { Component } from 'react'; import { Button, Card, Icon } from 'semantic-ui-react'; class TransferGroup extends Component { - state = { - isFolded: false, - selections: new Set(), - }; + constructor(props) { + super(props); + + this.state = { + isFolded: false, + selections: new Set(), + }; + } - onSelectionChange = (directoryName, file, selected) => { + handleSelectionChange = (directoryName, file, selected) => { const { selections } = this.state; const object = JSON.stringify({ directory: directoryName, filename: file.filename, }); - selected ? selections.add(object) : selections.delete(object); + + if (selected) { + selections.add(object); + } else { + selections.delete(object); + } this.setState({ selections }); }; @@ -52,7 +61,7 @@ class TransferGroup extends Component { }; retryAll = async (selected) => { - await Promise.all(selected.map((file) => this.retry(file))); + await Promise.all(selected.map((file) => this.handleRetry(file))); }; cancelAll = async (direction, username, selected) => { @@ -73,7 +82,7 @@ class TransferGroup extends Component { ); }; - retry = async (file) => { + handleRetry = async (file) => { const { filename, size, username } = file; try { @@ -83,7 +92,7 @@ class TransferGroup extends Component { } }; - fetchPlaceInQueue = async (file) => { + handleFetchPlaceInQueue = async (file) => { const { id, username } = file; try { @@ -94,7 +103,7 @@ class TransferGroup extends Component { }; toggleFolded = () => { - this.setState({ isFolded: !this.state.isFolded }); + this.setState((previousState) => ({ isFolded: !previousState.isFolded })); }; render() { @@ -131,18 +140,18 @@ class TransferGroup extends Component { </Card.Header> {user.directories && !isFolded && - user.directories.map((dir, index) => ( + user.directories.map((directory) => ( <TransferList direction={this.props.direction} - directoryName={dir.directory} - files={(dir.files || []).map((f) => ({ + directoryName={directory.directory} + files={(directory.files || []).map((f) => ({ ...f, - selected: this.isSelected(dir.directory, f), + selected: this.isSelected(directory.directory, f), }))} - key={index} - onPlaceInQueueRequested={this.fetchPlaceInQueue} - onRetryRequested={this.retry} - onSelectionChange={this.onSelectionChange} + key={directory.directory} + onPlaceInQueueRequested={this.handleFetchPlaceInQueue} + onRetryRequested={this.handleRetry} + onSelectionChange={this.handleSelectionChange} username={user.username} /> ))} diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index b55ada1b..b81049ec 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -33,15 +33,19 @@ const isQueuedState = (state) => state.includes('Queued'); const formatBytesTransferred = ({ size, transferred }) => { const [s, sExtension] = formatBytes(size, 1).split(' '); - const t = formatBytesAsUnit(transferred, 1, sExtension); + const t = formatBytesAsUnit(transferred, sExtension, 1); return `${t}/${s} ${sExtension}`; }; class TransferList extends Component { - state = { - isFolded: false, - }; + constructor(props) { + super(props); + + this.state = { + isFolded: false, + }; + } handleClick = (file) => { const { direction, state } = file; @@ -55,10 +59,12 @@ class TransferList extends Component { return this.props.onPlaceInQueueRequested(file); } } + + return undefined; }; toggleFolded = () => { - this.setState({ isFolded: !this.state.isFolded }); + this.setState((previousState) => ({ isFolded: !previousState.isFolded })); }; render() { @@ -78,7 +84,7 @@ class TransferList extends Component { /> {directoryName} </Header> - {!isFolded ? ( + {isFolded === false ? ( <List> <List.Item> <Table> @@ -117,8 +123,8 @@ class TransferList extends Component { getFileName(b.filename), ), ) - .map((f, index) => ( - <Table.Row key={index}> + .map((f) => ( + <Table.Row key={f.filename}> <Table.Cell className="transferlist-selector"> <Checkbox checked={f.selected} diff --git a/src/web/src/components/Transfers/Transfers.jsx b/src/web/src/components/Transfers/Transfers.jsx index 876cc14b..f43ed1ae 100644 --- a/src/web/src/components/Transfers/Transfers.jsx +++ b/src/web/src/components/Transfers/Transfers.jsx @@ -14,6 +14,16 @@ const Transfers = ({ direction, server }) => { const [cancelling, setCancelling] = useState(false); const [removing, setRemoving] = useState(false); + const fetch = async () => { + try { + const response = await transfersLibrary.getAll({ direction }); + setTransfers(response); + } catch (error) { + console.error(error); + toast.error(error?.response?.data ?? error?.message ?? error); + } + }; + useEffect(() => { setConnecting(true); @@ -40,16 +50,6 @@ const Transfers = ({ direction, server }) => { setConnecting(true); }, [direction]); // eslint-disable-line react-hooks/exhaustive-deps - const fetch = async () => { - try { - const response = await transfersLibrary.getAll({ direction }); - setTransfers(response); - } catch (error) { - console.error(error); - toast.error(error?.response?.data ?? error?.message ?? error); - } - }; - const retry = async ({ file, suppressStateChange = false }) => { const { filename, size, username } = file; @@ -67,10 +67,12 @@ const Transfers = ({ direction, server }) => { } }; - const retryAll = async (transfers) => { + const retryAll = async (transfersToRetry) => { setRetrying(true); await Promise.all( - transfers.map((file) => retry({ file, suppressStateChange: true })), + transfersToRetry.map((file) => + retry({ file, suppressStateChange: true }), + ), ); setRetrying(false); }; @@ -89,10 +91,12 @@ const Transfers = ({ direction, server }) => { } }; - const cancelAll = async (transfers) => { + const cancelAll = async (transfersToCancel) => { setCancelling(true); await Promise.all( - transfers.map((file) => cancel({ file, suppressStateChange: true })), + transfersToCancel.map((file) => + cancel({ file, suppressStateChange: true }), + ), ); setCancelling(false); }; @@ -111,10 +115,12 @@ const Transfers = ({ direction, server }) => { } }; - const removeAll = async (transfers) => { + const removeAll = async (transfersToRemove) => { setRemoving(true); await Promise.all( - transfers.map((file) => remove({ file, suppressStateChange: true })), + transfersToRemove.map((file) => + remove({ file, suppressStateChange: true }), + ), ); setRemoving(false); }; @@ -142,12 +148,12 @@ const Transfers = ({ direction, server }) => { icon={direction} /> ) : ( - transfers.map((user, index) => ( + transfers.map((user) => ( <TransferGroup cancel={cancel} cancelAll={cancelAll} direction={direction} - key={index} + key={user.username} remove={remove} removeAll={removeAll} retry={retry} diff --git a/src/web/src/components/Transfers/TransfersHeader.jsx b/src/web/src/components/Transfers/TransfersHeader.jsx index 2e61bab1..1aeb7e49 100644 --- a/src/web/src/components/Transfers/TransfersHeader.jsx +++ b/src/web/src/components/Transfers/TransfersHeader.jsx @@ -75,20 +75,18 @@ const TransfersHeader = ({ const [retryOption, setRetryOption] = useState('Errored'); const files = useMemo(() => { - const files = transfers.reduce((accumulator, username) => { - const allUserFiles = username.directories.reduce( - (accumulator_, directory) => { - accumulator_ = accumulator_.concat(directory.files); - return accumulator_; - }, - [], - ); - - accumulator = accumulator.concat(allUserFiles); - return accumulator; - }, []); + return transfers + .reduce((accumulator, username) => { + const allUserFiles = username.directories.reduce( + (directoryAccumulator, directory) => { + return directoryAccumulator.concat(directory.files); + }, + [], + ); - return files.filter((file) => file.direction.toLowerCase() === direction); + return accumulator.concat(allUserFiles); + }, []) + .filter((file) => file.direction.toLowerCase() === direction); }, [direction, transfers]); const empty = files.length === 0; diff --git a/src/web/src/components/Users/User.jsx b/src/web/src/components/Users/User.jsx index 41581db0..0e392122 100644 --- a/src/web/src/components/Users/User.jsx +++ b/src/web/src/components/Users/User.jsx @@ -33,14 +33,11 @@ const FreeUploadSlot = ({ hasFreeUploadSlot }) => ( const User = ({ address, description, - hasFreeUploadSlot, hasPicture, - isPrivileged, picture, port, presence, queueLength, - updatedAt, uploadSlots, username, }) => ( diff --git a/src/web/src/components/Users/Users.jsx b/src/web/src/components/Users/Users.jsx index 5639e3cc..e7f279ea 100644 --- a/src/web/src/components/Users/Users.jsx +++ b/src/web/src/components/Users/Users.jsx @@ -6,16 +6,39 @@ import User from './User'; import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'; import { Icon, Input, Item, Loader, Segment } from 'semantic-ui-react'; -const Users = (props) => { +const Users = () => { const inputRef = useRef(); const [user, setUser] = useState(); const [usernameInput, setUsernameInput] = useState(); const [selectedUsername, setSelectedUsername] = useState(undefined); + // eslint-disable-next-line react/hook-use-state const [{ error, fetching }, setStatus] = useState({ error: undefined, fetching: false, }); + const setInputText = (text) => { + inputRef.current.inputRef.current.value = text; + }; + + const setInputFocus = () => { + inputRef.current.focus(); + }; + + const clear = () => { + localStorage.removeItem(activeUserInfoKey); + setSelectedUsername(undefined); + setUser(undefined); + setInputText(''); + setInputFocus(); + }; + + const keyUp = (event) => (event.key === 'Escape' ? clear() : ''); + + useLayoutEffect(() => { + document.removeEventListener('keyup', keyUp, false); + }, []); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { document.addEventListener('keyup', keyUp, false); @@ -27,10 +50,6 @@ const Users = (props) => { } }, []); // eslint-disable-line react-hooks/exhaustive-deps - useLayoutEffect(() => { - document.removeEventListener('keyup', keyUp, false); - }, []); // eslint-disable-line react-hooks/exhaustive-deps - useEffect(() => { const fetchUser = async () => { if (!selectedUsername) { @@ -49,32 +68,14 @@ const Users = (props) => { localStorage.setItem(activeUserInfoKey, selectedUsername); setUser({ ...info.data, ...status.data, ...endpoint.data }); setStatus({ error: undefined, fetching: false }); - } catch (error) { - setStatus({ error, fetching: false }); + } catch (fetchError) { + setStatus({ error: fetchError, fetching: false }); } }; fetchUser(); }, [selectedUsername]); - const clear = () => { - localStorage.removeItem(activeUserInfoKey); - setSelectedUsername(undefined); - setUser(undefined); - setInputText(''); - setInputFocus(); - }; - - const setInputText = (text) => { - inputRef.current.inputRef.current.value = text; - }; - - const setInputFocus = () => { - inputRef.current.focus(); - }; - - const keyUp = (e) => (e.key === 'Escape' ? clear() : ''); - return ( <div className="users-container"> <Segment @@ -90,7 +91,7 @@ const Users = (props) => { <Input action={ !fetching && - (!user + (user == null ? { icon: 'search', onClick: () => setSelectedUsername(usernameInput), @@ -108,9 +109,9 @@ const Users = (props) => { /> } loading={fetching} - onChange={(e) => setUsernameInput(e.target.value)} - onKeyUp={(e) => - e.key === 'Enter' ? setSelectedUsername(usernameInput) : '' + onChange={(event) => setUsernameInput(event.target.value)} + onKeyUp={(event) => + event.key === 'Enter' ? setSelectedUsername(usernameInput) : '' } placeholder="Username" ref={inputRef} @@ -128,7 +129,7 @@ const Users = (props) => { <div> {error ? ( <span>Failed to retrieve information for {selectedUsername}</span> - ) : !user ? ( + ) : user == null ? ( <PlaceholderSegment caption="No user info to display" icon="users" diff --git a/src/web/src/config.js b/src/web/src/config.js index 5f808e9b..9d5647db 100644 --- a/src/web/src/config.js +++ b/src/web/src/config.js @@ -1,6 +1,7 @@ const urlBase = (window.urlBase === '/' ? '' : window.urlBase) || ''; const developmentPort = window.port ?? 5_030; const rootUrl = + // eslint-disable-next-line n/no-process-env process.env.NODE_ENV === 'production' ? urlBase : `http://localhost:${developmentPort}${urlBase}`; diff --git a/src/web/src/lib/api.js b/src/web/src/lib/api.js index 8f3a4c90..9506a0da 100644 --- a/src/web/src/lib/api.js +++ b/src/web/src/lib/api.js @@ -1,5 +1,5 @@ import { apiBaseUrl } from '../config'; -import * as session from './session'; +import { clearToken, getToken, isPassthroughEnabled } from './token'; import axios from 'axios'; axios.defaults.baseURL = apiBaseUrl; @@ -9,11 +9,11 @@ const api = axios.create({ }); api.interceptors.request.use((config) => { - const token = session.getToken(); + const token = getToken(); config.headers['Content-Type'] = 'application/json'; - if (!session.isPassthroughEnabled() && token) { + if (!isPassthroughEnabled() && token) { config.headers.Authorization = 'Bearer ' + token; } @@ -32,7 +32,7 @@ api.interceptors.response.use( ) ) { console.debug('received 401 from api route, logging out'); - session.logout(); + clearToken(); window.location.reload(true); return Promise.reject(error); diff --git a/src/web/src/lib/searches.js b/src/web/src/lib/searches.js index 5fbe257f..680a60c7 100644 --- a/src/web/src/lib/searches.js +++ b/src/web/src/lib/searches.js @@ -37,6 +37,16 @@ export const getResponses = async ({ id }) => { return response; }; +const getNthMatch = (string, regex, n) => { + const match = string.match(regex); + + if (match) { + return Number.parseInt(match[n], 10); + } + + return undefined; +}; + export const parseFiltersFromString = (string) => { const filters = { exclude: [], @@ -52,30 +62,24 @@ export const parseFiltersFromString = (string) => { minLength: 0, }; - const getNthMatch = (string, regex, n) => { - const match = string.match(regex); - - if (match) { - return Number.parseInt(match[n], 10); - } - }; - filters.minBitRate = - getNthMatch(string, /(minbr|minbitrate):(\d+)/i, 2) || filters.minBitRate; + getNthMatch(string, /(minbr|minbitrate):(\d+)/iu, 2) || filters.minBitRate; filters.minBitDepth = - getNthMatch(string, /(minbd|minbitdepth):(\d+)/i, 2) || filters.minBitDepth; + getNthMatch(string, /(minbd|minbitdepth):(\d+)/iu, 2) || + filters.minBitDepth; filters.minFileSize = - getNthMatch(string, /(minfs|minfilesize):(\d+)/i, 2) || filters.minFileSize; + getNthMatch(string, /(minfs|minfilesize):(\d+)/iu, 2) || + filters.minFileSize; filters.minLength = - getNthMatch(string, /(minlen|minlength):(\d+)/i, 2) || filters.minLength; + getNthMatch(string, /(minlen|minlength):(\d+)/iu, 2) || filters.minLength; filters.minFilesInFolder = - getNthMatch(string, /(minfif|minfilesinfolder):(\d+)/i, 2) || + getNthMatch(string, /(minfif|minfilesinfolder):(\d+)/iu, 2) || filters.minFilesInFolder; - filters.isVBR = Boolean(/isvbr/i.test(string)); - filters.isCBR = Boolean(/iscbr/i.test(string)); - filters.isLossless = Boolean(/islossless/i.test(string)); - filters.isLossy = Boolean(/islossy/i.test(string)); + filters.isVBR = Boolean(/isvbr/iu.test(string)); + filters.isCBR = Boolean(/iscbr/iu.test(string)); + filters.isLossless = Boolean(/islossless/iu.test(string)); + filters.isLossy = Boolean(/islossy/iu.test(string)); const terms = string .toLowerCase() @@ -124,8 +128,8 @@ export const filterResponse = ({ return { ...response, files: [] }; } - const filterFiles = (files) => - files.filter((file) => { + const filterFiles = (filesToFilter) => + filesToFilter.filter((file) => { const { bitRate, size, diff --git a/src/web/src/lib/session.js b/src/web/src/lib/session.js index 01f2ab61..014b131c 100644 --- a/src/web/src/lib/session.js +++ b/src/web/src/lib/session.js @@ -1,9 +1,6 @@ -import { tokenKey, tokenPassthroughValue } from '../config'; +import { tokenPassthroughValue } from '../config'; import api from './api'; - -export const getToken = () => - sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey); -const setToken = (storage, token) => storage.setItem(tokenKey, token); +import { clearToken, getToken, setToken } from './token'; export const getSecurityEnabled = async () => { return (await api.get('/session/enabled')).data; @@ -16,8 +13,6 @@ export const enablePassthrough = () => { setToken(sessionStorage, tokenPassthroughValue); }; -export const isPassthroughEnabled = () => getToken() === tokenPassthroughValue; - export const isLoggedIn = () => { const token = getToken(); return ( @@ -33,8 +28,7 @@ export const login = async ({ username, password, rememberMe = false }) => { export const logout = () => { console.debug('removing token from local and session storage'); - localStorage.removeItem(tokenKey); - sessionStorage.removeItem(tokenKey); + clearToken(); }; export const check = async () => { diff --git a/src/web/src/lib/token.js b/src/web/src/lib/token.js new file mode 100644 index 00000000..db8d69fa --- /dev/null +++ b/src/web/src/lib/token.js @@ -0,0 +1,11 @@ +import { tokenKey, tokenPassthroughValue } from '../config'; + +export const getToken = () => + sessionStorage.getItem(tokenKey) || localStorage.getItem(tokenKey); +export const setToken = (storage, token) => storage.setItem(tokenKey, token); +export const clearToken = () => { + localStorage.removeItem(tokenKey); + sessionStorage.removeItem(tokenKey); +}; + +export const isPassthroughEnabled = () => getToken() === tokenPassthroughValue; diff --git a/src/web/src/lib/util.js b/src/web/src/lib/util.js index 1da9e864..99b16148 100644 --- a/src/web/src/lib/util.js +++ b/src/web/src/lib/util.js @@ -1,15 +1,15 @@ export const formatSeconds = (seconds) => { - if (isNaN(seconds)) return ''; + if (Number.isNaN(seconds)) return ''; const date = new Date(1_970, 0, 1); date.setSeconds(seconds); if (seconds >= 3_600) { - return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, '$1'); + return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/u, '$1'); } - return date.toTimeString().replace(/.*(\d{2}:\d{2}).*/, '$1'); + return date.toTimeString().replace(/.*(\d{2}:\d{2}).*/u, '$1'); }; -export const formatBytesAsUnit = (bytes, decimals = 2, unit) => { +export const formatBytesAsUnit = (bytes, unit, decimals = 2) => { if (unit === 'B') return bytes + ' ' + unit; const k = 1_024; @@ -75,7 +75,9 @@ export const formatAttributes = ({ }; export const sleep = (milliseconds) => { - return new Promise((resolve) => setTimeout(resolve, milliseconds)); + return new Promise((resolve) => { + setTimeout(resolve, milliseconds); + }); }; /* https://www.npmjs.com/package/js-file-download @@ -98,6 +100,7 @@ export const sleep = (milliseconds) => { */ export const downloadFile = (data, filename, mime) => { const blob = new Blob([data], { type: mime || 'application/octet-stream' }); + // eslint-disable-next-line no-negated-condition if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE workaround for "HTML7007: One or more blob URLs were // revoked by closing the blob for which they were created. diff --git a/src/web/src/lib/util.test.js b/src/web/src/lib/util.test.js index 0507cb56..9bf79fab 100644 --- a/src/web/src/lib/util.test.js +++ b/src/web/src/lib/util.test.js @@ -1,5 +1,7 @@ import * as utils from './util'; -test('converts bytes to specified unit', () => { - expect(utils.formatBytesAsUnit(1_234_567, 2, 'MB')).toBe(1.18); +describe('formatBytesAsUnit', () => { + it('converts bytes to specified unit', () => { + expect(utils.formatBytesAsUnit(1_234_567, 'MB', 2)).toBe(1.18); + }); }); |
