Skip to content

Use sveltekit-search-params to simplify query string manipulation #168

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

Merged
merged 5 commits into from
Jan 7, 2025

Conversation

sean-zlai
Copy link
Contributor

@sean-zlai sean-zlai commented Jan 3, 2025

Summary

Simplify client side query string / URL management by using sveltekit-search-params. This is especially helpful to manage types when reading and also setting/updating values without having to manually use import { page } from '$app/stores' and import { goto } from '$app/navigation' in reactive statements ($derived, $effect, etc)

Also added getSearchParamValues(searchParams, paramConfigs) to simplify getting value server side, handling type parsing and defaults with the same configs.

Checklist

  • Added Unit Tests
  • Covered by existing CI
  • Integration tested
  • Documentation update

Summary by CodeRabbit

Release Notes

  • New Dependencies

    • Added sveltekit-search-params package to improve URL parameter management.
  • Improvements

    • Streamlined sorting and metric type selection mechanisms.
    • Enhanced type safety for sort directions and metric types.
    • Simplified state management in components, including date range selection.
    • Updated data fetching and sorting logic for improved organization and performance.
  • Technical Updates

    • Refactored URL parameter handling across multiple components.
    • Updated import and function structures to support new parameter management approach.

Copy link

coderabbitai bot commented Jan 3, 2025

Walkthrough

This pull request introduces the sveltekit-search-params package to enhance query parameter management in the frontend. Key changes include refactoring sorting and metric type handling across multiple components, replacing direct URL manipulations with a more structured approach using query parameter utilities. The updates aim to streamline state management and reduce unnecessary code related to URL search parameters.

Changes

File Changes
frontend/package.json Added sveltekit-search-params as a dev dependency
frontend/src/lib/components/ActionButtons/ActionButtons.svelte Replaced handleSort with toggleSort, using queryParameters for sorting
frontend/src/lib/components/MetricTypeToggle/MetricTypeToggle.svelte Refactored metric type toggling using queryParameters
frontend/src/lib/types/MetricType/MetricType.ts Added getMetricTypeParamsConfig function
frontend/src/lib/util/sort.ts Updated SortDirection type, added getSortParamsConfig, removed updateContextSort
frontend/src/routes/joins/[slug]/+page.svelte Updated sorting logic and imports
frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte Refactored date range management with queryParameters
frontend/src/lib/constants/date-ranges.ts Updated getDateRangeByValue to accept null
frontend/src/lib/util/date-ranges.ts Added getDateRangeParamsConfig function
frontend/src/lib/util/search-params.ts Added getSearchParamValues function

Possibly related PRs

Suggested reviewers

  • ken-zlai

Poem

🌐 Params dance with grace and might,
SvelteKit's magic takes flight!
Search strings now sing their tune,
Complexity fades, simplicity blooms 🚀
Code flows like a gentle stream,
In this realm, we dare to dream!

Warning

Review ran into problems

🔥 Problems

GitHub Actions: Resource not accessible by integration - https://docs.github.com/rest/actions/workflow-runs#list-workflow-runs-for-a-repository.

Please grant the required permissions to the CodeRabbit GitHub App under the organization or repository settings.


🪧 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. (Beta)
  • @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.

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: 0

🧹 Nitpick comments (3)
frontend/src/lib/constants/date-ranges.ts (1)

64-64: Handle null more explicitly.
Return early if value is null for clarity and consistency.

 export function getDateRangeByValue(value: string | null): DateRange | undefined {
+  if (!value) {
+    return undefined;
+  }
   return DATE_RANGES.find((range) => range.value === value);
 }
frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2)

61-69: Elegant alternative to manual URL updates.
Unsure if pushHistory: false aligns with user expectations for back navigation; consider toggling it if needed.


79-93: Remove commented code if unneeded.
It clutters the file with no clear purpose.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 6ad23b1 and 53270f8.

📒 Files selected for processing (2)
  • frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (4 hunks)
  • frontend/src/lib/constants/date-ranges.ts (1 hunks)
🔇 Additional comments (3)
frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (3)

2-3: Nice imports.
Clean approach to param management with sveltekit-search-params.


25-32: Params definition is clear.
Using typed query parameters simplifies handling.


56-56: Good usage of typed timestamps.
This avoids confusion over string conversions.

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: 0

🧹 Nitpick comments (2)
frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2)

Line range hint 68-74: Validate date range order

Add check to ensure end date is after start date.

if (endDate <= startDate) {
  return; // Or show error message
}

77-86: Add type safety for range parameter

Use union type for better type safety:

function updateURLParams(
  range: typeof DATE_RANGES[number]['value'],
  start?: number,
  end?: number
)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 53270f8 and 59a940e.

📒 Files selected for processing (1)
  • frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2 hunks)
🔇 Additional comments (2)
frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2)

2-3: Clean query parameter setup!

