From b613b4200c55e62f5bb0eff6c7e7c840e5d985d6 Mon Sep 17 00:00:00 2001 From: Is-ojo <111299515+Is-ojo@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:09:48 +0100 Subject: [PATCH] feat(trade): add a persistent market watchlist and recent markets Verified 3 focused tests for #1091. Repository-wide lint and docs typechecking have existing failures reproduced on upstream main. --- .../unreleased/1091-market-watchlist.md | 8 ++ .../components/chart/MarketSelector.test.tsx | 45 +++++++++++ .../trade/components/chart/MarketSelector.tsx | 81 ++++++++++--------- .../components/chart/market-lists.test.ts | 11 +++ .../trade/components/chart/market-lists.ts | 22 +++++ apps/web/src/features/trade/data/markets.ts | 1 + .../src/features/trade/hooks/useMarkets.ts | 4 +- 7 files changed, 132 insertions(+), 40 deletions(-) create mode 100644 .changelog/unreleased/1091-market-watchlist.md create mode 100644 apps/web/src/features/trade/components/chart/MarketSelector.test.tsx create mode 100644 apps/web/src/features/trade/components/chart/market-lists.test.ts create mode 100644 apps/web/src/features/trade/components/chart/market-lists.ts diff --git a/.changelog/unreleased/1091-market-watchlist.md b/.changelog/unreleased/1091-market-watchlist.md new file mode 100644 index 00000000..d06070cb --- /dev/null +++ b/.changelog/unreleased/1091-market-watchlist.md @@ -0,0 +1,8 @@ +--- +type: added +area: trade +pr: 1091 +breaking: false +--- + +Save markets in a watchlist and return to recent selections. diff --git a/apps/web/src/features/trade/components/chart/MarketSelector.test.tsx b/apps/web/src/features/trade/components/chart/MarketSelector.test.tsx new file mode 100644 index 00000000..513e55c9 --- /dev/null +++ b/apps/web/src/features/trade/components/chart/MarketSelector.test.tsx @@ -0,0 +1,45 @@ +import { cleanup, render, screen } from "@testing-library/react" +import userEvent from "@testing-library/user-event" +import { afterEach, expect, it, vi } from "vitest" +import { MarketSelector } from "./MarketSelector" + +const state = vi.hoisted(() => ({ loading: false })) +vi.mock("../../hooks/useMarkets", () => ({ + useMarkets: () => ({ isLoading: state.loading, markets: [ + { name: "BTC/USD", address: "btc-usd", indexTokenAddress: "btc" }, + { name: "ETH/USD", address: "eth-usd", indexTokenAddress: "eth" }, + ] }), +})) +vi.mock("../../hooks/useTokenPrices", () => ({ useTokenPrices: () => ({ getMidPrice: () => 0 }) })) +vi.mock("../../hooks/usePriceDelta24h", () => ({ usePriceDelta24h: () => ({}) })) +afterEach(() => { cleanup(); localStorage.clear(); state.loading = false }) + +it("saves a keyboard-highlighted market and remembers selections across mounts", async () => { + const user = userEvent.setup() + const select = vi.fn() + const view = render() + await user.click(screen.getByRole("button", { name: "Select Market" })) + screen.getByRole("combobox").focus() + await user.keyboard("{ArrowDown}") + await user.click(screen.getByRole("button", { name: "Add ETH/USD to watchlist" })) + await user.click(screen.getByRole("button", { name: "Watchlist" })) + expect(screen.getAllByRole("option")).toHaveLength(1) + await user.keyboard("{Enter}") + expect(select).toHaveBeenCalledWith("eth") + view.unmount() + render() + await user.click(screen.getByRole("button", { name: "Select Market" })) + await user.click(screen.getByRole("button", { name: "Recent markets" })) + expect(screen.getByRole("option", { name: /ETH/ })).toBeVisible() + await user.click(screen.getByRole("button", { name: "Remove ETH/USD from watchlist" })) + await user.click(screen.getByRole("button", { name: "Watchlist" })) + expect(screen.getByText("Your watchlist is empty")).toBeVisible() +}) + +it("allows disconnected browsing and announces loading", async () => { + state.loading = true + render() + await userEvent.click(screen.getByRole("button", { name: "Select Market" })) + expect(screen.getByRole("status")).toHaveTextContent("Loading markets") + expect(screen.getByText(/Wallet disconnected/)).toBeVisible() +}) diff --git a/apps/web/src/features/trade/components/chart/MarketSelector.tsx b/apps/web/src/features/trade/components/chart/MarketSelector.tsx index 86097a93..5a76001d 100644 --- a/apps/web/src/features/trade/components/chart/MarketSelector.tsx +++ b/apps/web/src/features/trade/components/chart/MarketSelector.tsx @@ -1,13 +1,16 @@ -import { useEffect, useId, useMemo, useRef, useState } from "react" +import { useId, useMemo, useRef, useState } from "react" import { Popover, PopoverContent, PopoverTrigger } from "@workspace/ui/components/popover" +import { activeQueryNetwork } from "../../lib/query-keys" import { useTokenPrices } from "../../hooks/useTokenPrices" import { usePriceDelta24h } from "../../hooks/usePriceDelta24h" import { useMarkets } from "../../hooks/useMarkets" +import { readMarketLists, saveMarketLists } from "./market-lists" import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, } from "react" import type { Market } from "../../hooks/useMarkets" +import { useWalletStore } from "@/features/wallet/store/wallet-store" import { formatUsd } from "@/shared/lib/format" type Props = { @@ -15,14 +18,6 @@ type Props = { onSelect: (indexTokenAddress: string) => void } -const RECENT_MARKETS_KEY = "so4-recent-markets-v1" -function readRecentMarkets(): Array { - try { - const value = JSON.parse(localStorage.getItem(RECENT_MARKETS_KEY) ?? "[]") - return Array.isArray(value) ? value.filter((id): id is string => typeof id === "string") : [] - } catch { return [] } -} - function MarketRow({ market, isActive, @@ -90,7 +85,14 @@ export function MarketSelector({ symbol, onSelect }: Props) { const [open, setOpen] = useState(false) const [search, setSearch] = useState("") const [activeIndex, setActiveIndex] = useState(0) - const [recentMarkets, setRecentMarkets] = useState>(() => readRecentMarkets()) + const network = activeQueryNetwork() + const [lists, setLists] = useState(() => readMarketLists(network)) + const [section, setSection] = useState<"All markets" | "Watchlist" | "Recent markets">("All markets") + const connected = useWalletStore((state) => Boolean(state.address)) + function updateLists(next: typeof lists) { + setLists(next) + saveMarketLists(network, next) + } const inputRef = useRef(null) const comboboxId = useId() const listboxId = `${comboboxId}-listbox` @@ -101,39 +103,26 @@ export function MarketSelector({ symbol, onSelect }: Props) { setSearch("") } - const { markets } = useMarkets() + const { markets, isLoading, isError } = useMarkets() const activeMarket = markets.find((m) => m.indexTokenAddress === symbol) - const filtered = markets.filter((m) => - search.trim() === "" - ? true - : m.name.toLowerCase().includes(search.toLowerCase()) || - m.indexTokenAddress.toLowerCase().includes(search.toLowerCase()) - ) - const recent = useMemo(() => recentMarkets.map((id) => markets.find((m) => m.indexTokenAddress === id)).filter((m): m is Market => Boolean(m)), [markets, recentMarkets]) const orderedMarkets = useMemo(() => { - if (search.trim() !== "") return filtered - const recentIds = new Set(recent.map((market) => market.indexTokenAddress)) - return [...recent, ...filtered.filter((market) => !recentIds.has(market.indexTokenAddress))] - }, [filtered, recent, search]) - - useEffect(() => { - if (!open) return - - const currentIndex = orderedMarkets.findIndex( - (m) => m.indexTokenAddress === symbol - ) - setActiveIndex(Math.max(0, currentIndex)) - }, [open, orderedMarkets, symbol]) + const ids = section === "Watchlist" ? lists.watchlist : lists.recent + const source = section === "All markets" ? markets : + ids.flatMap((id) => markets.filter((market) => market.indexTokenAddress === id)) + const term = search.trim().toLowerCase() + return source.filter((market) => !market.isDisabled && + (market.name.toLowerCase().includes(term) || market.indexTokenAddress.toLowerCase().includes(term))) + }, [lists, markets, search, section]) + const highlighted = orderedMarkets.at(activeIndex) + const watched = highlighted && lists.watchlist.includes(highlighted.indexTokenAddress) const selectMarket = (market: Market) => { - const nextRecent = [market.indexTokenAddress, ...recentMarkets.filter((id) => id !== market.indexTokenAddress)].slice(0, 5) - setRecentMarkets(nextRecent) - try { localStorage.setItem(RECENT_MARKETS_KEY, JSON.stringify(nextRecent)) } catch { /* optional preference */ } + updateLists({ ...lists, recent: [market.indexTokenAddress, ...lists.recent.filter((id) => id !== market.indexTokenAddress)].slice(0, 5) }) const prefersReduced = typeof window !== "undefined" && - window.matchMedia("(prefers-reduced-motion: reduce)").matches + typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches if ( typeof document !== "undefined" && "startViewTransition" in document && @@ -191,6 +180,7 @@ export function MarketSelector({ symbol, onSelect }: Props) { const handleOpenChange = (next: boolean) => { setOpen(next) + if (next) setActiveIndex(Math.max(0, orderedMarkets.findIndex((market) => market.indexTokenAddress === symbol))) if (!next) setSearch("") } @@ -260,22 +250,32 @@ export function MarketSelector({ symbol, onSelect }: Props) { } aria-autocomplete="list" value={search} - onChange={(e) => setSearch(e.target.value)} + onChange={(e) => { setSearch(e.target.value); setActiveIndex(0) }} onKeyDown={handleInputKeyDown} placeholder="Search markets..." className="w-full rounded-sm bg-background px-2.5 py-1.5 text-xs text-foreground ring-1 ring-border outline-none placeholder:text-muted-foreground focus:ring-primary" /> +
+ {(["All markets", "Watchlist", "Recent markets"] as const).map((name) => + )} +
+ {!connected &&

Wallet disconnected. Lists are saved on this device.

} + {isLoading &&

Loading markets…

} + {isError &&

Market updates unavailable.

}
    - {recent.length > 0 && search.trim() === "" &&
  • Recent markets
  • } {orderedMarkets.length === 0 ? (
  • - No markets found + {search || section === "All markets" ? "No markets found" : section === "Watchlist" ? "Your watchlist is empty" : "No recent markets"}
  • ) : ( orderedMarkets.map((market, index) => ( @@ -289,6 +289,11 @@ export function MarketSelector({ symbol, onSelect }: Props) { )) )}
+ {highlighted && } {symbol && ( diff --git a/apps/web/src/features/trade/components/chart/market-lists.test.ts b/apps/web/src/features/trade/components/chart/market-lists.test.ts new file mode 100644 index 00000000..43be1954 --- /dev/null +++ b/apps/web/src/features/trade/components/chart/market-lists.test.ts @@ -0,0 +1,11 @@ +import { expect, it } from "vitest" +import { readMarketLists, saveMarketLists } from "./market-lists" + +it("migrates legacy recent markets and network favorites without duplicates", () => { + localStorage.setItem("so4-recent-markets-v1", '["btc","btc",2,"eth"]') + localStorage.setItem("so4-market-favorites-v1:test", '{"markets":["eth"]}') + expect(readMarketLists("test")).toEqual({ recent: ["btc", "eth"], watchlist: ["eth"] }) + saveMarketLists("test", { recent: [], watchlist: [] }) + expect(readMarketLists("test")).toEqual({ recent: [], watchlist: [] }) + localStorage.clear() +}) diff --git a/apps/web/src/features/trade/components/chart/market-lists.ts b/apps/web/src/features/trade/components/chart/market-lists.ts new file mode 100644 index 00000000..bc277a1e --- /dev/null +++ b/apps/web/src/features/trade/components/chart/market-lists.ts @@ -0,0 +1,22 @@ +type MarketLists = { recent: Array; watchlist: Array } + +function read(key: string) { + try { return JSON.parse(localStorage.getItem(key) ?? "null") } catch { return null } +} + +function ids(values: unknown): Array { + return Array.isArray(values) ? [...new Set(values.filter((id): id is string => typeof id === "string" && id.length > 0))] : [] +} + +export function readMarketLists(network: string): MarketLists { + const saved = read("so4-market-lists-v2:" + network) + if (saved?.version === 2) return { recent: ids(saved.recent).slice(0, 5), watchlist: ids(saved.watchlist) } + const favorites = read("so4-market-favorites-v1:" + network) + return { recent: ids(read("so4-recent-markets-v1")).slice(0, 5), watchlist: ids(favorites?.markets ?? favorites) } +} + +export function saveMarketLists(network: string, lists: MarketLists) { + try { + localStorage.setItem("so4-market-lists-v2:" + network, JSON.stringify({ version: 2, ...lists })) + } catch { /* Browsing markets also works with session-only preferences. */ } +} diff --git a/apps/web/src/features/trade/data/markets.ts b/apps/web/src/features/trade/data/markets.ts index 4e69bb2d..20a35898 100644 --- a/apps/web/src/features/trade/data/markets.ts +++ b/apps/web/src/features/trade/data/markets.ts @@ -1,6 +1,7 @@ import { POOL_MARKETS } from "@/features/pools/data/markets" export type Market = { + isDisabled?: boolean address: string name: string indexTokenAddress: string // the asset being priced (e.g. BTC) diff --git a/apps/web/src/features/trade/hooks/useMarkets.ts b/apps/web/src/features/trade/hooks/useMarkets.ts index 9d5c0bde..1858b24c 100644 --- a/apps/web/src/features/trade/hooks/useMarkets.ts +++ b/apps/web/src/features/trade/hooks/useMarkets.ts @@ -24,7 +24,7 @@ async function fetchMarkets(): Promise> { export function useMarkets() { const { getToken } = useTokenList() - const { data: markets = MARKETS } = useQuery>({ + const { data: markets = MARKETS, isLoading, isError } = useQuery>({ queryKey: queryKeys.trade.markets(), queryFn: fetchMarkets, ...queryPolicy("metadata"), @@ -44,7 +44,7 @@ export function useMarkets() { [markets, getToken], ) - return { markets, getMarket, getMarketsForIndexToken } + return { markets, isLoading, isError, getMarket, getMarketsForIndexToken } } export type { Market }