Skip to content
6 changes: 6 additions & 0 deletions templates/design/actions/list-designs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,12 @@ beforeEach(() => {
});

describe("list-designs", () => {
it("points an agent at navigate for showing the matches, since a read cannot move the view", () => {
expect(action.tool.description).toMatch(
/navigate with view=list and search/,
);
});

it("returns a bounded page with total count metadata without selecting data", async () => {
mocks.designRows = [
design("design-1", "One"),
Expand Down
4 changes: 3 additions & 1 deletion templates/design/actions/list-designs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export default defineAction({
"List design projects accessible to the current user. Pass page and " +
"pageSize for pagination; omitted values use the first bounded page. " +
"Set includeAll only for a lightweight UI picker; it returns the first " +
"bounded picker page. Returns optional HTML previews.",
"bounded picker page. Returns optional HTML previews. This only reads: " +
"to also show the user the matches, call navigate with view=list and " +
"search set to the same text.",
schema: z.object({
page: z.coerce
.number()
Expand Down
13 changes: 13 additions & 0 deletions templates/design/actions/navigate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ beforeEach(() => {
});

describe("design navigate action", () => {
it("carries a design-home search into the one-shot navigation command", async () => {
const args = { view: "list", search: "checkout" } as const;
expect(action.schema?.safeParse(args).success).toBe(true);

const result = await action.run(args);

expect(mockWriteAppStateForCurrentTab).toHaveBeenCalledWith("navigate", {
view: "list",
search: "checkout",
});
expect(result).toContain('(search: "checkout")');
});

it("carries the requested editor tool into the one-shot navigation command", async () => {
const result = await action.run({
view: "editor",
Expand Down
13 changes: 11 additions & 2 deletions templates/design/actions/navigate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const designLeftPanelSchema = z.enum([

export default defineAction({
description:
"Navigate the UI to a specific view or path. Views: list, templates, editor, present, settings. Use --templateId with templates, --designId with editor/present views. For designs, use editorView=overview to show the infinite screens canvas, or editorView=single with fileId/filename/screen to focus a screen. Use leftPanel=file|agent|assets|tools|tokens|threads to focus the left rail (file is the panel labeled Layers, with screens and the layer tree; threads is the review comment threads panel). The inspector has no tabs, so inspectorTab is accepted and ignored; the legacy value extensions still opens Tools. Use tool to activate a design editor tool. In Interact mode, use interactDevice to pick the preview device and interactTheme=light|dark|system to pick the preview color scheme.",
"Navigate the UI to a specific view or path. Views: list, templates, editor, present, settings. Use --templateId with templates, --designId with editor/present views. Use view=list with --search to land on Design home filtered by that text (for example to show the designs matching a name), from any screen including an open editor. For designs, use editorView=overview to show the infinite screens canvas, or editorView=single with fileId/filename/screen to focus a screen. Use leftPanel=file|agent|assets|tools|tokens|threads to focus the left rail (file is the panel labeled Layers, with screens and the layer tree; threads is the review comment threads panel). The inspector has no tabs, so inspectorTab is accepted and ignored; the legacy value extensions still opens Tools. Use tool to activate a design editor tool. In Interact mode, use interactDevice to pick the preview device and interactTheme=light|dark|system to pick the preview color scheme.",
Comment thread
builder-io-integration[bot] marked this conversation as resolved.
Resolved
schema: z
.object({
view: z
Expand Down Expand Up @@ -116,6 +116,14 @@ export default defineAction({
.optional()
.describe("Saved or built-in template ID for templates view"),
path: z.string().optional().describe("URL path to navigate to"),
search: z
.string()
.trim()
.max(200)
.optional()
.describe(
"With view=list: filter Design home by this text (case-insensitive match on design titles)",
),
intent: navigationIntentSchema,
})
.superRefine((args, ctx) => {
Expand Down Expand Up @@ -172,6 +180,7 @@ export default defineAction({
if (args.interactTheme) nav.interactTheme = args.interactTheme;
if (args.templateId) nav.templateId = args.templateId;
if (args.path) nav.path = args.path;
if (args.search) nav.search = args.search;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Allow identical search navigation commands to run again

This action writes the same { view, search } payload each time. The route-state consumer deduplicates identical commands by their JSON and retains the last processed key for the mounted session, so after one successful search a repeated request can be consumed without navigating while this action still returns success. Include a unique _writeId per command and test two identical consecutive navigations.

Fix in Builder

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred as non-critical after round 2; tracked in follow-up list (design search follow-ups: typed-search scope parity, route-state dedup of identical navigate commands, search arg with non-list views).

await writeAppStateForCurrentTab("navigate", nav);
return `Navigating to ${args.view || args.path}${
args.designId ? ` (design: ${args.designId})` : ""
Expand All @@ -181,7 +190,7 @@ export default defineAction({
args.fileId || args.screenId || args.filename || args.screen
? ` (screen: ${args.fileId ?? args.screenId ?? args.filename ?? args.screen})`
: ""
}${args.tool ? ` (${args.tool} tool)` : ""}${
}${args.search ? ` (search: ${JSON.stringify(args.search)})` : ""}${args.tool ? ` (${args.tool} tool)` : ""}${
args.interactDevice ? ` (device: ${args.interactDevice})` : ""
}${args.interactTheme ? ` (theme: ${args.interactTheme})` : ""}`;
},
Expand Down
22 changes: 22 additions & 0 deletions templates/design/app/hooks/use-navigation-state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,36 @@ import { describe, expect, it } from "vitest";
import { DESIGN_EDITOR_TOOLS } from "@/pages/design-editor/tool-state";

import {
commandPathFromNavigation,
designEditorCommandKeysForTab,
designSelectionCleanupKeysForTab,
designSelectionStateKeysForTab,
editorCommandFromNavigate,
editorPathFromCommand,
homeSearchFromSearchParams,
} from "./use-navigation-state";

describe("design navigation state", () => {
it("sends a list navigation with a search to Design home filtered by it", () => {
expect(
commandPathFromNavigation({ view: "list", search: "checkout" }),
).toBe("/home?search=checkout");
expect(commandPathFromNavigation({ view: "list", search: "a b&c" })).toBe(
"/home?search=a+b%26c",
);
expect(commandPathFromNavigation({ view: "list", search: " " })).toBe(
"/home",
);
expect(commandPathFromNavigation({ view: "list" })).toBe("/home");
});

it("reports the home search back in the navigation state", () => {
expect(
homeSearchFromSearchParams(new URLSearchParams("search=checkout")),
).toBe("checkout");
expect(homeSearchFromSearchParams(new URLSearchParams(""))).toBeUndefined();
});

it("defaults focused screen navigation to a readable zoom", () => {
const command = {
view: "editor",
Expand Down
42 changes: 29 additions & 13 deletions templates/design/app/hooks/use-navigation-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export interface NavigationState {
interactDevice?: string;
interactTheme?: InteractThemeMode;
path?: string;
search?: string;
}

export interface DesignEditorCommand {
Expand Down Expand Up @@ -149,6 +150,27 @@ export function editorPathFromCommand(cmd: NavigationState): string | null {
return `/design/${encodeURIComponent(cmd.designId)}${query ? `?${query}` : ""}`;
}

export function homeSearchFromSearchParams(
searchParams: URLSearchParams,
): string | undefined {
return searchParams.get("search")?.trim() || undefined;
}

export function commandPathFromNavigation(cmd: NavigationState): string {
const editorPath = editorPathFromCommand(cmd);
if (editorPath) return editorPath;
if (cmd.view === "templates") {
return cmd.templateId
? `/templates?templateId=${encodeURIComponent(cmd.templateId)}`
: "/templates";
}
if (cmd.view === "present" && cmd.designId) return `/present/${cmd.designId}`;
if (cmd.view === "settings") return "/settings";
const search = cmd.search?.trim();
if (search) return `/home?${new URLSearchParams({ search }).toString()}`;
return "/home";
}

export function editorCommandFromNavigate(
cmd: NavigationState,
path: string,
Expand Down Expand Up @@ -216,6 +238,7 @@ export function useNavigationState(enabled = true) {

useAgentRouteState<NavigationState>({
browserTabId,
writeDebounceMs: 300,
getNavigationState: ({ pathname, search }) => {
const state: NavigationState = { view: "list" };
const searchParams = new URLSearchParams(search);
Expand Down Expand Up @@ -258,21 +281,14 @@ export function useNavigationState(enabled = true) {
const templateId = searchParams.get("templateId");
if (templateId) state.templateId = templateId;

return state;
},
getCommandPath: (cmd) => {
const editorPath = editorPathFromCommand(cmd);
if (editorPath) return editorPath;
if (cmd.view === "templates") {
return cmd.templateId
? `/templates?templateId=${encodeURIComponent(cmd.templateId)}`
: "/templates";
if (state.view === "list") {
const homeSearch = homeSearchFromSearchParams(searchParams);
if (homeSearch) state.search = homeSearch;
Comment thread
builder-io-integration[bot] marked this conversation as resolved.
Resolved
}
if (cmd.view === "present" && cmd.designId)
return `/present/${cmd.designId}`;
if (cmd.view === "settings") return "/settings";
return "/home";

return state;
},
getCommandPath: commandPathFromNavigation,
onNavigate: (cmd, path) => {
const command = editorCommandFromNavigate(cmd, path);
if (command) sendDesignEditorCommand(command, browserTabId);
Expand Down
38 changes: 38 additions & 0 deletions templates/design/app/pages/Index.skip-to-editor.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,44 @@ it("offers the reference sources and creates designs with no system link", async

// oracle-change: replace generator loading, cache and timeout states with fixed prompt pools.
describe("Index skip to editor", () => {
it("filters the home list by the search in the URL", async () => {
await act(async () => root.unmount());
mocks.queryString = "search=checkout";
mocks.ownCount = 1;
root = createRoot(container);

await act(async () => root.render(<Index />));

expect(mocks.listParams).toMatchObject({ search: "checkout" });
});

it("writes typed home search into the URL so the view can be shared and restored", async () => {
await act(async () => root.unmount());
mocks.ownCount = 1;
root = createRoot(container);
await act(async () => root.render(<Index />));
const input = container.querySelector<HTMLInputElement>(
"input[data-home-search]",
);
if (!input) throw new Error("home search input not rendered");

await act(async () => {
const valueSetter = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
"value",
)?.set;
valueSetter?.call(input, "checkout");
input.dispatchEvent(new Event("input", { bubbles: true }));
});

const written = mocks.setSearchParams.mock.calls
.map((call) => call[0])
.filter(
(value): value is URLSearchParams => value instanceof URLSearchParams,
);
expect(written.map((params) => params.get("search"))).toContain("checkout");
});

it("keeps home suggestions enabled before and after connection", async () => {
mocks.agentEngine = { state: "missing", missing: true, canChat: false };
await act(async () => root.render(<Index />));
Expand Down
43 changes: 35 additions & 8 deletions templates/design/app/pages/Index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,13 @@
const isSaveTemplateGettingStarted =
searchParams.get("gettingStarted") === "save-template";
const queryClient = useQueryClient();
const [search, setSearch] = useState("");
const [designFilter, setDesignFilter] = useState<DesignFilter>(
() => readStoredDesignFilter() ?? "mine",
);
const urlSearch = searchParams.get("search") ?? "";
const lastUrlSearchRef = useRef(urlSearch);
const [search, setSearch] = useState(urlSearch);
const [designFilter, setDesignFilter] = useState<DesignFilter>(() => {
const stored = readStoredDesignFilter() ?? "mine";
return urlSearch.trim() && stored === "mine" ? "all" : stored;
});
const [page, setPage] = useState(1);
const [deleteId, setDeleteId] = useState<string | null>(null);
const [bulkDeleteOpen, setBulkDeleteOpen] = useState(false);
Expand Down Expand Up @@ -345,7 +348,7 @@
if (!hasAccessibleDesigns) {
if (isSaveTemplateGettingStarted || hasSearchResultsSection) return;
homeLibraryTabWasSelectedRef.current = false;
setHomeSection("templates");

Check warning on line 351 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(set-state-in-effect)

templates/design/app/pages/Index.tsx:351:7: Calling setState synchronously within an effect can trigger cascading renders
return;
}
if (homeLibraryTabWasSelectedRef.current) return;
Expand All @@ -359,7 +362,7 @@
isSaveTemplateGettingStarted,
]);
useEffect(() => {
if (hasSearchResultsSection) setHomeSection("recent");

Check warning on line 365 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(set-state-in-effect)

templates/design/app/pages/Index.tsx:365:34: Calling setState synchronously within an effect can trigger cascading renders
}, [hasSearchResultsSection]);
const {
data: templatesData,
Expand Down Expand Up @@ -468,7 +471,7 @@
},
);
useEffect(() => {
const handleFirstRunCompleted = () => void homeSuggestionsProfile.refetch();

Check warning on line 474 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react-hooks(exhaustive-deps)

templates/design/app/pages/Index.tsx:474:48: React Hook useEffect has a missing dependency: 'homeSuggestionsProfile'
window.addEventListener(
"agent-native:first-run-completed",
handleFirstRunCompleted,
Expand Down Expand Up @@ -540,7 +543,7 @@
homeSuggestionRole,
createHomeSuggestionRandom(homeSuggestionSeed),
),
[homeSuggestionsIdentityScope, homeSuggestionRole, homeSuggestionSeed],

Check warning on line 546 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react-hooks(exhaustive-deps)

templates/design/app/pages/Index.tsx:546:5: React Hook useMemo has unnecessary dependency: homeSuggestionsIdentityScope
);
const homeSuggestions = selectedHomeSuggestionKeys.map(
({ id, label, prompt }) => {
Expand Down Expand Up @@ -586,7 +589,7 @@

useEffect(() => {
if (!designsData || page <= totalPages) return;
setPage(totalPages);

Check warning on line 592 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(set-state-in-effect)

templates/design/app/pages/Index.tsx:592:5: Calling setState synchronously within an effect can trigger cascading renders
setSelectedDesignIds(new Set());
}, [designsData, page, totalPages]);

Expand Down Expand Up @@ -618,7 +621,7 @@
// Submitting navigates away, and unmounting discards every Figma
// attachment the context still holds; accepting hands the sent ones over.
const acceptHomeContext = useRef(homeContext.submissionAccepted);
acceptHomeContext.current = homeContext.submissionAccepted;

Check warning on line 624 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(refs)

templates/design/app/pages/Index.tsx:624:20: Cannot access refs during render

const toggleDesignSelection = useCallback((id: string) => {
setSelectedDesignIds((current) => {
Expand Down Expand Up @@ -650,14 +653,38 @@
});
}, [designs]);

const handleSearchChange = useCallback((query: string) => {
setSearch(query);
if (query.trim()) setHomeSection("recent");
const handleSearchChange = useCallback(
(query: string) => {
setSearch(query);
if (query.trim()) setHomeSection("recent");
setPage(1);
setSelectedDesignIds((current) =>
current.size === 0 ? current : new Set(),
);
lastUrlSearchRef.current = query;
const next = new URLSearchParams(searchParams);
if (query) next.set("search", query);
else next.delete("search");
if (next.toString() !== searchParams.toString()) {
setSearchParams(next, { replace: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Keep typed search scope consistent with URL-restored searches

Typing a nonempty query writes the same ?search= URL used by agent navigation, but this handler leaves designFilter at mine. Reopening that URL switches mine to all, so the same URL can show different matches depending on how it was reached; apply the URL-search scope rule here too and assert the resulting createdBy value in the typed-search test.

Fix in Builder

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deferred as non-critical after round 2; tracked in follow-up list (design search follow-ups: typed-search scope parity, route-state dedup of identical navigate commands, search arg with non-list views).

}
},
[searchParams, setSearchParams],
);

useEffect(() => {
if (lastUrlSearchRef.current === urlSearch) return;
lastUrlSearchRef.current = urlSearch;
setSearch(urlSearch);
if (urlSearch.trim()) {
setDesignFilter((current) => (current === "mine" ? "all" : current));

Check warning on line 680 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(set-state-in-effect)

templates/design/app/pages/Index.tsx:680:7: Calling setState synchronously within an effect can trigger cascading renders
}
if (urlSearch.trim()) setHomeSection("recent");
setPage(1);
setSelectedDesignIds((current) =>
current.size === 0 ? current : new Set(),
);
}, []);
}, [urlSearch]);

const handleDesignFilterChange = useCallback(
(next: "all" | "mine" | "shared") => {
Expand Down Expand Up @@ -1404,7 +1431,7 @@
<ClientOnly>
<DesignHomeLibrary
value={
hasAccessibleDesigns && !homeLibraryTabWasSelectedRef.current

Check warning on line 1434 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(refs)

templates/design/app/pages/Index.tsx:1434:15: Cannot access refs during render

Check warning on line 1434 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(refs)

templates/design/app/pages/Index.tsx:1434:39: Cannot access refs during render

Check warning on line 1434 in templates/design/app/pages/Index.tsx

View workflow job for this annotation

GitHub Actions / Lint & format

react(refs)

templates/design/app/pages/Index.tsx:1434:40: Cannot access refs during render
? "recent"
: homeSection
}
Expand Down
Loading