Skip to content

Embed filter selection in query params #276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

brendan-kellam
Copy link
Contributor

@brendan-kellam brendan-kellam commented Apr 26, 2025

This PR changes the filter panel to embed the filter selection into query parameters to make it easier to share search results. For example:

image

http://localhost:3000/~/search?query=hello&repos=github.com%2Fsourcebot-dev%2Fsourcebot&langs=JSON%2CTSX

#166

Summary by CodeRabbit

  • New Features

    • Filter selections in the filter panel are now synchronized with the URL, allowing filter state to be preserved on reload and easily shared via link.
  • Bug Fixes

    • The loading indicator now accurately displays when either search results or repository metadata are loading.
  • Documentation

    • Updated the changelog to document the new filter state behavior.
  • Style

    • Improved variable naming for clarity in internal logic (no user-facing changes).

@brendan-kellam brendan-kellam requested a review from msukkari April 26, 2025 23:06
Copy link

coderabbitai bot commented Apr 26, 2025

Walkthrough

This update synchronizes the filter selection state in the filter panel with the URL query parameters, enabling deep linking and state persistence across reloads and navigation. The FilterPanel component now reads and updates selected repositories and languages directly from the URL, and modifies the query parameters as selections change. Additionally, variable naming in search and hook components was clarified for better code readability, and the loading state logic in the search page was updated to reflect both search and repository metadata loading states. The changelog was updated to document these changes.

Changes

File(s) Change Summary
CHANGELOG.md Added entry documenting that filter selection state is now embedded in query parameters, referencing PR #276.
packages/web/src/app/[domain]/search/components/filterPanel/index.tsx Refactored FilterPanel to synchronize filter state with URL query parameters using Next.js hooks; updated effects logic.
packages/web/src/app/[domain]/search/page.tsx Renamed loading state variables for clarity; updated loading spinner to check both search and repo metadata loading.
packages/web/src/hooks/useNonEmptyQueryParam.ts Renamed internal variable from inviteId to paramValue for clarity; no functional changes.

Poem

In the warren of code, a panel now sings,
Filters and queries with synchronized wings.
URLs remember what bunnies select,
So sharing and reloading work as you'd expect.
With clearer names and loading in view,
This rabbit hops forward—onward, anew!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

msukkari
msukkari previously approved these changes Apr 26, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
CHANGELOG.md (1)

10-12: Minor wording nit

To stay consistent with Keep-a-Changelog style (“Added / Changed / Fixed … : …”), consider trimming the redundant “Changed” prefix:

-### Changed
-- Changed the filter panel to embed the filter selection state in the query params.
+### Changed
+- The filter panel now embeds the filter-selection state in the query params.
🧰 Tools
🪛 LanguageTool

[duplication] ~10-~10: Possible typo: you repeated a word.
Context: ...pec/v2.0.0.html). ## [Unreleased] ### Changed - Changed the filter panel to embed the filter se...

(ENGLISH_WORD_REPEAT_RULE)

packages/web/src/app/[domain]/search/components/filterPanel/index.tsx (2)

100-115: Extraneous dependencies trigger superfluous re-filtering

router is listed in the dependency array but isn’t referenced in the effect body; including it causes the effect to run on every navigation event even when filter state didn’t change.

-}, [matches, repos, languages, onFilterChanged, searchParams, router]);
+}, [matches, repos, languages, onFilterChanged, searchParams]);

116-139: Safer URL replacement – keep explicit pathname

Using router.replace('?…') relies on implicit relative resolution.
When the current route contains optional catch-all segments it can break (e.g. /org/foo/search). Prepend the existing pathname for robustness:

-            router.replace(`?${newParams.toString()}`, { scroll: false });
+            router.replace(`${window.location.pathname}?${newParams.toString()}`, { scroll: false });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 78ec512 and 44d5e56.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • packages/web/src/app/[domain]/search/components/filterPanel/index.tsx (4 hunks)
  • packages/web/src/app/[domain]/search/page.tsx (3 hunks)
  • packages/web/src/hooks/useNonEmptyQueryParam.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/web/src/app/[domain]/search/components/filterPanel/index.tsx (1)
