directory preview fixes (#130)

- Set all cols of navigation row(first row) to - except the first col
- Fixed the issue where it scrolls right on load or when you click back
from the file preview
- Use OverlayScrollbars
This commit is contained in:
Red J Adaya 2024-07-26 12:14:21 +08:00 committed by GitHub
parent 127b2bb9bf
commit 2fea8e0a68
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 146 additions and 130 deletions

9
frontend/app/mixins.less Normal file
View File

@ -0,0 +1,9 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
.ellipsis() {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

View File

@ -1,15 +1,12 @@
// Copyright 2024, Command Line Inc. // Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
@import "../mixins.less";
.csv-view { .csv-view {
opacity: 0; /* Start with an opacity of 0, meaning it's invisible */ opacity: 0; /* Start with an opacity of 0, meaning it's invisible */
.ellipsis() { .ellipsis();
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
overflow-x: auto; overflow-x: auto;
overflow-y: hidden; overflow-y: hidden;

View File

@ -1,9 +1,13 @@
// Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
@import "../mixins.less";
.dir-table-container { .dir-table-container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
.dir-table { .dir-table {
overflow-x: auto;
height: 100%; height: 100%;
min-width: 600px; min-width: 600px;
--col-size-size: 0.2rem; --col-size-size: 0.2rem;
@ -76,6 +80,7 @@
flex: 1 1 auto; flex: 1 1 auto;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
overflow: hidden;
.dir-table-body-search-display { .dir-table-body-search-display {
display: flex; display: flex;
border-radius: 3px; border-radius: 3px;
@ -89,8 +94,6 @@
.dir-table-body-scroll-box { .dir-table-body-scroll-box {
position: relative; position: relative;
overflow-y: auto;
overflow-x: auto;
.dummy { .dummy {
position: absolute; position: absolute;
visibility: hidden; visibility: hidden;
@ -98,7 +101,7 @@
.dir-table-body-row { .dir-table-body-row {
display: flex; display: flex;
align-items: center; align-items: center;
border-radius: 6px; border-radius: 5px;
padding: 0 6px; padding: 0 6px;
&.focused { &.focused {
@ -156,12 +159,16 @@
margin-right: 12px; margin-right: 12px;
} }
.dir-table-type {
.ellipsis();
}
.dir-table-modestr { .dir-table-modestr {
font-family: Hack; font-family: Hack;
} }
&:has(.dir-table-name) { &:has(.dir-table-name) {
text-overflow: ellipsis; .ellipsis();
} }
.dir-table-name { .dir-table-name {
font-weight: 500; font-weight: 500;

View File

@ -1,6 +1,9 @@
// Copyright 2024, Command Line Inc. // Copyright 2024, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import { useHeight } from "@/app/hook/useHeight";
import { ContextMenuModel } from "@/app/store/contextmenu";
import { atoms, createBlock, getApi } from "@/app/store/global";
import * as services from "@/store/services"; import * as services from "@/store/services";
import * as keyutil from "@/util/keyutil"; import * as keyutil from "@/util/keyutil";
import * as util from "@/util/util"; import * as util from "@/util/util";
@ -18,10 +21,10 @@ import {
import clsx from "clsx"; import clsx from "clsx";
import dayjs from "dayjs"; import dayjs from "dayjs";
import * as jotai from "jotai"; import * as jotai from "jotai";
import React from "react"; import { OverlayScrollbarsComponent } from "overlayscrollbars-react";
import { ContextMenuModel } from "../store/contextmenu"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { atoms, createBlock, getApi } from "../store/global";
import { OverlayScrollbars } from "overlayscrollbars";
import "./directorypreview.less"; import "./directorypreview.less";
interface DirectoryTableProps { interface DirectoryTableProps {
@ -68,30 +71,9 @@ function getBestUnit(bytes: number, si: boolean = false, sigfig: number = 3): st
return `${parseFloat(currentValue.toPrecision(sigfig))}${displaySuffixes[currentUnit]}`; return `${parseFloat(currentValue.toPrecision(sigfig))}${displaySuffixes[currentUnit]}`;
} }
function getSpecificUnit(bytes: number, suffix: string): string {
if (bytes < 0) {
return "-";
}
const divisors = new Map([
["B", 1],
["kB", 1e3],
["MB", 1e6],
["GB", 1e9],
["TB", 1e12],
["KiB", 0x400],
["MiB", 0x400 ** 2],
["GiB", 0x400 ** 3],
["TiB", 0x400 ** 4],
]);
const divisor: number = divisors[suffix] ?? 1;
return `${bytes / divisor} ${displaySuffixes[suffix]}`;
}
function getLastModifiedTime(unixMillis: number, column: Column<FileInfo, number>): string { function getLastModifiedTime(unixMillis: number, column: Column<FileInfo, number>): string {
let fileDatetime = dayjs(new Date(unixMillis)); const fileDatetime = dayjs(new Date(unixMillis));
let nowDatetime = dayjs(new Date()); const nowDatetime = dayjs(new Date());
let datePortion: string; let datePortion: string;
if (nowDatetime.isSame(fileDatetime, "date")) { if (nowDatetime.isSame(fileDatetime, "date")) {
@ -136,9 +118,6 @@ function getSortIcon(sortType: string | boolean): React.ReactNode {
} }
function cleanMimetype(input: string): string { function cleanMimetype(input: string): string {
if (input == "") {
return "-";
}
const truncated = input.split(";")[0]; const truncated = input.split(";")[0];
return truncated.trim(); return truncated.trim();
} }
@ -153,8 +132,8 @@ function DirectoryTable({
setSelectedPath, setSelectedPath,
setRefreshVersion, setRefreshVersion,
}: DirectoryTableProps) { }: DirectoryTableProps) {
let settings = jotai.useAtomValue(atoms.settingsConfigAtom); const settings = jotai.useAtomValue(atoms.settingsConfigAtom);
const getIconFromMimeType = React.useCallback( const getIconFromMimeType = useCallback(
(mimeType: string): string => { (mimeType: string): string => {
while (mimeType.length > 0) { while (mimeType.length > 0) {
let icon = settings.mimetypes?.[mimeType]?.icon ?? null; let icon = settings.mimetypes?.[mimeType]?.icon ?? null;
@ -167,14 +146,14 @@ function DirectoryTable({
}, },
[settings.mimetypes] [settings.mimetypes]
); );
const getIconColor = React.useCallback( const getIconColor = useCallback(
(mimeType: string): string => { (mimeType: string): string => {
let iconColor = settings.mimetypes?.[mimeType]?.color ?? "inherit"; let iconColor = settings.mimetypes?.[mimeType]?.color ?? "inherit";
return iconColor; return iconColor;
}, },
[settings.mimetypes] [settings.mimetypes]
); );
const columns = React.useMemo( const columns = useMemo(
() => [ () => [
columnHelper.accessor("mimetype", { columnHelper.accessor("mimetype", {
cell: (info) => ( cell: (info) => (
@ -221,8 +200,8 @@ function DirectoryTable({
columnHelper.accessor("mimetype", { columnHelper.accessor("mimetype", {
cell: (info) => <span className="dir-table-type">{cleanMimetype(info.getValue() ?? "")}</span>, cell: (info) => <span className="dir-table-type">{cleanMimetype(info.getValue() ?? "")}</span>,
header: () => <span className="dir-table-head-type">Type</span>, header: () => <span className="dir-table-head-type">Type</span>,
size: 67, size: 97,
minSize: 67, minSize: 97,
sortingFn: "alphanumeric", sortingFn: "alphanumeric",
}), }),
columnHelper.accessor("path", {}), columnHelper.accessor("path", {}),
@ -256,12 +235,12 @@ function DirectoryTable({
enableSortingRemoval: false, enableSortingRemoval: false,
}); });
React.useEffect(() => { useEffect(() => {
setSelectedPath((table.getSortedRowModel()?.flatRows[focusIndex]?.getValue("path") as string) ?? null); setSelectedPath((table.getSortedRowModel()?.flatRows[focusIndex]?.getValue("path") as string) ?? null);
}, [table, focusIndex, data]); }, [table, focusIndex, data]);
React.useEffect(() => { useEffect(() => {
let rows = table.getRowModel()?.flatRows; const rows = table.getRowModel()?.flatRows;
for (const row of rows) { for (const row of rows) {
if (row.getValue("name") == "..") { if (row.getValue("name") == "..") {
row.pin("top"); row.pin("top");
@ -269,7 +248,7 @@ function DirectoryTable({
} }
} }
}, [data]); }, [data]);
const columnSizeVars = React.useMemo(() => { const columnSizeVars = useMemo(() => {
const headers = table.getFlatHeaders(); const headers = table.getFlatHeaders();
const colSizes: { [key: string]: number } = {}; const colSizes: { [key: string]: number } = {};
for (let i = 0; i < headers.length; i++) { for (let i = 0; i < headers.length; i++) {
@ -364,73 +343,88 @@ function TableBody({
setSelectedPath, setSelectedPath,
setRefreshVersion, setRefreshVersion,
}: TableBodyProps) { }: TableBodyProps) {
const dummyLineRef = React.useRef<HTMLDivElement>(null); const [bodyHeight, setBodyHeight] = useState(0);
const parentRef = React.useRef<HTMLDivElement>(null);
const warningBoxRef = React.useRef<HTMLDivElement>(null);
const [bodyHeight, setBodyHeight] = React.useState(0);
const [containerHeight, setContainerHeight] = React.useState(0);
React.useEffect(() => { const dummyLineRef = useRef<HTMLDivElement>(null);
if (parentRef.current == null) { const parentRef = useRef<HTMLDivElement>(null);
return; const warningBoxRef = useRef<HTMLDivElement>(null);
} const osInstanceRef = useRef<OverlayScrollbars>(null);
const resizeObserver = new ResizeObserver(() => { const rowRefs = useRef<HTMLDivElement[]>([]);
setContainerHeight(parentRef.current.getBoundingClientRect().height); // 17 is height of breadcrumb
});
resizeObserver.observe(parentRef.current);
return () => resizeObserver.disconnect(); const parentHeight = useHeight(parentRef);
}, []);
React.useEffect(() => { useEffect(() => {
if (dummyLineRef.current && data && parentRef.current) { if (dummyLineRef.current && data && parentRef.current) {
const rowHeight = dummyLineRef.current.offsetHeight; const rowHeight = dummyLineRef.current.offsetHeight;
const fullTBodyHeight = rowHeight * data.length; const fullTBodyHeight = rowHeight * data.length;
const warningBoxHeight = warningBoxRef.current?.offsetHeight ?? 0; const warningBoxHeight = warningBoxRef.current?.offsetHeight ?? 0;
const maxHeight = containerHeight - 1; // i don't know why, but the -1 makes the resize work const maxHeightLessHeader = parentHeight - warningBoxHeight;
const maxHeightLessHeader = maxHeight - warningBoxHeight;
const tbodyHeight = Math.min(maxHeightLessHeader, fullTBodyHeight); const tbodyHeight = Math.min(maxHeightLessHeader, fullTBodyHeight);
setBodyHeight(tbodyHeight); setBodyHeight(tbodyHeight);
} }
}, [data, containerHeight]); }, [data, parentHeight]);
const handleFileContextMenu = React.useCallback( useEffect(() => {
(e: React.MouseEvent<HTMLDivElement>, path: string) => { if (focusIndex !== null && rowRefs.current[focusIndex] && parentRef.current) {
const viewport = osInstanceRef.current.elements().viewport;
const viewportHeight = viewport.offsetHeight;
const rowElement = rowRefs.current[focusIndex];
const rowRect = rowElement.getBoundingClientRect();
const parentRect = parentRef.current.getBoundingClientRect();
const viewportScrollTop = viewport.scrollTop;
const rowTopRelativeToViewport = rowRect.top - parentRect.top + viewportScrollTop;
const rowBottomRelativeToViewport = rowRect.bottom - parentRect.top + viewportScrollTop;
if (rowTopRelativeToViewport < viewportScrollTop) {
// Row is above the visible area
viewport.scrollTo({ top: rowTopRelativeToViewport });
} else if (rowBottomRelativeToViewport > viewportScrollTop + viewportHeight) {
// Row is below the visible area
viewport.scrollTo({ top: rowBottomRelativeToViewport - viewportHeight });
}
}
}, [focusIndex, parentHeight]);
const handleFileContextMenu = useCallback(
(e, path) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
let menu: ContextMenuItem[] = []; const menu = [
menu.push({ {
label: "Open in New Block", label: "Open in New Block",
click: async () => { click: async () => {
const blockDef = { const blockDef = {
view: "preview", view: "preview",
meta: { file: path }, meta: { file: path },
}; };
await createBlock(blockDef); await createBlock(blockDef);
},
}, },
}); {
menu.push({ label: "Delete File",
label: "Delete File", click: async () => {
click: async () => { await services.FileService.DeleteFile(path).catch((e) => console.log(e));
await services.FileService.DeleteFile(path).catch((e) => console.log(e)); //todo these errors need a popup setRefreshVersion((current) => current + 1);
setRefreshVersion((current) => current + 1); },
}, },
}); {
menu.push({ label: "Download File",
label: "Download File", click: async () => {
click: async () => { getApi().downloadFile(path);
getApi().downloadFile(path); },
}, },
}); ];
ContextMenuModel.showContextMenu(menu, e); ContextMenuModel.showContextMenu(menu, e);
}, },
[setRefreshVersion] [setRefreshVersion]
); );
const displayRow = React.useCallback( const displayRow = useCallback(
(row: Row<FileInfo>, idx: number) => ( (row: Row<FileInfo>, idx: number) => (
<div <div
ref={(el) => (rowRefs.current[idx] = el)}
className={clsx("dir-table-body-row", { focused: focusIndex === idx })} className={clsx("dir-table-body-row", { focused: focusIndex === idx })}
key={row.id} key={row.id}
onDoubleClick={() => { onDoubleClick={() => {
@ -439,42 +433,49 @@ function TableBody({
setSearch(""); setSearch("");
}} }}
onClick={() => setFocusIndex(idx)} onClick={() => setFocusIndex(idx)}
onContextMenu={(e) => handleFileContextMenu(e, row.getValue("path") as string)} onContextMenu={(e) => handleFileContextMenu(e, row.getValue("path"))}
> >
{row.getVisibleCells().map((cell) => { {row.getVisibleCells().map((cell) => (
return ( <div
<div className={clsx("dir-table-body-cell", "col-" + cell.column.id)}
className={clsx("dir-table-body-cell", "col-" + cell.column.id)} key={cell.id}
key={cell.id} style={{ width: `calc(var(--col-${cell.column.id}-size) * 1px)` }}
style={{ width: `calc(var(--col-${cell.column.id}-size) * 1px)` }} >
> {flexRender(cell.column.columnDef.cell, cell.getContext())}
{flexRender(cell.column.columnDef.cell, cell.getContext())} </div>
</div> ))}
);
})}
</div> </div>
), ),
[setSearch, setFileName, handleFileContextMenu, setFocusIndex, focusIndex] [setSearch, setFileName, handleFileContextMenu, setFocusIndex, focusIndex]
); );
const handleScrollbarInitialized = (instance) => {
osInstanceRef.current = instance;
};
return ( return (
<div className="dir-table-body" ref={parentRef}> <div className="dir-table-body" ref={parentRef}>
{search == "" || ( {search !== "" && (
<div className="dir-table-body-search-display" ref={warningBoxRef}> <div className="dir-table-body-search-display" ref={warningBoxRef}>
<span>Searching for "{search}"</span> <span>Searching for "{search}"</span>
<div className="search-display-close-button dir-table-button" onClick={() => setSearch("")}> <div className="search-display-close-button dir-table-button" onClick={() => setSearch("")}>
<i className="fa-solid fa-xmark" /> <i className="fa-solid fa-xmark" />
<input type="text" value={search} onChange={() => {}}></input> <input type="text" value={search} onChange={() => {}} />
</div> </div>
</div> </div>
)} )}
<div className="dir-table-body-scroll-box" style={{ height: bodyHeight }}> <OverlayScrollbarsComponent
<div className="dummy dir-table-body-row" ref={dummyLineRef}> options={{ scrollbars: { autoHide: "leave" } }}
<div className="dir-table-body-cell">dummy-data</div> events={{ initialized: handleScrollbarInitialized }}
>
<div className="dir-table-body-scroll-box" style={{ height: bodyHeight }}>
<div className="dummy dir-table-body-row" ref={dummyLineRef}>
<div className="dir-table-body-cell">dummy-data</div>
</div>
{table.getTopRows().map(displayRow)}
{table.getCenterRows().map((row, idx) => displayRow(row, idx + table.getTopRows().length))}
</div> </div>
{table.getTopRows().map(displayRow)} </OverlayScrollbarsComponent>
{table.getCenterRows().map((row, idx) => displayRow(row, idx + table.getTopRows().length))}
</div>
</div> </div>
); );
} }
@ -490,16 +491,16 @@ interface DirectoryPreviewProps {
} }
function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) { function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
const [searchText, setSearchText] = React.useState(""); const [searchText, setSearchText] = useState("");
const [focusIndex, setFocusIndex] = React.useState(0); const [focusIndex, setFocusIndex] = useState(0);
const [unfilteredData, setUnfilteredData] = React.useState<FileInfo[]>([]); const [unfilteredData, setUnfilteredData] = useState<FileInfo[]>([]);
const [filteredData, setFilteredData] = React.useState<FileInfo[]>([]); const [filteredData, setFilteredData] = useState<FileInfo[]>([]);
const [fileName, setFileName] = jotai.useAtom(fileNameAtom); const [fileName, setFileName] = jotai.useAtom(fileNameAtom);
const hideHiddenFiles = jotai.useAtomValue(model.showHiddenFiles); const showHiddenFiles = jotai.useAtomValue(model.showHiddenFiles);
const [selectedPath, setSelectedPath] = React.useState(""); const [selectedPath, setSelectedPath] = useState("");
const [refreshVersion, setRefreshVersion] = jotai.useAtom(model.refreshVersion); const [refreshVersion, setRefreshVersion] = jotai.useAtom(model.refreshVersion);
React.useEffect(() => { useEffect(() => {
model.refreshCallback = () => { model.refreshCallback = () => {
setRefreshVersion((refreshVersion) => refreshVersion + 1); setRefreshVersion((refreshVersion) => refreshVersion + 1);
}; };
@ -508,27 +509,27 @@ function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
}; };
}, [setRefreshVersion]); }, [setRefreshVersion]);
React.useEffect(() => { useEffect(() => {
const getContent = async () => { const getContent = async () => {
const file = await services.FileService.ReadFile(fileName); const file = await services.FileService.ReadFile(fileName);
const serializedContent = util.base64ToString(file?.data64); const serializedContent = util.base64ToString(file?.data64);
let content: FileInfo[] = JSON.parse(serializedContent); const content: FileInfo[] = JSON.parse(serializedContent);
setUnfilteredData(content); setUnfilteredData(content);
}; };
getContent(); getContent();
}, [fileName, refreshVersion]); }, [fileName, refreshVersion]);
React.useEffect(() => { useEffect(() => {
let filtered = unfilteredData.filter((fileInfo) => { const filtered = unfilteredData.filter((fileInfo) => {
if (hideHiddenFiles && fileInfo.name.startsWith(".") && fileInfo.name != "..") { if (!showHiddenFiles && fileInfo.name.startsWith(".") && fileInfo.name != "..") {
return false; return false;
} }
return fileInfo.name.toLowerCase().includes(searchText); return fileInfo.name.toLowerCase().includes(searchText);
}); });
setFilteredData(filtered); setFilteredData(filtered);
}, [unfilteredData, hideHiddenFiles, searchText]); }, [unfilteredData, showHiddenFiles, searchText]);
const handleKeyDown = React.useCallback( const handleKeyDown = useCallback(
(waveEvent: WaveKeyboardEvent): boolean => { (waveEvent: WaveKeyboardEvent): boolean => {
if (keyutil.checkKeyPressed(waveEvent, "Escape")) { if (keyutil.checkKeyPressed(waveEvent, "Escape")) {
setSearchText(""); setSearchText("");
@ -554,7 +555,7 @@ function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
[filteredData, setFocusIndex, selectedPath] [filteredData, setFocusIndex, selectedPath]
); );
React.useEffect(() => { useEffect(() => {
if (filteredData.length != 0 && focusIndex > filteredData.length - 1) { if (filteredData.length != 0 && focusIndex > filteredData.length - 1) {
setFocusIndex(filteredData.length - 1); setFocusIndex(filteredData.length - 1);
} }
@ -569,7 +570,7 @@ function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
}, []); }, []);
return ( return (
<div <OverlayScrollbarsComponent
className="dir-table-container" className="dir-table-container"
onChangeCapture={(e) => { onChangeCapture={(e) => {
const event = e as React.ChangeEvent<HTMLInputElement>; const event = e as React.ChangeEvent<HTMLInputElement>;
@ -577,6 +578,7 @@ function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
}} }}
onKeyDownCapture={(e) => keyutil.keydownWrapper(handleKeyDown)(e)} onKeyDownCapture={(e) => keyutil.keydownWrapper(handleKeyDown)(e)}
onFocusCapture={() => document.getSelection().collapseToEnd()} onFocusCapture={() => document.getSelection().collapseToEnd()}
options={{ scrollbars: { autoHide: "leave" } }}
> >
<div className="dir-table-search-line"> <div className="dir-table-search-line">
<input <input
@ -598,7 +600,7 @@ function DirectoryPreview({ fileNameAtom, model }: DirectoryPreviewProps) {
setSelectedPath={setSelectedPath} setSelectedPath={setSelectedPath}
setRefreshVersion={setRefreshVersion} setRefreshVersion={setRefreshVersion}
/> />
</div> </OverlayScrollbarsComponent>
); );
} }

View File

@ -98,6 +98,7 @@ func (fs *FileService) ReadFile(path string) (*FullFile, error) {
if err == nil && parent != finfo.Path { if err == nil && parent != finfo.Path {
log.Printf("adding parent") log.Printf("adding parent")
parentFileInfo.Name = ".." parentFileInfo.Name = ".."
parentFileInfo.Size = -1
innerFilesInfo = append(innerFilesInfo, *parentFileInfo) innerFilesInfo = append(innerFilesInfo, *parentFileInfo)
} }
for _, innerFileEntry := range innerFilesEntries { for _, innerFileEntry := range innerFilesEntries {