Good choice using sveltekit-search-params with proper configuration.

Also applies to: 22-29


42-58: Add timestamp validation

Add checks for invalid timestamp values before conversion to prevent runtime errors.

if (
  (isCustomPreset && typeof params[DATE_RANGE_START_PARAM] !== 'number') ||
  (isCustomPreset && typeof params[DATE_RANGE_END_PARAM] !== 'number')
) {
  // Handle invalid timestamps
}

… range preset default to fix condition (and align with existing utils)
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: 0

🧹 Nitpick comments (12)
frontend/src/lib/util/date-ranges.ts (1)

37-43: Add doc comment
A brief doc for getDateRangeParamsConfig would help.

frontend/src/lib/types/MetricType/MetricType.ts (2)

20-29: Simplify decode
Use concise checks for METRIC_TYPES.


32-35: Reuse config
Avoid duplicating logic between getMetricTypeParamsConfig and getMetricTypeFromParams.

frontend/src/lib/util/sort.ts (1)

4-5: Clear naming
SORT_DIRECTIONS is good, maybe rename for clarity?

frontend/src/lib/components/ActionButtons/ActionButtons.svelte (4)

12-12: Maintain consistency
Organize imports similarly across files.


28-30: Effective param usage
Consider defaulting pushHistory to true if user expects it.


58-58: UI feedback
Disabled button state might confuse users.


60-60: Inline text
"Sort A-Z" might be "Ascending" for clarity.

frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (1)

40-55: Add error handling for invalid dates

The effect block should handle cases where fromAbsolute might fail with invalid timestamps.

 $effect(() => {
   const selectedRange = selectDateRange?.getRange();
   const isCustomPreset = selectDateRange?.value === CUSTOM;
   untrack(() => {
+    try {
       calendarDateRange = {
         start: fromAbsolute(
           isCustomPreset ? params[DATE_RANGE_START_PARAM] : selectedRange?.[0],
           getLocalTimeZone()
         ),
         end: fromAbsolute(
           isCustomPreset ? params[DATE_RANGE_END_PARAM] : selectedRange?.[1],
           getLocalTimeZone()
         )
       };
+    } catch (error) {
+      console.error('Invalid date range:', error);
+      calendarDateRange = { start: undefined, end: undefined };
+    }
   });
 });
frontend/src/routes/joins/[slug]/+page.svelte (3)

455-461: Add type safety for sort parameters

Consider using a type-safe approach for sort parameters.

-const sortKey = getSortParamKey(sortContext);
+const sortKey = getSortParamKey(sortContext) as keyof ReturnType<typeof getSortParamsConfig>;

Line range hint 392-421: Add debouncing to prevent concurrent loads

Consider adding debouncing to prevent multiple rapid calls to loadDistributions.

+let loadDebounceTimeout: NodeJS.Timeout;
 async function loadDistributions() {
   if (distributions.length > 0 || isLoadingDistributions) return;
+  clearTimeout(loadDebounceTimeout);
+  loadDebounceTimeout = setTimeout(async () => {
     isLoadingDistributions = true;
     try {
       // ... existing code ...
     } finally {
       isLoadingDistributions = false;
     }
+  }, 300);
 }

Line range hint 464-497: Add cleanup for stale events

Consider clearing selectedEvents when the matching point is not found.

 if (updatedPoint) {
   selectedEvents = [
     {
       ...selectedEvents[0],
       data: updatedPoint
     }
   ];
+} else {
+  selectedEvents = [];
+  isSheetOpen = false;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 59a940e and b7f4756.

📒 Files selected for processing (7)
  • frontend/src/lib/components/ActionButtons/ActionButtons.svelte (4 hunks)
  • frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2 hunks)
  • frontend/src/lib/components/MetricTypeToggle/MetricTypeToggle.svelte (1 hunks)
  • frontend/src/lib/types/MetricType/MetricType.ts (2 hunks)
  • frontend/src/lib/util/date-ranges.ts (2 hunks)
  • frontend/src/lib/util/sort.ts (1 hunks)
  • frontend/src/routes/joins/[slug]/+page.svelte (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/lib/components/MetricTypeToggle/MetricTypeToggle.svelte
🔇 Additional comments (8)
frontend/src/lib/util/date-ranges.ts (1)

8-8: Use ssp import
Good addition for param parsing.

frontend/src/lib/types/MetricType/MetricType.ts (1)

1-1: Check import path
Ensure EncodeAndDecodeOptions import is correct.

frontend/src/lib/util/sort.ts (2)

2-2: Check import version
Make sure we’re pulling from the right subpath.


12-22: Type safety
The encode/decode approach is neat.

frontend/src/lib/components/ActionButtons/ActionButtons.svelte (2)

2-3: Unused imports
Check if removed imports affect other components.


33-34: Naming
toggleSort is clear and minimal.

frontend/src/lib/components/DateRangeSelector/DateRangeSelector.svelte (2)

23-26: LGTM: Clean parameter configuration

Parameter configuration with pushHistory: false and showDefaults: false is appropriate for this use case.


74-83: LGTM: Clean parameter updates

Good practice using null to clear unused parameters.

…params config to get values from URLSearchParams (particularly useful server side)
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)
frontend/src/lib/util/search-params.ts (1)

