Use easy-peasy to store file state data

This commit is contained in:
Dane Everitt 2019-08-04 14:58:31 -07:00
parent 918e0e2947
commit 5f59210c85
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
11 changed files with 110 additions and 34 deletions

View File

@ -27,6 +27,7 @@
"sockette": "^2.0.6",
"styled-components": "^4.3.2",
"use-react-router": "^1.0.7",
"uuid": "^3.3.2",
"ws-wrapper": "^2.0.0",
"xterm": "^3.14.4",
"xterm-addon-attach": "^0.1.0",
@ -50,6 +51,7 @@
"@types/react-router-dom": "^4.3.3",
"@types/react-transition-group": "^2.9.2",
"@types/styled-components": "^4.1.18",
"@types/uuid": "^3.4.5",
"@types/webpack-env": "^1.13.6",
"@types/yup": "^0.26.17",
"@typescript-eslint/eslint-plugin": "^1.10.1",

View File

@ -1,6 +1,8 @@
import http from '@/api/http';
import v4 from 'uuid/v4';
export interface FileObject {
uuid: string;
name: string;
mode: string;
size: number;
@ -18,6 +20,7 @@ export default (uuid: string, directory?: string): Promise<FileObject[]> => {
params: { directory },
})
.then(response => resolve((response.data.data || []).map((item: any): FileObject => ({
uuid: v4(),
name: item.attributes.name,
mode: item.attributes.mode,
size: Number(item.attributes.size),

View File

@ -8,10 +8,11 @@ interface Props {
name: string;
label?: string;
description?: string;
autoFocus?: boolean;
validate?: (value: any) => undefined | string | Promise<any>;
}
export default ({ id, type, name, label, description, validate }: Props) => (
export default ({ id, type, name, label, description, autoFocus, validate }: Props) => (
<Field name={name} validate={validate}>
{
({ field, form: { errors, touched } }: FieldProps) => (
@ -23,6 +24,7 @@ export default ({ id, type, name, label, description, validate }: Props) => (
id={id}
type={type}
{...field}
autoFocus={autoFocus}
className={classNames('input-dark', {
error: touched[field.name] && errors[field.name],
})}

View File

@ -1,7 +1,6 @@
import React, { createRef, useEffect, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faEllipsisH } from '@fortawesome/free-solid-svg-icons/faEllipsisH';
import { FileObject } from '@/api/server/files/loadDirectory';
import { CSSTransition } from 'react-transition-group';
import { faPencilAlt } from '@fortawesome/free-solid-svg-icons/faPencilAlt';
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons/faTrashAlt';
@ -9,15 +8,21 @@ import { faFileDownload } from '@fortawesome/free-solid-svg-icons/faFileDownload
import { faCopy } from '@fortawesome/free-solid-svg-icons/faCopy';
import { faLevelUpAlt } from '@fortawesome/free-solid-svg-icons/faLevelUpAlt';
import RenameFileModal from '@/components/server/files/RenameFileModal';
import { ServerContext } from '@/state/server';
type ModalType = 'rename' | 'move';
export default ({ file }: { file: FileObject }) => {
export default ({ uuid }: { uuid: string }) => {
const menu = createRef<HTMLDivElement>();
const [ visible, setVisible ] = useState(false);
const [ modal, setModal ] = useState<ModalType | null>(null);
const [ posX, setPosX ] = useState(0);
const file = ServerContext.useStoreState(state => state.files.contents.find(file => file.uuid === uuid));
if (!file) {
return null;
}
const windowListener = (e: MouseEvent) => {
if (e.button === 2 || !visible || !menu.current) {
return;

View File

@ -1,7 +1,6 @@
import React, { useEffect, useState } from 'react';
import FlashMessageRender from '@/components/FlashMessageRender';
import { ServerContext } from '@/state/server';
import loadDirectory, { FileObject } from '@/api/server/files/loadDirectory';
import { Actions, useStoreActions } from 'easy-peasy';
import { ApplicationStore } from '@/state';
import { httpErrorToHuman } from '@/api/http';
@ -9,22 +8,21 @@ import { CSSTransition } from 'react-transition-group';
import { Link } from 'react-router-dom';
import Spinner from '@/components/elements/Spinner';
import FileObjectRow from '@/components/server/files/FileObjectRow';
import { getDirectoryFromHash } from '@/helpers';
export default () => {
const [ loading, setLoading ] = useState(true);
const [ files, setFiles ] = useState<FileObject[]>([]);
const server = ServerContext.useStoreState(state => state.server.data!);
const { addError, clearFlashes } = useStoreActions((actions: Actions<ApplicationStore>) => actions.flashes);
const { contents: files } = ServerContext.useStoreState(state => state.files);
const getDirectoryContents = ServerContext.useStoreActions(actions => actions.files.getDirectoryContents);
const urlDirectory = window.location.hash.replace(/^#(\/)+/, '/');
const load = () => {
setLoading(true);
clearFlashes();
loadDirectory(server.uuid, getDirectoryFromHash())
.then(files => {
setFiles(files);
setLoading(false);
})
getDirectoryContents(urlDirectory)
.then(() => setLoading(false))
.catch(error => {
if (error.response && error.response.status === 404) {
window.location.hash = '#/';
@ -36,7 +34,7 @@ export default () => {
});
};
const breadcrumbs = (): { name: string; path?: string }[] => getDirectoryFromHash().split('/')
const breadcrumbs = (): { name: string; path?: string }[] => urlDirectory.split('/')
.filter(directory => !!directory)
.map((directory, index, dirs) => {
if (index === dirs.length - 1) {
@ -86,7 +84,7 @@ export default () => {
<div>
{
files.map(file => (
<FileObjectRow key={file.name} directory={getDirectoryFromHash()} file={file}/>
<FileObjectRow key={file.name} file={file}/>
))
}
</div>

View File

@ -9,8 +9,11 @@ import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';
import React from 'react';
import { FileObject } from '@/api/server/files/loadDirectory';
import FileDropdownMenu from '@/components/server/files/FileDropdownMenu';
import { ServerContext } from '@/state/server';
export default ({ file }: { file: FileObject }) => {
const directory = ServerContext.useStoreState(state => state.files.directory);
export default ({ file, directory }: { file: FileObject; directory: string }) => {
return (
<a
key={file.name}
@ -50,7 +53,7 @@ export default ({ file, directory }: { file: FileObject; directory: string }) =>
distanceInWordsToNow(file.modifiedAt, { includeSeconds: true })
}
</div>
<FileDropdownMenu file={file}/>
<FileDropdownMenu uuid={file.uuid}/>
</a>
);
};

View File

@ -1,26 +1,32 @@
import React from 'react';
import Modal, { RequiredModalProps } from '@/components/elements/Modal';
import { Form, Formik, FormikActions } from 'formik';
import { FileObject } from '@/api/server/files/loadDirectory';
import Field from '@/components/elements/Field';
import { getDirectoryFromHash } from '@/helpers';
import { join } from 'path';
import renameFile from '@/api/server/files/renameFile';
import { ServerContext } from '@/state/server';
import { FileObject } from '@/api/server/files/loadDirectory';
interface FormikValues {
name: string;
}
export default ({ file, ...props }: RequiredModalProps & { file: FileObject }) => {
const server = ServerContext.useStoreState(state => state.server.data!);
type Props = RequiredModalProps & { file: FileObject };
export default ({ file, ...props }: Props) => {
const uuid = ServerContext.useStoreState(state => state.server.data!.uuid);
const directory = ServerContext.useStoreState(state => state.files.directory);
const pushFile = ServerContext.useStoreActions(actions => actions.files.pushFile);
const submit = (values: FormikValues, { setSubmitting }: FormikActions<FormikValues>) => {
const renameFrom = join(getDirectoryFromHash(), file.name);
const renameTo = join(getDirectoryFromHash(), values.name);
const renameFrom = join(directory, file.name);
const renameTo = join(directory, values.name);
renameFile(server.uuid, { renameFrom, renameTo })
.then(() => props.onDismissed())
renameFile(uuid, { renameFrom, renameTo })
.then(() => {
pushFile({ ...file, name: values.name });
props.onDismissed();
})
.catch(error => {
setSubmitting(false);
console.error(error);
@ -41,6 +47,7 @@ export default ({ file, ...props }: RequiredModalProps & { file: FileObject }) =
name={'name'}
label={'File Name'}
description={'Enter the new name of this file or folder.'}
autoFocus={true}
/>
<div className={'mt-6 text-right'}>
<button className={'btn btn-sm btn-primary'}>

View File

@ -4,10 +4,3 @@ export function bytesToHuman (bytes: number): string {
// @ts-ignore
return `${(bytes / Math.pow(1000, i)).toFixed(2) * 1} ${['Bytes', 'kB', 'MB', 'GB', 'TB'][i]}`;
}
/**
* Returns the current directory for the given window.
*/
export function getDirectoryFromHash (): string {
return window.location.hash.replace(/^#(\/)+/, '/');
}

View File

@ -0,0 +1,54 @@
import loadDirectory, { FileObject } from '@/api/server/files/loadDirectory';
import { action, Action, thunk, Thunk } from 'easy-peasy';
import { ServerStore } from '@/state/server/index';
export interface ServerFileStore {
directory: string;
contents: FileObject[];
getDirectoryContents: Thunk<ServerFileStore, string, {}, ServerStore, Promise<void>>;
setContents: Action<ServerFileStore, FileObject[]>;
pushFile: Action<ServerFileStore, FileObject>;
removeFile: Action<ServerFileStore, string>;
setDirectory: Action<ServerFileStore, string>;
}
const files: ServerFileStore = {
directory: '',
contents: [],
getDirectoryContents: thunk(async (actions, payload, { getStoreState }) => {
const server = getStoreState().server.data;
if (!server) {
return;
}
const contents = await loadDirectory(server.uuid, payload);
actions.setDirectory(payload);
actions.setContents(contents);
}),
setContents: action((state, payload) => {
state.contents = payload;
}),
pushFile: action((state, payload) => {
const matchIndex = state.contents.findIndex(file => file.uuid === payload.uuid);
if (matchIndex < 0) {
state.contents = state.contents.concat(payload);
return;
}
state.contents[matchIndex] = payload;
}),
removeFile: action((state, payload) => {
state.contents = state.contents.filter(file => file.uuid !== payload);
}),
setDirectory: action((state, payload) => {
state.directory = payload;
}),
};
export default files;

View File

@ -2,12 +2,13 @@ import getServer, { Server } from '@/api/server/getServer';
import { action, Action, createContextStore, thunk, Thunk } from 'easy-peasy';
import socket, { SocketStore } from './socket';
import { ServerDatabase } from '@/api/server/getServerDatabases';
import files, { ServerFileStore } from '@/state/server/files';
export type ServerStatus = 'offline' | 'starting' | 'stopping' | 'running';
interface ServerDataStore {
data?: Server;
getServer: Thunk<ServerDataStore, string, {}, any, Promise<void>>;
getServer: Thunk<ServerDataStore, string, {}, ServerStore, Promise<void>>;
setServer: Action<ServerDataStore, Server>;
}
@ -49,13 +50,14 @@ const databases: ServerDatabaseStore = {
state.items = state.items.filter(item => item.id !== payload.id).concat(payload);
}),
removeDatabase: action((state, payload) => {
state.items = state.items.filter(item => item.id !== payload.id);
state.items = state.items.filter(item => item.id !== payload.id);
}),
};
export interface ServerStore {
server: ServerDataStore;
databases: ServerDatabaseStore;
files: ServerFileStore;
socket: SocketStore;
status: ServerStatusStore;
clearServerState: Action<ServerStore>;
@ -66,6 +68,7 @@ export const ServerContext = createContextStore<ServerStore>({
socket,
status,
databases,
files,
clearServerState: action(state => {
state.server.data = undefined;
state.databases.items = [];

View File

@ -857,7 +857,7 @@
version "4.14.119"
resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.119.tgz#be847e5f4bc3e35e46d041c394ead8b603ad8b39"
"@types/node@^12.6.9":
"@types/node@*", "@types/node@^12.6.9":
version "12.6.9"
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.6.9.tgz#ffeee23afdc19ab16e979338e7b536fdebbbaeaf"
@ -929,6 +929,12 @@
"@types/react-native" "*"
csstype "^2.2.0"
"@types/uuid@^3.4.5":
version "3.4.5"
resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.5.tgz#d4dc10785b497a1474eae0ba7f0cb09c0ddfd6eb"
dependencies:
"@types/node" "*"
"@types/webpack-env@^1.13.6":
version "1.13.6"
resolved "http://registry.npmjs.org/@types/webpack-env/-/webpack-env-1.13.6.tgz#128d1685a7c34d31ed17010fc87d6a12c1de6976"