FileBrowser files can be tagged. A Tag icon is displayed on each file row in the browser.

This commit is contained in:
Roland 2023-04-01 11:52:41 -06:00
parent 655e944960
commit ae2b6daa33
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
29 changed files with 356 additions and 219 deletions

View file

@ -29,8 +29,7 @@ pre.wrap-text {
top: 4px;
right: 4px;
color: black;
background: #eee;
opacity: 0.8;
background: #ffffff;
padding: 0px 4px;
border-radius: 3px;
}

View file

@ -77,22 +77,19 @@ const router = createBrowserRouter(createRoutesFromElements(<Route
export default function App() {
const statusValue = useStatusInterval();
const tagsValue = useTags();
useEventsInterval();
return <ThemeWrapper>
<TagsContext.Provider value={tagsValue}>
<FilePreviewWrapper>
{/* Context and style to handle switching between mobile/computer. */}
<style>{mediaStyles}</style>
{/* Toasts can be on any page. */}
<SemanticToastContainer position='top-right'/>
<MediaContextProvider>
<StatusContext.Provider value={statusValue}>
<RouterProvider router={router}/>
</StatusContext.Provider>
</MediaContextProvider>
</FilePreviewWrapper>
</TagsContext.Provider>
<FilePreviewWrapper>
{/* Context and style to handle switching between mobile/computer. */}
<style>{mediaStyles}</style>
{/* Toasts can be on any page. */}
<SemanticToastContainer position='top-right'/>
<MediaContextProvider>
<StatusContext.Provider value={statusValue}>
<RouterProvider router={router}/>
</StatusContext.Provider>
</MediaContextProvider>
</FilePreviewWrapper>
</ThemeWrapper>
}

View file

@ -12,7 +12,7 @@ import {Divider, Icon, Message} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {refreshFiles} from "./api";
import _ from "lodash";
import {TagsDashboard} from "./Tags";
import {TagsDashboard, TagsProvider} from "./Tags";
function FlagsMessages({flags}) {
if (!flags) {

View file

@ -25,6 +25,7 @@ import {contrastingColor, HelpPopup} from "./components/Common";
import {Segment} from "./components/Theme";
import _ from "lodash";
import {HexColorPicker} from "react-colorful";
import {useRecurringTimeout} from "./hooks/customHooks";
export const TagsContext = React.createContext({
NameToTagLabel: null,
@ -117,6 +118,15 @@ export function useTags() {
return {tags, tagNames, NameToTagLabel, TagsGroup, TagsLinkGroup, fetchTags, findTagByName}
}
export const useTagsInterval = () => {
const tagsValue = useTags();
const {fetchTags} = tagsValue;
useRecurringTimeout(fetchTags, 10_000);
return tagsValue
}
function EditTagLabel({tag, onDelete, onEdit}) {
const {NameToTagLabel} = React.useContext(TagsContext);
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false);
@ -238,7 +248,7 @@ function EditTagsModal() {
</>
}
export function TagsModal({fileGroup, onClick}) {
export function AddTagsButton({fileGroup, afterTag}) {
const {tags: usedTags} = fileGroup;
const {tags: availableTags, TagsGroup} = React.useContext(TagsContext);
const [open, setOpen] = useState(false);
@ -248,10 +258,11 @@ export function TagsModal({fileGroup, onClick}) {
setLoading(true);
try {
await addTag(fileGroup, name);
if (onClick) {
await onClick();
}
console.debug('Added tag');
if (afterTag) {
console.debug('Calling afterTag');
await afterTag();
}
} finally {
setLoading(false);
}
@ -261,10 +272,11 @@ export function TagsModal({fileGroup, onClick}) {
setLoading(true);
try {
await removeTag(fileGroup, name);
if (onClick) {
await onClick();
}
console.debug('Removed tag');
if (afterTag) {
console.debug('Calling afterTag');
await afterTag();
}
} finally {
setLoading(false);
}
@ -312,7 +324,7 @@ export function TagsModal({fileGroup, onClick}) {
export const taggedImageLabel = {corner: 'left', icon: 'tag', color: 'green'};
export const TagsDisplay = ({fileGroup, onClick}) => {
const Display = ({fileGroup, afterTag}) => {
const {TagsLinkGroup} = React.useContext(TagsContext);
if (!fileGroup || !TagsLinkGroup) {
@ -322,7 +334,7 @@ export const TagsDisplay = ({fileGroup, onClick}) => {
return <Grid>
<Grid.Row>
<Grid.Column mobile={2} computer={1}>
<TagsModal fileGroup={fileGroup} onClick={onClick}/>
<AddTagsButton fileGroup={fileGroup} afterTag={afterTag}/>
</Grid.Column>
<Grid.Column mobile={13} computer={14}>
<TagsLinkGroup tagNames={fileGroup['tags']}/>
@ -334,7 +346,13 @@ export const TagsDisplay = ({fileGroup, onClick}) => {
</Grid>
}
export const TagsDashboard = () => {
export const TagsDisplay = ({fileGroup, afterTag, ...props}) => {
return <TagsProvider>
<Display fileGroup={fileGroup} afterTag={afterTag} {...props}/>
</TagsProvider>
}
const Dashboard = () => {
const {tagNames, TagsLinkGroup} = React.useContext(TagsContext);
let availableTagsGroup = <SLoader active inline/>;
@ -351,3 +369,17 @@ export const TagsDashboard = () => {
<EditTagsModal/>
</Segment>
}
export const TagsDashboard = () => {
return <TagsProvider>
<Dashboard/>
</TagsProvider>
}
export const TagsProvider = ({children}) => {
const value = useTagsInterval();
return <TagsContext.Provider value={value}>
{children}
</TagsContext.Provider>
}

View file

@ -681,9 +681,18 @@ export async function getTags() {
}
export async function addTag(fileGroup, name) {
const {id} = fileGroup;
const body = {tag_name: name};
const {id, primary_path, path} = fileGroup;
if (id) {
body['file_group_id'] = id;
} else if (primary_path) {
body['file_group_primary_path'] = primary_path;
} else if (path) {
body['file_group_primary_path'] = path;
}
const uri = `${API_URI}/files/tag`;
const body = {file_group_id: id, tag_name: name};
let response = await apiPost(uri, body);
if (response.status !== 201) {
console.error('Failed to add tag');
@ -691,9 +700,18 @@ export async function addTag(fileGroup, name) {
}
export async function removeTag(fileGroup, name) {
const {id} = fileGroup;
const body = {tag_name: name};
const {id, primary_path, path} = fileGroup;
if (id) {
body['file_group_id'] = id;
} else if (primary_path) {
body['file_group_primary_path'] = primary_path;
} else if (path) {
body['file_group_primary_path'] = path;
}
const uri = `${API_URI}/files/untag`;
const body = {file_group_id: id, tag_name: name};
let response = await apiPost(uri, body)
if (response.status !== 204) {
console.error('Failed to remove tag');
@ -740,3 +758,15 @@ export async function deleteTag(id, name) {
})
}
}
export async function fetchFile(path) {
const uri = `${API_URI}/files/file`;
const body = {file: path};
const response = await apiPost(uri, body);
if (response.status === 200) {
const content = await response.json();
return content['file'];
} else {
console.error('Unable to fetch file dict! See client logs.');
}
}

View file

@ -2,11 +2,12 @@ import React, {useContext, useEffect, useState} from "react";
import {Card, Container, IconGroup, Input, Modal, Pagination} from 'semantic-ui-react';
import {Link, NavLink, useNavigate} from "react-router-dom";
import Message from "semantic-ui-react/dist/commonjs/collections/Message";
import {useDirectories, useDownloaders, useHotspot, useSettings, useThrottle} from "../hooks/customHooks";
import {useDirectories, useHotspot, useSettings, useThrottle} from "../hooks/customHooks";
import {Media, StatusContext, ThemeContext} from "../contexts/contexts";
import {Button, CardIcon, darkTheme, Form, Header, Icon, lightTheme, Menu, Popup, Statistic} from "./Theme";
import {FilePreviewContext} from "./FilePreview";
import _ from "lodash";
import {killDownloads, startDownloads} from "../api";
export const API_URI = process.env && process.env.REACT_APP_API_URI ? process.env.REACT_APP_API_URI : `${window.location.protocol}//${window.location.host}/api`;
export const VIDEOS_API = `${API_URI}/videos`;
@ -20,16 +21,32 @@ export function Paginator({activePage, onPageChange, totalPages, showFirstAndLas
onPageChange(activePage);
}
return <Pagination
activePage={activePage}
boundaryRange={1}
onPageChange={handlePageChange}
size={size}
siblingRange={2}
totalPages={totalPages}
firstItem={showFirstAndLast ? undefined : null}
lastItem={showFirstAndLast ? undefined : null}
/>
return <>
<Media at='mobile'>
<Pagination
activePage={activePage}
boundaryRange={1}
onPageChange={handlePageChange}
size={size}
siblingRange={2}
totalPages={totalPages}
firstItem={showFirstAndLast ? undefined : null}
lastItem={showFirstAndLast ? undefined : null}
/>
</Media>
<Media greaterThanOrEqual='tablet'>
<Pagination
activePage={activePage}
boundaryRange={1}
onPageChange={handlePageChange}
size={size}
siblingRange={5}
totalPages={totalPages}
firstItem={showFirstAndLast ? undefined : null}
lastItem={showFirstAndLast ? undefined : null}
/>
</Media>
</>
}
export function divmod(x, y) {
@ -616,7 +633,19 @@ export function Toggle({label, checked, disabled, onChange, icon}) {
}
export function DisableDownloadsToggle() {
let {on, setDownloads} = useDownloaders();
const {status, fetchStatus} = React.useContext(StatusContext);
const {downloads} = status;
const setDownloads = async (enable) => {
if (enable) {
await startDownloads();
} else {
await killDownloads();
}
await fetchStatus();
}
const on = downloads && downloads['disabled'] === false;
return <Form>
<Toggle
label={on ? 'Downloading Enabled' : 'Downloading Disabled'}

View file

@ -1,58 +1,2 @@
import React from "react";
import {getByTestId, render, screen} from '@testing-library/react';
import {DisableDownloadsToggle} from "./Common";
import {useDownloaders} from "../hooks/customHooks";
import user from '@testing-library/user-event';
jest.mock('../hooks/customHooks', () => ({useDownloaders: jest.fn()}));
test('DownloadsToggle is off when loading', async () => {
useDownloaders.mockImplementation(() => ({on: null}));
const {container} = render(<DisableDownloadsToggle/>);
let toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Disabled while loading.
expect(toggle).toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is off if downloading is Off', async () => {
useDownloaders.mockImplementation(() => ({on: false}));
const {container} = render(<DisableDownloadsToggle/>);
const toggle = screen.getByRole('checkbox');
expect(toggle).not.toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "disabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Disabled');
});
test('DownloadsToggle is on if downloading is On', async () => {
useDownloaders.mockImplementation(() => ({on: true}));
const {container} = render(<DisableDownloadsToggle/>);
const toggle = screen.getByRole('checkbox');
expect(toggle).toBeChecked();
// Not disabled when loaded.
expect(toggle).not.toHaveClass('disabled');
// Text is "enabled" when downloading is On.
const label = getByTestId(container, 'toggle-label');
expect(label).toHaveTextContent('Downloading Enabled');
});
test('DownloadsToggle click', async () => {
const mock = jest.fn();
useDownloaders.mockImplementation(() => ({on: true, setDownloads: mock}));
render(<DisableDownloadsToggle/>);
// Downloads is toggled when DownloadsToggle is clicked.
const toggle = screen.getByRole('checkbox');
user.click(toggle);
expect(mock).toHaveBeenCalled();
expect(mock).toHaveBeenLastCalledWith(false);
})

View file

@ -1,12 +1,12 @@
import {Button, Icon, Placeholder} from "./Theme";
import {Checkbox, Confirm, PlaceholderLine, TableCell, TableFooter, TableHeaderCell, TableRow} from "semantic-ui-react";
import {FileIcon, humanFileSize} from "./Common";
import React from "react";
import {deleteFile} from "../api";
import React, {useEffect} from "react";
import {deleteFile, fetchFile} from "../api";
import _ from 'lodash';
import {SortableTable} from "./SortableTable";
import {useBrowseFiles} from "../hooks/customHooks";
import {DirectoryRefreshButton, FilesRefreshButton} from "./Files";
import {DirectoryRefreshButton, FileRowTagIcon, FilesRefreshButton} from "./Files";
import {FilePreviewContext} from "./FilePreview";
function depthIndentation(path) {
@ -58,6 +58,7 @@ function File({file, onFileClick, selectedPath, onSelect}) {
</TableCell>
<TableCell onClick={() => onFileClick(file)} className='file-path'>
{depthIndentation(path)}
<FileRowTagIcon file={file}/>
{/*null size to make icon the correct size*/}
<FileIcon file={file} size={null}/>
{name}
@ -96,11 +97,20 @@ export function FileBrowser() {
const {browseFiles, openFolders, setOpenFolders, fetchFiles} = useBrowseFiles();
const headers = [{key: 'select', text: ''}, {
key: 'path', text: 'Path', sortBy: i => i['path'].toLowerCase()
}, {key: 'size', text: 'Size', sortBy: 'size'},];
const headers = [
{key: 'select', text: ''},
{key: 'path', text: 'Path', sortBy: i => i['path'].toLowerCase()},
{key: 'size', text: 'Size', sortBy: 'size'},
];
const {setPreviewFile} = React.useContext(FilePreviewContext);
const {setPreviewFile, setCallbacks} = React.useContext(FilePreviewContext);
useEffect(() => {
// Fetch files after tagging.
setCallbacks([fetchFiles]);
return () => setCallbacks(null);
}, []);
const onSelect = (path) => {
if (path.endsWith('/') && selectedPath === path) {

View file

@ -10,9 +10,10 @@ import {
ModalContent,
ModalHeader
} from "semantic-ui-react";
import {TagsDisplay} from "../Tags";
import {TagsDisplay, TagsProvider} from "../Tags";
import {Media} from "../contexts/contexts";
import {encodeMediaPath} from "./Common";
import {fetchFile} from "../api";
function getMediaPathURL(previewFile) {
if (previewFile['primary_path']) {
@ -126,7 +127,11 @@ function getAudioModal(previewFile) {
}
export const FilePreviewContext = React.createContext({
previewFile: null, setPreviewFile: null, previewModal: null, setPreviewModal: null,
previewFile: null,
setPreviewFile: null,
previewModal: null,
setPreviewModal: null,
setCallbacks: null,
});
const MAXIMUM_TEXT_SIZE = 5_000_000;
@ -134,15 +139,38 @@ const MAXIMUM_TEXT_SIZE = 5_000_000;
export function FilePreviewWrapper({children}) {
const [previewFile, setPreviewFile] = React.useState(null);
const [previewModal, setPreviewModal] = React.useState(null);
const [callbacks, setCallbacks] = React.useState(null);
const value = {
previewFile, setPreviewFile, previewModal, setPreviewModal,
const localFetchFile = async () => {
// Get the file again with its Tags.
const {path, primary_path} = previewFile;
try {
const file = await fetchFile(primary_path ?? path);
setPreviewFile(file);
} finally {
await handleCallbacks();
}
};
const handleClose = () => {
setPreviewModal(null);
setPreviewFile(null);
}
const handleCallbacks = async () => {
for (const callbacksKey in callbacks) {
try {
await callbacks[callbacksKey]();
} catch (e) {
console.error(e);
}
}
}
function setModalContent(content, url, downloadURL) {
const openButton = <SButton color='blue' as='a' href={url}>Open</SButton>;
const closeButton = <SButton onClick={() => setPreviewFile(null)}>Close</SButton>;
const tagsDisplay = <TagsDisplay fileGroup={previewFile}/>;
const closeButton = <SButton onClick={handleClose}>Close</SButton>;
const tagsDisplay = <TagsDisplay fileGroup={previewFile} afterTag={localFetchFile}/>;
let downloadButton;
if (downloadURL) {
downloadButton = <SButton color='yellow' as='a' href={downloadURL} floated='left'>
@ -153,7 +181,7 @@ export function FilePreviewWrapper({children}) {
setPreviewModal(<Modal closeIcon
size='fullscreen'
open={true}
onClose={() => setPreviewModal(null)}
onClose={handleClose}
>
{content}
<ModalActions>
@ -222,6 +250,8 @@ export function FilePreviewWrapper({children}) {
}
}, [previewFile]);
const value = {previewFile, setPreviewFile, previewModal, setPreviewModal, setCallbacks};
return <FilePreviewContext.Provider value={value}>
{children}
{previewModal}

View file

@ -210,7 +210,7 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
</Segment>
<Segment>
<TagsDisplay fileGroup={videoFile} onClick={fetchVideo}/>
<TagsDisplay fileGroup={videoFile} afterTag={fetchVideo}/>
</Segment>
<Tab menu={tabMenu} panes={tabPanes}/>

View file

@ -531,37 +531,6 @@ export const useDownloads = () => {
return {onceDownloads, recurringDownloads, fetchDownloads}
}
export const useDownloaders = () => {
const [on, setOn] = useState(null);
const [downloaders, setDownloaders] = useState(null);
const fetchDownloaders = async () => {
try {
let data = await getDownloaders();
setDownloaders(data['downloaders']);
setOn(!data['manager_disabled']);
} catch (e) {
console.error(e);
}
}
useEffect(() => {
fetchDownloaders();
}, []);
const localSetDownloads = async (on) => {
setOn(null);
if (on) {
await startDownloads();
} else {
await killDownloads();
}
await fetchDownloaders();
}
return {on, setOn, downloaders, setDownloads: localSetDownloads};
}
export const useThrottle = () => {
const [on, setOn] = useState(null);
@ -669,12 +638,6 @@ export const useStatus = () => {
setStatus(s);
} catch (e) {
console.error(e);
toast({
type: 'error',
title: 'Unexpected server response',
description: 'Could not get server status',
time: 5000,
});
}
}