10-14: Add error handling for invalid parameter configurations

Consider adding try-catch to handle potential decode failures.

 const paramEntries = Object.entries(paramsConfig).map(([paramName, paramConfig]) => {
   const value = searchParams.get(paramName);
-  let decodedValue = paramConfig.decode(value) ?? paramConfig.defaultValue;
+  let decodedValue;
+  try {
+    decodedValue = paramConfig.decode(value) ?? paramConfig.defaultValue;
+  } catch (error) {
+    console.warn(`Failed to decode ${paramName}:`, error);
+    decodedValue = paramConfig.defaultValue;
+  }
   return [paramName, decodedValue];
 });
frontend/src/lib/types/MetricType/MetricType.ts (1)

24-24: Validate input in encode function

Add type validation to encode function.

-encode: (value) => value,
+encode: (value: MetricType) => METRIC_TYPES.includes(value) ? value : DEFAULT_METRIC_TYPE,
frontend/src/lib/util/date-ranges.ts (1)

29-29: Use strict equality check

Replace == with === for null check.

-if (paramValues[DATE_RANGE_START_PARAM] == null || paramValues[DATE_RANGE_END_PARAM] == null) {
+if (paramValues[DATE_RANGE_START_PARAM] === null || paramValues[DATE_RANGE_END_PARAM] === null) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between b7f4756 and 1d277d3.

📒 Files selected for processing (3)
  • frontend/src/lib/types/MetricType/MetricType.ts (2 hunks)
  • frontend/src/lib/util/date-ranges.ts (1 hunks)
  • frontend/src/lib/util/search-params.ts (1 hunks)

Comment on lines +29 to +32
if (paramValues[DATE_RANGE_START_PARAM] == null || paramValues[DATE_RANGE_END_PARAM] == null) {
const [start, end] = getDateRange(paramValues[DATE_RANGE_PARAM] || PAST_1_WEEK);
paramValues[DATE_RANGE_START_PARAM] = start;
paramValues[DATE_RANGE_END_PARAM] = end;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timestamp validation

Ensure start timestamp is before end timestamp.

 if (paramValues[DATE_RANGE_START_PARAM] == null || paramValues[DATE_RANGE_END_PARAM] == null) {
   const [start, end] = getDateRange(paramValues[DATE_RANGE_PARAM] || PAST_1_WEEK);
   paramValues[DATE_RANGE_START_PARAM] = start;
   paramValues[DATE_RANGE_END_PARAM] = end;
+} else if (paramValues[DATE_RANGE_START_PARAM] > paramValues[DATE_RANGE_END_PARAM]) {
+  const [start, end] = getDateRange(PAST_1_WEEK);
+  paramValues[DATE_RANGE_START_PARAM] = start;
+  paramValues[DATE_RANGE_END_PARAM] = end;
 }
📝 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
if (paramValues[DATE_RANGE_START_PARAM] == null || paramValues[DATE_RANGE_END_PARAM] == null) {
const [start, end] = getDateRange(paramValues[DATE_RANGE_PARAM] || PAST_1_WEEK);
paramValues[DATE_RANGE_START_PARAM] = start;
paramValues[DATE_RANGE_END_PARAM] = end;
if (paramValues[DATE_RANGE_START_PARAM] == null || paramValues[DATE_RANGE_END_PARAM] == null) {
const [start, end] = getDateRange(paramValues[DATE_RANGE_PARAM] || PAST_1_WEEK);
paramValues[DATE_RANGE_START_PARAM] = start;
paramValues[DATE_RANGE_END_PARAM] = end;
} else if (paramValues[DATE_RANGE_START_PARAM] > paramValues[DATE_RANGE_END_PARAM]) {
const [start, end] = getDateRange(PAST_1_WEEK);
paramValues[DATE_RANGE_START_PARAM] = start;
paramValues[DATE_RANGE_END_PARAM] = end;
}

@sean-zlai sean-zlai requested a review from ken-zlai January 6, 2025 20:11
Copy link
Contributor

@ken-zlai ken-zlai left a comment

Choose a reason for hiding this comment

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

I really like sveltekit-search-params. Clean code for handling search parameters :)

@sean-zlai sean-zlai merged commit 302c018 into main Jan 7, 2025
3 of 4 checks passed
@sean-zlai sean-zlai deleted the sean/sveltekit-search-params branch January 7, 2025 16:36
@coderabbitai coderabbitai bot mentioned this pull request Jan 17, 2025
4 tasks
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.

3 participants