Skip to content
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
8 changes: 8 additions & 0 deletions .changelog/unreleased/1091-market-watchlist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
type: added
area: trade
pr: 1091
breaking: false
---

Save markets in a watchlist and return to recent selections.
Original file line number Diff line number Diff line change
@@ -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(<MarketSelector onSelect={select} symbol={undefined} />)
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(<MarketSelector onSelect={select} symbol={undefined} />)
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(<MarketSelector onSelect={vi.fn()} symbol={undefined} />)
await userEvent.click(screen.getByRole("button", { name: "Select Market" }))
expect(screen.getByRole("status")).toHaveTextContent("Loading markets")
expect(screen.getByText(/Wallet disconnected/)).toBeVisible()
})
81 changes: 43 additions & 38 deletions apps/web/src/features/trade/components/chart/MarketSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,23 @@
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 = {
symbol: string | undefined
onSelect: (indexTokenAddress: string) => void
}

const RECENT_MARKETS_KEY = "so4-recent-markets-v1"
function readRecentMarkets(): Array<string> {
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,
Expand Down Expand Up @@ -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<Array<string>>(() => 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<HTMLInputElement>(null)
const comboboxId = useId()
const listboxId = `${comboboxId}-listbox`
Expand All @@ -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 &&
Expand Down Expand Up @@ -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("")
}

Expand Down Expand Up @@ -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"
/>
</div>
<div role="group" aria-label="Market lists" className="flex flex-wrap gap-2 px-2">
{(["All markets", "Watchlist", "Recent markets"] as const).map((name) =>
<button type="button" key={name} aria-pressed={section === name} onClick={() => {
setSection(name)
setActiveIndex(0)
inputRef.current?.focus()
}}>{name}</button>)}
</div>
{!connected && <p className="px-2 text-xs text-muted-foreground">Wallet disconnected. Lists are saved on this device.</p>}
{isLoading && <p role="status">Loading markets…</p>}
{isError && <p role="status">Market updates unavailable.</p>}
<ul
className="max-h-72 overflow-y-auto px-1 pb-1"
role="listbox"
id={listboxId}
aria-labelledby={`${comboboxId}-label`}
>
{recent.length > 0 && search.trim() === "" && <li className="px-3 pb-1 pt-2 text-10 font-medium uppercase tracking-wider text-muted-foreground">Recent markets</li>}
{orderedMarkets.length === 0 ? (
<li className="px-3 py-4 text-center text-xs text-muted-foreground">
No markets found
{search || section === "All markets" ? "No markets found" : section === "Watchlist" ? "Your watchlist is empty" : "No recent markets"}
</li>
) : (
orderedMarkets.map((market, index) => (
Expand All @@ -289,6 +289,11 @@ export function MarketSelector({ symbol, onSelect }: Props) {
))
)}
</ul>
{highlighted && <button type="button" className="px-3 py-2 text-xs" onClick={() => {
const id = highlighted.indexTokenAddress
updateLists({ ...lists, watchlist: watched ? lists.watchlist.filter((value) => value !== id) : [...lists.watchlist, id] })
setActiveIndex(0)
}}>{watched ? "Remove " + highlighted.name + " from watchlist" : "Add " + highlighted.name + " to watchlist"}</button>}
</PopoverContent>
</Popover>
{symbol && (
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/features/trade/components/chart/market-lists.test.ts
Original file line number Diff line number Diff line change
@@ -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()
})
22 changes: 22 additions & 0 deletions apps/web/src/features/trade/components/chart/market-lists.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
type MarketLists = { recent: Array<string>; watchlist: Array<string> }

function read(key: string) {
try { return JSON.parse(localStorage.getItem(key) ?? "null") } catch { return null }
}

function ids(values: unknown): Array<string> {
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. */ }
}
1 change: 1 addition & 0 deletions apps/web/src/features/trade/data/markets.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/features/trade/hooks/useMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async function fetchMarkets(): Promise<Array<Market>> {
export function useMarkets() {
const { getToken } = useTokenList()

const { data: markets = MARKETS } = useQuery<Array<Market>>({
const { data: markets = MARKETS, isLoading, isError } = useQuery<Array<Market>>({
queryKey: queryKeys.trade.markets(),
queryFn: fetchMarkets,
...queryPolicy("metadata"),
Expand All @@ -44,7 +44,7 @@ export function useMarkets() {
[markets, getToken],
)

return { markets, getMarket, getMarketsForIndexToken }
return { markets, isLoading, isError, getMarket, getMarketsForIndexToken }
}

export type { Market }