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
61 changes: 59 additions & 2 deletions frontend/src/pages/MarketplacePage.test.tsx
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -68,6 +68,35 @@ afterEach(() => {
sessionStorage.clear();
});

function LocationProbe() {
const location = useLocation();
return <output data-testid="location">{`${location.pathname}${location.search}`}</output>;
}

// 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 <button type="button" onClick={() => navigate(returnTo)}>Back</button>;
}

function renderMarketplaceRoutes() {
render(
<I18nProvider>
<MemoryRouter initialEntries={["/marketplace"]}>
<LocationProbe />
<Routes>
<Route path="/marketplace" element={<MarketplacePage />} />
<Route path="/marketplace/:id" element={<DetailBackProbe />} />
</Routes>
</MemoryRouter>
</I18nProvider>,
);
}

const currentLocation = () => screen.getByTestId("location").textContent;
const searchBox = () => screen.getByRole<HTMLInputElement>("textbox", { name: "Search Marketplace" });

describe("filterMarketplaceItems", () => {
it("returns all items when category is 'all' and query is empty", () => {
expect(filterMarketplaceItems(ITEMS, "all", "")).toHaveLength(3);
Expand Down Expand Up @@ -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(
Expand Down
84 changes: 61 additions & 23 deletions frontend/src/pages/MarketplacePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,13 @@ export function KindBadge({ item }: { item: MarketplaceItem }) {
return <span className="marketplace-kind-group" title={kinds.join(", ")} aria-label={kinds.join(", ")}><MarketplaceKindBadge kind={kinds[0]} />{kinds.length > 1 ? <span className="marketplace-kind-more">+{kinds.length - 1}</span> : null}</span>;
}

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);
Expand Down Expand Up @@ -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 <ul className="marketplace-grid" aria-label="工具列表">{items.map((item) => <li key={item.id}><MarketplaceItemCard item={item} onCopied={onCopied} /></li>)}</ul>;
return <ul className="marketplace-grid" aria-label="工具列表">{items.map((item) => <li key={item.id}><MarketplaceItemCard item={item} onCopied={onCopied} currentSearch={currentSearch} /></li>)}</ul>;
}
const rowCount = Math.ceil(items.length / columns);
const topRow = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
Expand All @@ -447,7 +453,7 @@ function VirtualMarketplaceGrid({ items, onCopied }: { items: MarketplaceItem[];
return <>
<div style={{ height: topRow * rowHeight }} aria-hidden="true" />
<ul className="marketplace-grid" aria-label="工具列表">
{items.slice(start, end).map((item) => <li key={item.id}><MarketplaceItemCard item={item} onCopied={onCopied} /></li>)}
{items.slice(start, end).map((item) => <li key={item.id}><MarketplaceItemCard item={item} onCopied={onCopied} currentSearch={currentSearch} /></li>)}
</ul>
<div style={{ height: Math.max(0, (rowCount - endRow) * rowHeight + (endRow < rowCount ? gridGap : 0)) }} aria-hidden="true" />
</>;
Expand Down Expand Up @@ -481,13 +487,13 @@ function CardIcon({ item }: { item: MarketplaceItem }) {
return <ItemIcon name={item.icon} color={item.iconColor} />;
}

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<HTMLElement>(".page-body.marketplace-page");
saveMarketplaceQuerySession({ returnTo, scrollTop: container?.scrollTop ?? 0 });
navigate(`/marketplace/${encodeURIComponent(item.id)}`, { state: { returnTo, item } });
Expand Down Expand Up @@ -617,8 +623,15 @@ export function MarketplacePage() {
const [recommendationOpen, setRecommendationOpen] = useState(false);
const noticeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const queryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const searchParamsRef = useRef(searchParams);
searchParamsRef.current = searchParams;
const pendingQuery = useRef<string | null>(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();
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -800,7 +838,7 @@ export function MarketplacePage() {
}
/>
) : (
<VirtualMarketplaceGrid items={visible} onCopied={handleCopied} />
<VirtualMarketplaceGrid items={visible} onCopied={handleCopied} currentSearch={flushedSearch} />
)}
</div>
</div>
Expand Down
Loading