packages/web/src/lib/types.ts (2)
  • SearchResultFile (11-11)
  • Repository (20-20)
🪛 LanguageTool
CHANGELOG.md

[duplication] ~10-~10: Possible typo: you repeated a word.
Context: ...pec/v2.0.0.html). ## [Unreleased] ### Changed - Changed the filter panel to embed the filter se...

(ENGLISH_WORD_REPEAT_RULE)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (4)
packages/web/src/hooks/useNonEmptyQueryParam.ts (1)

20-24: Readable rename – looks good

Changing inviteIdparamValue makes the variable purpose clearer without touching behaviour. No further action required.

packages/web/src/app/[domain]/search/page.tsx (3)

50-63: Clearer loading-state names – approved

Renaming to isSearchLoading & isRepoMetadataLoading eliminates ambiguity and makes the below conditional far easier to follow.


94-108: Consistent naming adopted in repo-metadata query

The rename propagates correctly here; logic remains unchanged.

🧰 Tools
🪛 Biome (1.9.4)

[error] 102-102: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)


197-203: Improved UX – spinner covers both async calls

Showing the loader while either query is inflight prevents flashes of un-initialised UI. Nice touch.

Comment on lines +28 to +37
const router = useRouter();
const searchParams = useSearchParams();

// Helper to parse query params into sets
const getSelectedFromQuery = (param: string) => {
const value = searchParams.get(param);
return value ? new Set(value.split(',')) : new Set();
};

const [repos, setRepos] = useState<Record<string, Entry>>(() => {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

State desynchronises when the URL is changed via browser navigation

repos and languages are initialised from the query string only once (the useState initialiser).
If the user:

  1. toggles filters (pushes a new URL),
  2. presses the browser “Back” button,

the query params revert but the repos / languages state does not, so the UI and filtering logic become inconsistent.

Add an effect that re-hydrates the state whenever searchParams changes:

+// Keep local state in sync if the URL changes externally
+useEffect(() => {
+    setRepos(prev => {
+        const selected = getSelectedFromQuery(REPOS_QUERY_PARAM);
+        return Object.fromEntries(
+            Object.entries(prev).map(([k, v]) => [
+                k,
+                { ...v, isSelected: selected.has(k) }
+            ]),
+        );
+    });
+    setLanguages(prev => {
+        const selected = getSelectedFromQuery(LANGUAGES_QUERY_PARAM);
+        return Object.fromEntries(
+            Object.entries(prev).map(([k, v]) => [
+                k,
+                { ...v, isSelected: selected.has(k) }
+            ]),
+        );
+    });
+}, [searchParams]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const router = useRouter();
const searchParams = useSearchParams();
// Helper to parse query params into sets
const getSelectedFromQuery = (param: string) => {
const value = searchParams.get(param);
return value ? new Set(value.split(',')) : new Set();
};
const [repos, setRepos] = useState<Record<string, Entry>>(() => {
const router = useRouter();
const searchParams = useSearchParams();
// Helper to parse query params into sets
const getSelectedFromQuery = (param: string) => {
const value = searchParams.get(param);
return value ? new Set(value.split(',')) : new Set();
};
const [repos, setRepos] = useState<Record<string, Entry>>(() => {
// initial repos setup...
});
const [languages, setLanguages] = useState<Record<string, Entry>>(() => {
// initial languages setup...
});
// Keep local state in sync if the URL changes externally
useEffect(() => {
setRepos(prev => {
const selected = getSelectedFromQuery(REPOS_QUERY_PARAM);
return Object.fromEntries(
Object.entries(prev).map(([k, v]) => [
k,
{ ...v, isSelected: selected.has(k) }
]),
);
});
setLanguages(prev => {
const selected = getSelectedFromQuery(LANGUAGES_QUERY_PARAM);
return Object.fromEntries(
Object.entries(prev).map(([k, v]) => [
k,
{ ...v, isSelected: selected.has(k) }
]),
);
});
}, [searchParams]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants