Skip to content

Commit

Permalink
table fixes (#4666)
Browse files Browse the repository at this point in the history
* fix: table fixes

* fix: tablaroni

* fix: pagination protection

* fix: dm much more

* fix: colors

* fix: colors

* fix: colors

* fix Timestamp on stocks `get_quote`

* fix `call_tob`  having `quote` as prog/docstring

---------

Co-authored-by: teh_coderer <me@tehcoderer.com>
  • Loading branch information
2 people authored and IgorWounds committed Apr 6, 2023
1 parent b98cbe1 commit 8f8d99e
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 82 deletions.
27 changes: 21 additions & 6 deletions frontend-components/tables/src/components/Table/Pagination.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
import clsx from "clsx";
import { useState } from "react";
import { DEFAULT_ROWS_PER_PAGE } from ".";
import useLocalStorage from "../../utils/useLocalStorage";
import Select from "../Select";
import { DEFAULT_ROWS_PER_PAGE } from ".";

export function validatePageSize(
pageSize: any
) {
if (typeof pageSize !== "number") {
if (typeof pageSize === "string" && pageSize.includes("All")) {
return pageSize
}
return DEFAULT_ROWS_PER_PAGE
}
if (pageSize < 1) {
return DEFAULT_ROWS_PER_PAGE
}
return pageSize
}

export default function Pagination({
table,
Expand All @@ -20,9 +33,11 @@ export default function Pagination({
<Select
value={currentPage}
onChange={(value) => {
setCurrentPage(value);
if (value === `All (${totalRows})`) table.setPageSize(totalRows);
else table.setPageSize(value);
const newValue = validatePageSize(value)
console.log(newValue)
setCurrentPage(newValue);
if (newValue.toString().includes("All")) table.setPageSize(totalRows);
else table.setPageSize(newValue);
}}
labelType="row"
label="Rows per page"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function Timestamp() {
</clipPath>
</defs>
</svg>
<span>
<span className="whitespace-nowrap">
{minutesPassed > 0 ? `${minutesPassed} minutes ago` : "Just now"}
</span>
</div>
Expand Down
52 changes: 28 additions & 24 deletions frontend-components/tables/src/components/Table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { useVirtual } from "react-virtual";
import Select from "../Select";
import { formatNumberMagnitude, fuzzyFilter, isEqual } from "../../utils/utils";
import DraggableColumnHeader from "./ColumnHeader";
import Pagination from "./Pagination";
import Pagination, { validatePageSize } from "./Pagination";
import Export from "./Export";
import Timestamp from "./Timestamp";
import FilterColumns from "./FilterColumns";
Expand All @@ -33,8 +33,8 @@ function getCellWidth(row, column) {
const indexLabel = row.hasOwnProperty("index")
? "index"
: row.hasOwnProperty("Index")
? "Index"
: null;
? "Index"
: null;
const indexValue = indexLabel ? row[indexLabel] : null;
const value = row[column];
const valueType = typeof value;
Expand Down Expand Up @@ -115,7 +115,8 @@ export default function Table({
};
const [currentPage, setCurrentPage] = useLocalStorage(
"rowsPerPage",
DEFAULT_ROWS_PER_PAGE
DEFAULT_ROWS_PER_PAGE,
validatePageSize
);
const [advanced, setAdvanced] = useLocalStorage("advanced", false);
const [colors, setColors] = useLocalStorage("colors", false);
Expand All @@ -132,7 +133,7 @@ export default function Table({
);

const getColumnWidth = (rows, accessor, headerText) => {
const maxWidth = 400;
const maxWidth = 200;
const magicSpacing = 12;
const cellLength = Math.max(
...rows.map((row) => getCellWidth(row, accessor)),
Expand All @@ -153,25 +154,20 @@ export default function Table({
const indexLabel = row.original.hasOwnProperty("index")
? "index"
: row.original.hasOwnProperty("Index")
? "Index"
: null;
? "Index"
: columns[0]
const indexValue = indexLabel ? row.original[indexLabel] : null;
const value = row.original[column];
const valueType = typeof value;
const probablyDate =
column.toLowerCase().includes("date") ||
(column.toLowerCase().includes("date") || column.toLowerCase().includes("timestamp")) ||
column.toLowerCase() === "index" ||
(indexValue &&
typeof indexValue == "string" &&
(indexValue.toLowerCase().includes("date") ||
indexValue.toLowerCase().includes("day") ||
indexValue.toLowerCase().includes("time") ||
indexValue.toLowerCase().includes("timestamp") ||
indexValue.toLowerCase().includes("year") ||
indexValue.toLowerCase().includes("month") ||
indexValue.toLowerCase().includes("week") ||
indexValue.toLowerCase().includes("hour") ||
indexValue.toLowerCase().includes("minute")));
indexValue.toLowerCase().includes("year")));

const probablyLink =
valueType === "string" && value.startsWith("http");
Expand All @@ -193,6 +189,12 @@ export default function Table({
return <p>{value}</p>;
}

if (typeof value === "number") {
if (value < 1000000000000) {
return <p>{value}</p>
}
}

try {
const date = new Date(value);
let dateFormatted = "";
Expand Down Expand Up @@ -257,6 +259,8 @@ export default function Table({
return !isEqual(currentOrder, defaultOrder);
}, [columnOrder, rtColumns]);

console.log(validatePageSize(currentPage))

const table = useReactTable({
data,
columns: rtColumns,
Expand All @@ -279,7 +283,7 @@ export default function Table({
initialState: {
pagination: {
pageIndex: 0,
pageSize: currentPage,
pageSize: typeof currentPage === "string" ? currentPage.includes("All") ? data.length : parseInt(currentPage) : currentPage,
},
},
});
Expand Down Expand Up @@ -382,7 +386,7 @@ export default function Table({
toggleDarkMode(!darkMode);
}}
>
{darkMode ? (
{!darkMode ? (
<MoonIcon className="w-4 h-4" />
) : (
<SunIcon className="w-4 h-4" />
Expand Down Expand Up @@ -487,9 +491,9 @@ export default function Table({
style={{
fontSize: `${Number(fontSize) * 100}%`,
}}
/*style={{
width: table.getCenterTotalSize(),
}}*/
/*style={{
width: table.getCenterTotalSize(),
}}*/
>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
Expand Down Expand Up @@ -528,7 +532,7 @@ export default function Table({
<td
key={cell.id}
className={clsx(
"whitespace-nowrap overflow-auto p-4",
"whitespace-normal p-4 text-black dark:text-white",
{
"bg-grey-100 dark:bg-grey-850": idx % 2 === 0,
"bg-grey-200 dark:bg-[#202020]":
Expand Down Expand Up @@ -571,9 +575,9 @@ export default function Table({
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.footer,
header.getContext()
)}
header.column.columnDef.footer,
header.getContext()
)}
</th>
))}
</tr>
Expand All @@ -584,7 +588,7 @@ export default function Table({
</div>
</div>
</div>
<div className="fixed bg-white/70 dark:bg-grey-900/70 backdrop-filter backdrop-blur z-20 bottom-0 left-0 w-full flex gap-10 justify-between py-4 px-6">
<div className="max-h-[68px] overflow-x-auto fixed bg-white/70 dark:bg-grey-900/70 backdrop-filter backdrop-blur z-20 bottom-0 left-0 w-full flex gap-10 justify-between py-4 px-6">
<Export columns={columns} data={data} />
<div className="flex items-center gap-10">
<Pagination
Expand Down
6 changes: 4 additions & 2 deletions frontend-components/tables/src/utils/useLocalStorage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState } from "react";

export default function useLocalStorage(key: string, initialValue: any) {
export default function useLocalStorage(key: string, initialValue: any, validateFn?: (value: any) => any) {
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState(() => {
Expand All @@ -11,7 +11,9 @@ export default function useLocalStorage(key: string, initialValue: any) {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
return item ?
validateFn ? validateFn(JSON.parse(item)) :
JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
Expand Down
94 changes: 47 additions & 47 deletions openbb_terminal/core/plots/table.html

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions openbb_terminal/stocks/stocks_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,11 +266,11 @@ def call_search(self, other_args: List[str]):

@log_start_end(log=logger)
def call_tob(self, other_args: List[str]):
"""Process quote command."""
"""Process tob command."""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="quote",
prog="tob",
description="Get top of book for loaded ticker from selected exchange",
)
parser.add_argument(
Expand Down
6 changes: 6 additions & 0 deletions openbb_terminal/stocks/stocks_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,10 @@ def get_quote(symbol: str) -> pd.DataFrame:
df_fa.loc["Earnings announcement"][
0
] = f"{earning_announcement.date()} {earning_announcement.time()}"
# Check if there is a valid timestamp and convert it to a readable format
if "Timestamp" in df_fa.index and df_fa.loc["Timestamp"][0]:
df_fa.loc["Timestamp"][0] = datetime.fromtimestamp(
df_fa.loc["Timestamp"][0]
).strftime("%Y-%m-%d %H:%M:%S")

return df_fa

0 comments on commit 8f8d99e

Please sign in to comment.