Skip to content
Open
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
13,796 changes: 9,269 additions & 4,527 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@stellar/freighter-api": "^6.0.1",
"@stellar/stellar-sdk": "^17.2.0",
"@tanstack/react-query": "^5.104.0",
"@testing-library/dom": "^10.4.2",
"framer-motion": "^11.0.0",
"next": "14.2.5",
"react": "^18",
Expand Down
8 changes: 7 additions & 1 deletion src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WalletProvider } from "@/lib/wallet/WalletProvider";
import { AriaLiveProvider } from "@/components/ui/AriaLiveProvider";
import { RealtimeSyncProvider } from "@/lib/realtime/RealtimeSyncProvider";

export function Providers({ children }: { children: React.ReactNode }) {
// One client per browser session. Query functions already fold failures
Expand All @@ -13,7 +15,11 @@ export function Providers({ children }: { children: React.ReactNode }) {

return (
<QueryClientProvider client={queryClient}>
<WalletProvider>{children}</WalletProvider>
<AriaLiveProvider>
<RealtimeSyncProvider>
<WalletProvider>{children}</WalletProvider>
</RealtimeSyncProvider>
</AriaLiveProvider>
</QueryClientProvider>
);
}
139 changes: 139 additions & 0 deletions src/components/ui/AriaLiveProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { render, screen, act } from "@testing-library/react";
import { AriaLiveProvider, useAriaLive } from "@/components/ui/AriaLiveProvider";
import React from "react";

/** Test harness that exposes announce via buttons. */
function TestConsumer() {
const { announce } = useAriaLive();
return (
<div>
<button type="button" onClick={() => announce("first")}>
announce-first
</button>
<button type="button" onClick={() => announce("second")}>
announce-second
</button>
<button
type="button"
onClick={() => {
announce("Oracle reading updated");
announce("Pool statistics updated");
announce("Claim settled");
}}
>
announce-batch
</button>
<button type="button" onClick={() => announce("")}>
announce-empty
</button>
</div>
);
}

function renderProvider() {
return render(
<AriaLiveProvider>
<TestConsumer />
</AriaLiveProvider>,
);
}

describe("AriaLiveProvider", () => {
beforeEach(() => {
vi.useFakeTimers();
});

afterEach(() => {
vi.useRealTimers();
});

it("renders a polite aria-live region", () => {
renderProvider();
const region = document.querySelector('[aria-live="polite"]');
expect(region).not.toBeNull();
expect(region?.getAttribute("aria-atomic")).toBe("true");
expect(region?.className).toContain("sr-only");
});

it("flushes a single announcement when the timer fires", () => {
renderProvider();
const region = document.querySelector('[aria-live="polite"]')!;
expect(region.textContent).toBe("");

act(() => {
screen.getByText("announce-first").click();
vi.advanceTimersByTime(0);
});

expect(region.textContent).toContain("first");
});

it("coalesces multiple messages in the same tick into one announcement", () => {
renderProvider();
const region = document.querySelector('[aria-live="polite"]')!;

act(() => {
screen.getByText("announce-batch").click();
vi.advanceTimersByTime(0);
});

// All three messages should be joined into one announcement.
expect(region.textContent).toContain("Oracle reading updated");
expect(region.textContent).toContain("Pool statistics updated");
expect(region.textContent).toContain("Claim settled");
});

it("does not flush a second announcement within the 2s throttle window", () => {
renderProvider();
const region = document.querySelector('[aria-live="polite"]')!;

// First announcement — flushed via 0ms timer.
act(() => {
screen.getByText("announce-first").click();
vi.advanceTimersByTime(0);
});
expect(region.textContent).toContain("first");

// Advance only 500ms (within the 2s window).
act(() => vi.advanceTimersByTime(500));

// Second call — should queue but not flush yet.
act(() => {
screen.getByText("announce-second").click();
vi.advanceTimersByTime(0);
});

expect(region.textContent).not.toContain("second");

// Advance past the remaining throttle window — the queued message
// should now flush.
act(() => vi.advanceTimersByTime(2000));
expect(region.textContent).toContain("second");
});

it("ignores empty messages", () => {
renderProvider();
const region = document.querySelector('[aria-live="polite"]')!;
act(() => {
screen.getByText("announce-empty").click();
vi.advanceTimersByTime(3000);
});
expect(region.textContent).toBe("");
});

it("useAriaLive returns a no-op announce when used outside provider", () => {
const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
function Orphan() {
const { announce } = useAriaLive();
return (
<button type="button" onClick={() => announce("hello")}>
orphan
</button>
);
}
render(<Orphan />);
expect(() => screen.getByText("orphan").click()).not.toThrow();
spy.mockRestore();
});
});
135 changes: 135 additions & 0 deletions src/components/ui/AriaLiveProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
"use client";

import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";

/**
* Throttled ARIA live region system.
*
* Continuous realtime streams are an accessibility trap: an unthrottled
* `aria-live="polite"` region on the oracle price or the LP pool stats will
* machine-gun the screen reader and make the page unusable, while no live
* region at all means non-visual users never learn that a claim settled or
* a policy was issued.
*
* This system solves that with a deliberate, throttled announcement policy:
*
* - **Polite, not assertive.** The region uses `aria-live="polite"` so the
* screen reader finishes the current utterance before announcing —
* never interrupts.
* - **Throttle window.** At most one announcement is flushed every
* `THROTTLE_MS` (2 000 ms). If multiple events arrive within the window,
* the most recent one wins and older pending announcements are coalesced.
* - **Batch coalescing.** When multiple distinct messages arrive within
* the throttle window, they are joined into a single announcement so
* the user still hears about every meaningful change — just not 30 times
* per second.
* - **Reduced motion.** Respects `prefers-reduced-motion` by lengthening
* the throttle to `REDUCED_THROTTLE_MS` (5 000 ms), because a user who
* disables visual animation likely also prefers fewer auditory
* interruptions.
*/

const THROTTLE_MS = 2_000;
const REDUCED_THROTTLE_MS = 5_000;

interface AriaLiveContextValue {
/** Enqueue a message for the throttled polite live region. */
announce: (message: string) => void;
}

const AriaLiveContext = createContext<AriaLiveContextValue | null>(null);

/**
* Provides the throttled `aria-live="polite"` region and the `announce`
* function. Mount once near the app root (inside `Providers`).
*/
export function AriaLiveProvider({ children }: { children: React.ReactNode }) {
const [announcement, setAnnouncement] = useState("");
const queueRef = useRef<string[]>([]);
const lastFlushRef = useRef<number>(0);
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const [reducedMotion, setReducedMotion] = useState(false);

// Detect prefers-reduced-motion once on mount.
useEffect(() => {
if (typeof window === "undefined" || !window.matchMedia) return;
const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
setReducedMotion(mq.matches);
const handler = (e: MediaQueryListEvent) => setReducedMotion(e.matches);
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, []);

const flush = useCallback(() => {
// Already scheduled — the pending timer will pick up everything in the
// queue when it fires, so there's nothing to do. This is what enables
// batch coalescing: all synchronous `announce` calls in the same tick
// accumulate in the queue before any of them are flushed.
if (timerRef.current) return;

const throttleMs = reducedMotion ? REDUCED_THROTTLE_MS : THROTTLE_MS;
const now = Date.now();
const elapsed = now - lastFlushRef.current;
// If we're outside the throttle window, flush ASAP (0ms timer). If
// we're still inside it, wait for the remaining time. Using a timer
// in both cases (instead of a synchronous flush) ensures that every
// `announce` call in the current synchronous batch is queued before
// the flush runs.
const remaining = Math.max(0, throttleMs - elapsed);

timerRef.current = setTimeout(() => {
lastFlushRef.current = Date.now();
const pending = queueRef.current;
if (pending.length > 0) {
setAnnouncement(pending.join(". "));
queueRef.current = [];
}
timerRef.current = null;
}, remaining);
}, [reducedMotion]);

const announce = useCallback(
(message: string) => {
if (!message) return;
queueRef.current.push(message);
flush();
},
[flush],
);

// Clear the timer on unmount.
useEffect(() => {
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);

const value = useMemo(() => ({ announce }), [announce]);

return (
<AriaLiveContext.Provider value={value}>
{children}
{/* Visually-hidden, throttled polite live region. */}
<div aria-live="polite" aria-atomic="true" className="sr-only">
{announcement}
</div>
</AriaLiveContext.Provider>
);
}

/**
* Returns the `announce` function from the nearest `AriaLiveProvider`.
* Throws if used outside of one to catch wiring mistakes during development.
*/
export function useAriaLive(): AriaLiveContextValue {
const ctx = useContext(AriaLiveContext);
if (!ctx) {
if (process.env.NODE_ENV !== "production") {
// eslint-disable-next-line no-console
console.warn("useAriaLive called outside AriaLiveProvider — announcements will be lost");
}
// Return a no-op so the calling code doesn't crash.
return { announce: () => {} };
}
return ctx;
}
Loading