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
6 changes: 3 additions & 3 deletions apps/web/src/features/changelog/hooks/use-release-hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ function focusHashTarget() {
const target = document.getElementById(window.location.hash.slice(1))
if (!target) return

const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches
const reducedMotion =
document.documentElement.dataset.reducedMotion === "true" ||
window.matchMedia("(prefers-reduced-motion: reduce)").matches

target.scrollIntoView({
behavior: reducedMotion ? "auto" : "smooth",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ const mockChartMethods = {
remove: vi.fn(),
applyOptions: vi.fn(),
timeScale: vi.fn(() => mockTimeScale),
subscribeCrosshairMove: vi.fn(),
unsubscribeCrosshairMove: vi.fn(),
}

const mockSeriesMethods = {
Expand Down Expand Up @@ -141,6 +143,16 @@ describe("TVChartContainer", () => {
expect(chart).toBeInTheDocument()
})

it("uses the magnetic crosshair and shows its OHLC legend", () => {
mockCandles = SAMPLE_CANDLES
render(<TVChartContainer {...defaultProps} />)

expect(mockCreateChart).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
crosshair: { mode: 1 },
}))
expect(screen.getByTestId("ohlc-legend")).toBeInTheDocument()
})

it("describes the chart as linked from the summary", () => {
mockCandles = SAMPLE_CANDLES
const { container } = render(<TVChartContainer {...defaultProps} />)
Expand Down
42 changes: 34 additions & 8 deletions apps/web/src/features/trade/components/chart/TVChartContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CandlestickSeries, LineStyle, createChart } from "lightweight-charts"
import { CandlestickSeries, CrosshairMode, LineStyle, createChart } from "lightweight-charts"
import { useEffect, useMemo, useRef, useState } from "react"
import { Skeleton } from "@workspace/ui/components/skeleton"
import { RollingNumber } from "@workspace/ui/components/rolling-number"
import { VisuallyHidden } from "@workspace/ui/components/visually-hidden"
import { LiveRegion, useAnnouncer } from "@workspace/ui/components/live-region"
import { cn } from "@workspace/ui/lib/utils"
Expand Down Expand Up @@ -28,9 +29,6 @@ import type { OhlcBar } from "../../lib/oracle"
import { useWalletStore } from "@/features/wallet/store/wallet-store"
import { formatUsd } from "@/shared/lib/format"
import { ENV } from "@/app/config/env"
import type { CandlestickData, IChartApi, IPriceLine, ISeriesApi, UTCTimestamp } from "lightweight-charts"
import type { OhlcBar } from "../../lib/oracle"
import { useWalletStore } from "@/features/wallet/store/wallet-store"

type ChartLine = {
id: string
Expand All @@ -40,6 +38,8 @@ type ChartLine = {
lineStyle?: LineStyle
}

type CrosshairEvent = Parameters<Parameters<IChartApi["subscribeCrosshairMove"]>[0]>[0]

type Props = {
symbol: string
period: string
Expand Down Expand Up @@ -132,6 +132,8 @@ export function TVChartContainer({ symbol, period }: Props) {
const account = useWalletStore((state) => state.address)

const [showTable, setShowTable] = useState(false)
const [crosshairBar, setCrosshairBar] = useState<OhlcBar | null>(null)
const crosshairTimeRef = useRef<number | null>(null)
const lastAnnounceRef = useRef(0)
const announcer = useAnnouncer()

Expand All @@ -146,6 +148,7 @@ export function TVChartContainer({ symbol, period }: Props) {

const summary = useMemo(() => getChartSummary(candles, liveBar, symbol, period), [candles, liveBar, symbol, period])
const tableRows = useMemo(() => getRepresentativeRows(candles), [candles])
const legendBar = crosshairBar ?? liveBar ?? candles.at(-1) ?? null

const currentSymbolRef = useRef(symbol)
const currentPeriodRef = useRef(period)
Expand All @@ -158,6 +161,7 @@ export function TVChartContainer({ symbol, period }: Props) {

const chart = createChart(containerRef.current, {
...buildChartOptions(palette),
crosshair: { mode: CrosshairMode.Magnet },
handleScroll: { mouseWheel: true, pressedMouseMove: true },
handleScale: { mouseWheel: true, pinch: true },
})
Expand All @@ -167,6 +171,15 @@ export function TVChartContainer({ symbol, period }: Props) {
chartRef.current = chart
seriesRef.current = series

// Snap to candles in the renderer and update React only on a new candle.
const onCrosshairMove = (event: CrosshairEvent) => {
const bar = event.seriesData.get(series) as CandlestickData<UTCTimestamp> | undefined
if (!bar || crosshairTimeRef.current === Number(bar.time)) return
crosshairTimeRef.current = Number(bar.time)
setCrosshairBar({ time: Number(bar.time), open: bar.open, high: bar.high, low: bar.low, close: bar.close })
}
chart.subscribeCrosshairMove(onCrosshairMove)

// Responsive resize — guard against zero-size to avoid chart overflow or
// dimension errors. Preserve the chart instance across ordinary layout changes.
const resizeObserver = new ResizeObserver(() => {
Expand Down Expand Up @@ -199,6 +212,7 @@ export function TVChartContainer({ symbol, period }: Props) {
return () => {
resizeObserver.disconnect()
themeObserver.disconnect()
chart.unsubscribeCrosshairMove(onCrosshairMove)
chart.remove()
chartRef.current = null
seriesRef.current = null
Expand All @@ -215,6 +229,8 @@ export function TVChartContainer({ symbol, period }: Props) {
const symbolChanged = currentSymbolRef.current !== symbol
currentSymbolRef.current = symbol
currentPeriodRef.current = period
crosshairTimeRef.current = null
setCrosshairBar(null)

if (!seriesRef.current) return
seriesRef.current.setData([])
Expand Down Expand Up @@ -365,9 +381,19 @@ export function TVChartContainer({ symbol, period }: Props) {
{sourceType === "oracle_reference" ? `Reference Price (${venueName})` : `Execution Fills (${venueName})`}
</span>
</div>
<span className="font-mono text-[10px] uppercase text-muted-foreground/60">
{network}
</span>
<div className="flex items-center gap-3 font-mono text-[10px] uppercase text-muted-foreground/60">
{legendBar && (
<dl className="flex items-center gap-2 normal-case" aria-label="Candle values" data-testid="ohlc-legend">
{(["open", "high", "low", "close"] as const).map((key) => (
<div key={key} className="flex gap-0.5">
<dt>{key[0].toUpperCase()}</dt>
<dd className="text-foreground"><RollingNumber value={formatUsd(legendBar[key], { decimals: 4 })} /></dd>
</div>
))}
</dl>
)}
<span>{network}</span>
</div>
</div>

{/* ═══ Chart area ═══════════════════════════════════════════════════════ */}
Expand Down Expand Up @@ -455,7 +481,7 @@ export function TVChartContainer({ symbol, period }: Props) {
{/* Lightweight Charts canvas — hidden from AT; the VisuallyHidden summary replaces it */}
<div
ref={containerRef}
className={cn("h-full w-full transition-opacity duration-150", isStale && "opacity-60")}
className={cn("h-full w-full transition-opacity duration-base", isStale && "opacity-60")}
style={{ touchAction: "none" }}
role="img"
aria-label={`Price chart for ${symbol}`}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Slider } from "@workspace/ui/components/slider"
import { Badge } from "@workspace/ui/components/badge"
import { haptic } from "@/shared/lib/haptics"

type LeverageSliderProps = {
min?: number
Expand All @@ -21,7 +22,11 @@ export function LeverageSlider({ min = 1, max = 50, step = 0.5, value, onChange
max={max}
step={step}
value={[value]}
onValueChange={(v) => onChange(Array.isArray(v) ? v[0] : v)}
onValueChange={(v) => {
const next = Array.isArray(v) ? v[0] : v
if (next !== value) haptic("detent")
onChange(next)
}}
className="w-full"
/>
<div className="flex justify-between text-xs text-muted-foreground">
Expand Down
55 changes: 55 additions & 0 deletions apps/web/src/lib/motion-preference.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState } from "react"

const STORAGE_KEY = "so4-reduced-motion"
const CHANGE_EVENT = "so4:reduced-motion-change"

function readPreference(): boolean {
return typeof window !== "undefined" && localStorage.getItem(STORAGE_KEY) === "true"
}

function applyPreference(enabled: boolean): void {
document.documentElement.dataset.reducedMotion = String(enabled)
}

/** Persist and broadcast the app-level motion preference. */
export function setMotionReduction(enabled: boolean): void {
localStorage.setItem(STORAGE_KEY, String(enabled))
applyPreference(enabled)
window.dispatchEvent(new Event(CHANGE_EVENT))
}

/** Combines the system preference with the explicit app preference. */
export function useReducedMotion(): boolean {
const [reduced, setReduced] = useState(false)

useEffect(() => {
const media = window.matchMedia("(prefers-reduced-motion: reduce)")
const sync = () => {
const enabled = media.matches || readPreference()
applyPreference(readPreference())
setReduced(enabled)
}
sync()
media.addEventListener("change", sync)
window.addEventListener(CHANGE_EVENT, sync)
return () => {
media.removeEventListener("change", sync)
window.removeEventListener(CHANGE_EVENT, sync)
}
}, [])

return reduced
}

export function useMotionReductionSetting(): readonly [boolean, (enabled: boolean) => void] {
const [enabled, setEnabled] = useState(readPreference)

useEffect(() => {
const sync = () => setEnabled(readPreference())
sync()
window.addEventListener(CHANGE_EVENT, sync)
return () => window.removeEventListener(CHANGE_EVENT, sync)
}, [])

return [enabled, setMotionReduction] as const
}
13 changes: 12 additions & 1 deletion apps/web/src/lib/use-reduced-motion.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { act, renderHook } from "@testing-library/react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"

import { useReducedMotion } from "./use-reduced-motion"
import { setMotionReduction, useReducedMotion } from "./motion-preference"

describe("useReducedMotion", () => {
let mediaQueryListMock: {
Expand All @@ -27,6 +27,8 @@ describe("useReducedMotion", () => {

afterEach(() => {
vi.restoreAllMocks()
localStorage.removeItem("so4-reduced-motion")
delete document.documentElement.dataset.reducedMotion
})

it("returns false initially (SSR-safe hydration)", () => {
Expand Down Expand Up @@ -93,6 +95,15 @@ describe("useReducedMotion", () => {
)
})

it("honours the in-app setting and exposes it to CSS", () => {
const { result } = renderHook(() => useReducedMotion())

act(() => setMotionReduction(true))

expect(result.current).toBe(true)
expect(document.documentElement.dataset.reducedMotion).toBe("true")
})

it("does not leak timers or listeners on rapid mount/unmount", () => {
const { rerender, unmount } = renderHook(() => useReducedMotion())

Expand Down
27 changes: 1 addition & 26 deletions apps/web/src/lib/use-reduced-motion.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react"
export { useReducedMotion } from "./motion-preference"

/**
* Hook that detects the system's prefers-reduced-motion preference and updates
Expand All @@ -19,28 +19,3 @@ import { useEffect, useState } from "react"
* }
* }, [reducedMotion])
*/
export function useReducedMotion(): boolean {
// Default to false on server render to match initial hydration
const [reducedMotion, setReducedMotion] = useState(false)
const [mounted, setMounted] = useState(false)

useEffect(() => {
// Query the current preference
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)")
setReducedMotion(mediaQuery.matches)
setMounted(true)

// Listen for changes to the preference
const handleChange = (event: MediaQueryListEvent) => {
setReducedMotion(event.matches)
}

mediaQuery.addEventListener("change", handleChange)
return () => {
mediaQuery.removeEventListener("change", handleChange)
}
}, [])

// Return false until mounted to ensure hydration matches server render
return mounted ? reducedMotion : false
}
5 changes: 5 additions & 0 deletions apps/web/src/shared/hooks/useTxSubmit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { toast } from "@workspace/ui/components/toast"
import { sendAndPoll } from "@/lib/tx-builder"
import { explorerTxUrl } from "@/app/config/network"
import { useTxFeedback } from "./useTxFeedback"
import { haptic } from "@/shared/lib/haptics"

export type SubmitTxOptions = {
loadingMessage: string
Expand Down Expand Up @@ -46,6 +47,7 @@ export async function submitTx(
</div>
),
})
haptic("success")

// Execute onSuccess as a side effect after transaction confirmation,
// but don't let its errors overwrite transaction success state
Expand All @@ -64,6 +66,7 @@ export async function submitTx(
} catch (error) {
const message = options.onError?.(error) ?? "Transaction failed"
toast.error(message, { id: toastId })
haptic("error")
throw error
}
}
Expand Down Expand Up @@ -166,13 +169,15 @@ export function useTxSubmit() {
message: options.successMessage,
description: options.successDescription?.(hash),
})
haptic("success")

setState({ isLoading: false, txHash: hash, error: null })
submitInProgressRef.current = false
return hash
} catch (error) {
const message = options.onError?.(error) ?? "Transaction failed"
feedback.handleEvent({ type: "error", message })
haptic("error")
setState({
isLoading: false,
txHash: null,
Expand Down
29 changes: 29 additions & 0 deletions apps/web/src/shared/lib/haptics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { afterEach, describe, expect, it, vi } from "vitest"

import { haptic } from "./haptics"

describe("haptic", () => {
afterEach(() => {
vi.restoreAllMocks()
delete document.documentElement.dataset.reducedMotion
})

it("uses a short success vibration when supported", () => {
const vibrate = vi.fn()
Object.defineProperty(navigator, "vibrate", { configurable: true, value: vibrate })

haptic("success")

expect(vibrate).toHaveBeenCalledWith(12)
})

it("does nothing when reduced motion is selected", () => {
const vibrate = vi.fn()
Object.defineProperty(navigator, "vibrate", { configurable: true, value: vibrate })
document.documentElement.dataset.reducedMotion = "true"

haptic("error")

expect(vibrate).not.toHaveBeenCalled()
})
})
18 changes: 18 additions & 0 deletions apps/web/src/shared/lib/haptics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
type HapticKind = "success" | "error" | "detent"

const patterns: Record<HapticKind, number | Array<number>> = {
success: 12,
error: [18, 35, 18],
detent: 6,
}

/** Android vibration with an intentionally silent no-op on unsupported devices. */
export function haptic(kind: HapticKind): void {
if (
typeof navigator === "undefined" ||
document.documentElement.dataset.reducedMotion === "true" ||
!navigator.vibrate
) return

navigator.vibrate(patterns[kind])
}
Loading