Skip to content

feat(insights): add StatCard icons and Alerts, plus code cleanup #2175

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,14 @@ const AssetClassTable = ({
count: <Badge style="outline">{count}</Badge>,
},
})),
[numFeedsByAssetClass, collator, closeDrawer, pathname, updateAssetClass],
[
numFeedsByAssetClass,
collator,
closeDrawer,
pathname,
updateAssetClass,
updateSearch,
],
);
return (
<Table
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
@use "@pythnetwork/component-library/theme";

.changePercent {
font-size: theme.font-size("sm");
transition: color 100ms linear;
display: flex;
flex-flow: row nowrap;
gap: theme.spacing(1);
align-items: center;

.caret {
width: theme.spacing(3);
height: theme.spacing(3);
transition: transform 300ms linear;
}

&[data-direction="up"] {
color: theme.color("states", "success", "base");
}

&[data-direction="down"] {
color: theme.color("states", "error", "base");

.caret {
transform: rotate3d(1, 0, 0, 180deg);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
"use client";

import { CaretUp } from "@phosphor-icons/react/dist/ssr/CaretUp";
import { Card } from "@pythnetwork/component-library/Card";
import { Skeleton } from "@pythnetwork/component-library/Skeleton";
import { type ReactNode, useMemo } from "react";
import { type ComponentProps, createContext, use } from "react";
import { useNumberFormatter } from "react-aria";
import { z } from "zod";

import styles from "./featured-recently-added.module.scss";
import styles from "./change-percent.module.scss";
import { StateType, useData } from "../../use-data";
import { LivePrice, useLivePrice } from "../LivePrices";
import { useLivePrice } from "../LivePrices";

const ONE_SECOND_IN_MS = 1000;
const ONE_MINUTE_IN_MS = 60 * ONE_SECOND_IN_MS;
Expand All @@ -18,87 +17,64 @@ const REFRESH_YESTERDAYS_PRICES_INTERVAL = ONE_HOUR_IN_MS;

const CHANGE_PERCENT_SKELETON_WIDTH = 15;

type Props = {
recentlyAdded: RecentlyAddedPriceFeed[];
type Props = Omit<ComponentProps<typeof YesterdaysPricesContext>, "value"> & {
symbolsToFeedKeys: Record<string, string>;
};

type RecentlyAddedPriceFeed = {
id: string;
symbol: string;
priceFeedName: ReactNode;
};
const YesterdaysPricesContext = createContext<
undefined | ReturnType<typeof useData<Map<string, number>>>
>(undefined);

export const FeaturedRecentlyAdded = ({ recentlyAdded }: Props) => {
const feedKeys = useMemo(
() => recentlyAdded.map(({ id }) => id),
[recentlyAdded],
);
const symbols = useMemo(
() => recentlyAdded.map(({ symbol }) => symbol),
[recentlyAdded],
);
export const YesterdaysPricesProvider = ({
symbolsToFeedKeys,
...props
}: Props) => {
const state = useData(
["yesterdaysPrices", feedKeys],
() => getYesterdaysPrices(symbols),
["yesterdaysPrices", Object.values(symbolsToFeedKeys)],
() => getYesterdaysPrices(symbolsToFeedKeys),
{
refreshInterval: REFRESH_YESTERDAYS_PRICES_INTERVAL,
},
);

return (
<>
{recentlyAdded.map(({ priceFeedName, id, symbol }, i) => (
<Card
key={i}
href="#"
title={priceFeedName}
footer={
<div className={styles.footer}>
<LivePrice account={id} />
<div className={styles.changePercent}>
<ChangePercent
yesterdaysPriceState={state}
feedKey={id}
symbol={symbol}
/>
</div>
</div>
}
className={styles.recentlyAddedFeed ?? ""}
variant="tertiary"
/>
))}
</>
);
return <YesterdaysPricesContext value={state} {...props} />;
};

const getYesterdaysPrices = async (
symbols: string[],
): Promise<Record<string, number>> => {
symbolsToFeedKeys: Record<string, string>,
): Promise<Map<string, number>> => {
const url = new URL("/yesterdays-prices", window.location.origin);
for (const symbol of symbols) {
for (const symbol of Object.keys(symbolsToFeedKeys)) {
url.searchParams.append("symbols", symbol);
}
const response = await fetch(url);
const data: unknown = await response.json();
return yesterdaysPricesSchema.parse(data);
return new Map(
Object.entries(yesterdaysPricesSchema.parse(data)).map(
([symbol, value]) => [symbolsToFeedKeys[symbol] ?? "", value],
),
);
};

const yesterdaysPricesSchema = z.record(z.string(), z.number());

const useYesterdaysPrices = () => {
const state = use(YesterdaysPricesContext);

if (state) {
return state;
} else {
throw new YesterdaysPricesNotInitializedError();
}
};

type ChangePercentProps = {
yesterdaysPriceState: ReturnType<
typeof useData<Awaited<ReturnType<typeof getYesterdaysPrices>>>
>;
feedKey: string;
symbol: string;
};

const ChangePercent = ({
yesterdaysPriceState,
feedKey,
symbol,
}: ChangePercentProps) => {
export const ChangePercent = ({ feedKey }: ChangePercentProps) => {
const yesterdaysPriceState = useYesterdaysPrices();

switch (yesterdaysPriceState.type) {
case StateType.Error: {
// eslint-disable-next-line unicorn/no-null
Expand All @@ -107,11 +83,16 @@ const ChangePercent = ({

case StateType.Loading:
case StateType.NotLoaded: {
return <Skeleton width={CHANGE_PERCENT_SKELETON_WIDTH} />;
return (
<Skeleton
className={styles.changePercent}
width={CHANGE_PERCENT_SKELETON_WIDTH}
/>
);
}

case StateType.Loaded: {
const yesterdaysPrice = yesterdaysPriceState.data[symbol];
const yesterdaysPrice = yesterdaysPriceState.data.get(feedKey);
// eslint-disable-next-line unicorn/no-null
return yesterdaysPrice === undefined ? null : (
<ChangePercentLoaded priorPrice={yesterdaysPrice} feedKey={feedKey} />
Expand All @@ -132,7 +113,10 @@ const ChangePercentLoaded = ({
const currentPrice = useLivePrice(feedKey);

return currentPrice === undefined ? (
<Skeleton width={CHANGE_PERCENT_SKELETON_WIDTH} />
<Skeleton
className={styles.changePercent}
width={CHANGE_PERCENT_SKELETON_WIDTH}
/>
) : (
<PriceDifference
currentPrice={currentPrice.price}
Expand All @@ -154,7 +138,7 @@ const PriceDifference = ({
const direction = getDirection(currentPrice, priorPrice);

return (
<span data-direction={direction} className={styles.price}>
<span data-direction={direction} className={styles.changePercent}>
<CaretUp weight="fill" className={styles.caret} />
{numberFormatter.format(
(100 * Math.abs(currentPrice - priorPrice)) / currentPrice,
Expand All @@ -173,3 +157,12 @@ const getDirection = (currentPrice: number, priorPrice: number) => {
return "flat";
}
};

class YesterdaysPricesNotInitializedError extends Error {
constructor() {
super(
"This component must be contained within a <YesterdaysPricesProvider>",
);
this.name = "YesterdaysPricesNotInitializedError";
}
}

This file was deleted.

Loading
Loading