diff --git a/frontend/src/pages/MarketplacePage.test.tsx b/frontend/src/pages/MarketplacePage.test.tsx
index f7586e4..6be69b0 100644
--- a/frontend/src/pages/MarketplacePage.test.tsx
+++ b/frontend/src/pages/MarketplacePage.test.tsx
@@ -1,6 +1,6 @@
-import { render, screen, within } from "@testing-library/react";
+import { act, fireEvent, render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { MemoryRouter } from "react-router-dom";
+import { MemoryRouter, Route, Routes, useLocation, useNavigate } from "react-router-dom";
import { afterEach, describe, expect, it, vi } from "vitest";
// Block the real Wails runtime: importing it registers a module-level timer in
@@ -68,6 +68,35 @@ afterEach(() => {
sessionStorage.clear();
});
+function LocationProbe() {
+ const location = useLocation();
+ return ;
+}
+
+// Stands in for the detail page, which goes back to the recorded returnTo.
+function DetailBackProbe() {
+ const navigate = useNavigate();
+ const { returnTo } = useLocation().state as { returnTo: string };
+ return ;
+}
+
+function renderMarketplaceRoutes() {
+ render(
+
+
+
+
+ } />
+ } />
+
+
+ ,
+ );
+}
+
+const currentLocation = () => screen.getByTestId("location").textContent;
+const searchBox = () => screen.getByRole("textbox", { name: "Search Marketplace" });
+
describe("filterMarketplaceItems", () => {
it("returns all items when category is 'all' and query is empty", () => {
expect(filterMarketplaceItems(ITEMS, "all", "")).toHaveLength(3);
@@ -208,6 +237,34 @@ describe("MarketplacePage category URL", () => {
});
});
+ it("keeps search text typed just before opening a card when going back", () => {
+ renderMarketplaceRoutes();
+
+ // No timer runs between the two events, so the 180ms debounce is pending.
+ fireEvent.change(searchBox(), { target: { value: "ultracode" } });
+ expect(currentLocation()).toBe("/marketplace");
+ fireEvent.click(screen.getByRole("link", { name: "Ultracode Skill" }));
+
+ expect(currentLocation()).toBe("/marketplace/skill-a");
+ expect(readMarketplaceQuerySession()?.returnTo).toBe("/marketplace?q=ultracode");
+
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ expect(currentLocation()).toBe("/marketplace?q=ultracode");
+ expect(searchBox().value).toBe("ultracode");
+ });
+
+ it("keeps both the pending search text and a filter changed in the same moment", async () => {
+ renderMarketplaceRoutes();
+ fireEvent.click(screen.getByRole("button", { name: "Tool type" }));
+
+ fireEvent.change(searchBox(), { target: { value: "ultracode" } });
+ fireEvent.click(screen.getByLabelText("Skill"));
+ expect(currentLocation()).toBe("/marketplace?q=ultracode&kind=skill");
+
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 250)); });
+ expect(currentLocation()).toBe("/marketplace?q=ultracode&kind=skill");
+ });
+
it("does not expose filter values or top-level resource categories without tool supply", async () => {
const user = userEvent.setup();
render(
diff --git a/frontend/src/pages/MarketplacePage.tsx b/frontend/src/pages/MarketplacePage.tsx
index 8f8fcc3..485428c 100644
--- a/frontend/src/pages/MarketplacePage.tsx
+++ b/frontend/src/pages/MarketplacePage.tsx
@@ -407,7 +407,13 @@ export function KindBadge({ item }: { item: MarketplaceItem }) {
return {kinds.length > 1 ? +{kinds.length - 1} : null};
}
-function VirtualMarketplaceGrid({ items, onCopied }: { items: MarketplaceItem[]; onCopied: (item: MarketplaceItem) => void }) {
+type MarketplaceCardProps = {
+ onCopied: (item: MarketplaceItem) => void;
+ // Returns the list's query string after committing any debounced search text.
+ currentSearch: () => string;
+};
+
+function VirtualMarketplaceGrid({ items, onCopied, currentSearch }: { items: MarketplaceItem[] } & MarketplaceCardProps) {
const [scrollTop, setScrollTop] = useState(0);
const [viewportHeight, setViewportHeight] = useState(() => window.innerHeight);
const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth);
@@ -436,7 +442,7 @@ function VirtualMarketplaceGrid({ items, onCopied }: { items: MarketplaceItem[];
// as if it had added results when the unfiltered virtual list was already
// showing only its viewport. Small result sets remain fully accessible.
if (items.length <= 24) {
- return ;
+ return ;
}
const rowCount = Math.ceil(items.length / columns);
const topRow = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
@@ -447,7 +453,7 @@ function VirtualMarketplaceGrid({ items, onCopied }: { items: MarketplaceItem[];
return <>
- {items.slice(start, end).map((item) => )}
+ {items.slice(start, end).map((item) => )}
>;
@@ -481,13 +487,13 @@ function CardIcon({ item }: { item: MarketplaceItem }) {
return ;
}
-function MarketplaceItemCard({ item, onCopied }: { item: MarketplaceItem; onCopied: (item: MarketplaceItem) => void }) {
+function MarketplaceItemCard({ item, onCopied, currentSearch }: { item: MarketplaceItem } & MarketplaceCardProps) {
const { t, locale } = useI18n();
const navigate = useNavigate();
const location = useLocation();
- const returnTo = `${location.pathname}${location.search}`;
const openDetail = () => {
recordMarketplaceEvent("item_open", item.source);
+ const returnTo = `${location.pathname}${currentSearch()}`;
const container = document.querySelector(".page-body.marketplace-page");
saveMarketplaceQuerySession({ returnTo, scrollTop: container?.scrollTop ?? 0 });
navigate(`/marketplace/${encodeURIComponent(item.id)}`, { state: { returnTo, item } });
@@ -617,8 +623,15 @@ export function MarketplacePage() {
const [recommendationOpen, setRecommendationOpen] = useState(false);
const noticeTimer = useRef | null>(null);
const queryTimer = useRef | null>(null);
- const searchParamsRef = useRef(searchParams);
- searchParamsRef.current = searchParams;
+ const pendingQuery = useRef(null);
+ // A URL write is visible here before its render, so two writes in a row
+ // build on each other instead of on the same stale render.
+ const latestParams = useRef(searchParams);
+ const renderedParams = useRef(searchParams);
+ if (renderedParams.current !== searchParams) {
+ renderedParams.current = searchParams;
+ latestParams.current = searchParams;
+ }
useEffect(() => {
const session = readMarketplaceQuerySession();
@@ -673,41 +686,66 @@ export function MarketplacePage() {
// Empty type tabs are hidden until a trusted adapter supplies an item.
const visibleCategories = CATEGORIES.filter(({ id }) => id === "all" || (counts[id] ?? 0) > 0);
+ const commitParams = (next: URLSearchParams, options?: { replace?: boolean }) => {
+ latestParams.current = next;
+ setSearchParams(next, options);
+ };
+
+ // Folds the debounced search text into the latest params and cancels its
+ // timer. The caller must commit the result.
+ const paramsWithPendingQuery = () => {
+ const next = new URLSearchParams(latestParams.current);
+ const pending = pendingQuery.current;
+ if (pending === null) return next;
+ if (queryTimer.current) clearTimeout(queryTimer.current);
+ queryTimer.current = null;
+ pendingQuery.current = null;
+ if (pending.trim()) next.set("q", pending);
+ else next.delete("q");
+ return next;
+ };
+
+ const flushQuery = () => {
+ if (pendingQuery.current !== null) commitParams(paramsWithPendingQuery(), { replace: true });
+ return latestParams.current;
+ };
+
+ // Opening a card inside the debounce window would otherwise unmount the page
+ // with the search text still uncommitted, and Back would return without it.
+ const flushedSearch = () => {
+ const search = flushQuery().toString();
+ return search ? `?${search}` : "";
+ };
+
const selectCategory = (category: MarketplaceCategory | "all") => {
- const next = new URLSearchParams(searchParams);
+ const next = new URLSearchParams(latestParams.current);
if (category === "all") next.delete("category");
else next.set("category", category);
next.delete("q");
- setSearchParams(next, { replace: true });
+ commitParams(next, { replace: true });
};
const updateQuery = (value: string) => {
if (queryTimer.current) clearTimeout(queryTimer.current);
- queryTimer.current = setTimeout(() => {
- const next = new URLSearchParams(searchParamsRef.current);
- if (value.trim()) next.set("q", value);
- else next.delete("q");
- setSearchParams(next, { replace: true });
- queryTimer.current = null;
- }, 180);
+ pendingQuery.current = value;
+ queryTimer.current = setTimeout(() => commitParams(paramsWithPendingQuery(), { replace: true }), 180);
};
const updateFilters = (nextFilters: FilterState) => {
recordMarketplaceEvent("filter_change");
- const next = serializeMarketplaceFilters(searchParams, nextFilters);
- setSearchParams(next, { replace: true });
+ commitParams(serializeMarketplaceFilters(paramsWithPendingQuery(), nextFilters), { replace: true });
};
const historyOpen = searchParams.get("recommendationHistory") === "1";
const openHistory = () => {
- const next = new URLSearchParams(searchParams);
+ const next = new URLSearchParams(flushQuery());
next.set("recommendationHistory", "1");
- setSearchParams(next);
+ commitParams(next);
};
const closeHistory = () => {
- const next = new URLSearchParams(searchParams);
+ const next = paramsWithPendingQuery();
next.delete("recommendationHistory");
- setSearchParams(next, { replace: true });
+ commitParams(next, { replace: true });
};
return (
@@ -800,7 +838,7 @@ export function MarketplacePage() {
}
/>
) : (
-
+
)}