Skip to content

fix: Adjust links and search path with locale - #3214

Merged
hellofanny merged 9 commits into
feat/multilanguagefrom
chore/adjust-links-search
Feb 20, 2026
Merged

hellofanny merged 9 commits into
feat/multilanguagefrom
chore/adjust-links-search

Conversation

@hellofanny

@hellofanny hellofanny commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

  • Centralize link resolution so internal links always get the correct locale/context: either a custom path prefix (e.g. /europe/it/...) when on a custom path page, or the Next.js locale prefix (e.g. /pt-BR/...) when localization is enabled and the current locale is not the default.

  • Keep search URLs aligned with the rest of the application: when search state is applied, the URL written is resolved through the same logic so it keeps the current locale or custom path instead of always using /s.

Problematic behaviour:

busca_verde.mov

How it works?

useLink

  • For internal paths (/...), resolveLink(href):
  1. Calls addCustomPathPrefix(href, asPath) so links get the current custom path prefix when the user is on a custom-path page (e.g. /europe/it).
  2. If no custom path was applied and localization is enabled, the current locale is not the default, and the user is not on a custom-path page, it prepends the Next.js locale (e.g. /pt-BR/s).
  3. Otherwise it returns the path unchanged. External or non-absolute URLs are returned as-is. When localization is disabled, internal links are returned unchanged.
  4. OnCustomPath check when the current page is under a custom path, so we don’t add the Next.js locale segment on those pages (locale is already in the path).

Search state

useApplySearchState runs the new search URL through resolveLink() before calling replaceState, so the URL in the url and history keeps the correct locale or custom path (e.g. /europe/it/s?q=shoes or /pt-BR/s?q=shoes instead of /s?q=shoes when that would be wrong).

How to test it?

Use the instructions here to run the project locally and set the binding and enable localization.

Scenario 1:

search_link_locale.mov

Scenario 2: With custom paths

search-link-custom-path.mov

note: we still need to adjust the search history scenario, it will redirect to the "correct" url, but we are currently saving all the search history terms using the same locale key. (task to address it)
image

References

Jira Tasks:

Summary by CodeRabbit

  • Refactor

    • Search components now use a hook-based path formatter and consistent resolved URLs for navigation, improving behavior across inputs, suggestions, and top results.
    • Link resolution was enhanced to preserve locale and custom-path context when building hrefs.
  • New Features

    • Added a search base resolver hook to ensure localized search links honor custom prefixes.
  • Chores

    • Exported the custom-path extractor for reuse.

- Add useSearchBase hook using useLink resolveLink for /s base path
- Use useSearchBase in SearchTop, SearchInput, and SearchDropdown
- Search links to respect locale and custom path (/emea-eur/s and /pt-BR/s)
when search state is applied (filters, sort) - updates the browser URL through resolveLink before writing it to handle localization paths
helps internal link decides if use  custom path prefix or next.js locale prefix
@coderabbitai

coderabbitai Bot commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉


Walkthrough

Replaced direct search-path formatting with a hook-based approach: added useFormatSearchPath and useSearchBase, updated search components to call the hook, and enhanced link resolution (useLink) and search state handling to produce locale- and custom-path-aware search URLs. No public export removals; new types/hooks added.

Changes

Cohort / File(s) Summary
Search Components
packages/core/src/components/search/SearchDropdown/SearchDropdown.tsx, packages/core/src/components/search/SearchInput/SearchInput.tsx, packages/core/src/components/search/SearchTop/SearchTop.tsx
Replaced direct formatSearchPath imports with useFormatSearchPath(); components now call the hook to obtain formatSearchPath and use it for href/onClick navigation.
Search SDK Core
packages/core/src/sdk/search/formatSearchPath.ts
Added FormatSearchPathParams type; formatSearchPath accepts an optional base (default DEFAULT_SEARCH_BASE); exported useFormatSearchPath() hook that binds the resolved base via useSearchBase.
Locale-Aware Base Resolution
packages/core/src/sdk/search/useSearchBase.ts
New useSearchBase() hook that resolves canonical search base using useLink/resolveLink (falls back to /s).
Search State & Link Resolution
packages/core/src/sdk/search/state.ts, packages/core/src/sdk/ui/useLink.ts
useApplySearchState now resolves URLs via resolveLink and uses resolved URL for history.replaceState; useLink updated to apply custom-path prefixes and locale-prefixed routing when appropriate (considers router.asPath, router.locale, defaultLocale, and custom-path detection).
Localization Utilities
packages/core/src/utils/localization/customPaths.ts
Made extractCustomPathPrefix() exported so link/base resolution can detect custom-path pages.

Sequence Diagram

sequenceDiagram
    participant SC as Search Component
    participant UFS as useFormatSearchPath
    participant USB as useSearchBase
    participant UL as useLink/resolveLink
    participant Router as Router

    SC->>UFS: call useFormatSearchPath()
    activate UFS
    UFS->>USB: call useSearchBase()
    activate USB
    USB->>UL: resolveLink("/s")
    activate UL
    UL->>Router: inspect asPath, locale, custom prefixes
    Router-->>UL: resolved base path
    deactivate UL
    USB-->>UFS: return resolved base
    deactivate USB
    UFS->>UFS: bind formatSearchPath(params, base)
    UFS-->>SC: return bound format function
    deactivate UFS
    SC->>SC: compute href via bound format function and use in link/navigation
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • emersonlaurentino
  • lariciamota
  • lemagnetic

Poem

🔎 Hooks rewired where search paths roam,
Locale and custom prefixes guide us home,
Links resolve steady across each land,
Paths bound by hooks, tidy and planned,
A small change maps a smoother roam ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: Adjust links and search path with locale' accurately describes the main change—centralizing link and search path resolution to respect locale and custom path contexts across multiple components and utilities.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/adjust-links-search

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Feb 19, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@hellofanny
hellofanny marked this pull request as ready for review February 19, 2026 02:39
@hellofanny
hellofanny requested a review from a team as a code owner February 19, 2026 02:39
@hellofanny
hellofanny requested review from emersonlaurentino and lariciamota and removed request for a team February 19, 2026 02:39

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/core/src/components/search/SearchDropdown/SearchDropdown.tsx (1)

64-95: formatSearchPath called with identical args on lines 70 and 74 — minor redundancy.

The href computed on line 70 (for the anchor's href prop) and on line 74 (inside onClick) use the same { term: suggestion, sort } arguments. You could reuse the anchor's href or lift the computation:

Suggested simplification
        {terms?.map(({ value: suggestion }) => {
+         const suggestionPath = formatSearchPath({ term: suggestion, sort })
+         return (
          <UISearchAutoCompleteTerm
            key={suggestion}
            term={term}
            suggestion={suggestion}
            linkProps={{
-             href: formatSearchPath({ term: suggestion, sort }),
+             href: suggestionPath,
              onClick: async (event: React.MouseEvent<HTMLAnchorElement>) => {
                event.preventDefault()

-               const href = formatSearchPath({ term: suggestion, sort })
-
                // Execute search selection callback
                onSearchSelection?.(
                  term,
                  formatSearchPath({ term: term, sort })
                )

                // Wait for analytics event to complete
                try {
                  await sendAutocompleteClickEvent({
                    term: term,
                    url: window.location.href,
                  })
                } catch (_) {}

                // Navigate after events are completed
-               window.location.href = href
+               window.location.href = suggestionPath
              },
            }}
          />
+         )
        })}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchDropdown/SearchDropdown.tsx` around
lines 64 - 95, Compute the suggestion URL once inside the map and reuse it
instead of calling formatSearchPath twice: inside the terms?.map block create
const href = formatSearchPath({ term: suggestion, sort }) and pass that href to
UISearchAutoCompleteTerm's linkProps.href and use the same href inside the
onClick handler for window.location.href (and for any analytics/navigation
uses), leaving sendAutocompleteClickEvent, onSearchSelection,
UISearchAutoCompleteTerm, term, suggestion, and sort intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/components/search/SearchTop/SearchTop.tsx`:
- Line 12: The import useSearchBase is unused in SearchTop.tsx
(useFormatSearchPath already consumes it), so remove the unused import statement
"useSearchBase" from the top of the file to clean up imports and avoid linter
warnings; ensure only the necessary imports (including useFormatSearchPath)
remain.

In `@packages/core/src/sdk/search/state.ts`:
- Around line 8-26: The useApplySearchState callback redundantly calls
resolveLink on newUrl which has already been locale/custom-path resolved by
useSearchBase/formatSearchState, causing double-prefixing; remove the
resolveLink(newUrl) call and use newUrl directly when setting
window.history.replaceState (keep spreading window.history.state and the as/url
fields), ensuring the function signatures and dependency on resolveLink remain
consistent in the closure.

---

Nitpick comments:
In `@packages/core/src/components/search/SearchDropdown/SearchDropdown.tsx`:
- Around line 64-95: Compute the suggestion URL once inside the map and reuse it
instead of calling formatSearchPath twice: inside the terms?.map block create
const href = formatSearchPath({ term: suggestion, sort }) and pass that href to
UISearchAutoCompleteTerm's linkProps.href and use the same href inside the
onClick handler for window.location.href (and for any analytics/navigation
uses), leaving sendAutocompleteClickEvent, onSearchSelection,
UISearchAutoCompleteTerm, term, suggestion, and sort intact.

Comment thread packages/core/src/sdk/search/state.ts Resolved
@hellofanny hellofanny self-assigned this Feb 19, 2026
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
packages/core/src/components/search/SearchTop/SearchTop.tsx (1)

52-68: Per-term locale-aware path looks correct; optional: memoize the hook's return value.

The inline formatSearchPath({term, sort}) call inside .map() is fine for this bounded list. One thing worth noting: useFormatSearchPath returns a brand-new closure on every render (no useCallback inside the hook). It's benign here because the function is called inline and never passed as a prop, but memoizing it inside the hook would be the cleaner approach if this pattern is reused in components where the function is propagated.

The fix lives in the hook itself (formatSearchPath.ts), not in this component — but flagging the pattern:

// packages/core/src/sdk/search/formatSearchPath.ts
+import { useCallback } from 'react'

 export function useFormatSearchPath(): (params: FormatSearchPathParams) => string {
   const searchBase = useSearchBase()
-  return (params: FormatSearchPathParams) =>
-    formatSearchPath(params, searchBase)
+  return useCallback(
+    (params: FormatSearchPathParams) => formatSearchPath(params, searchBase),
+    [searchBase]
+  )
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchTop/SearchTop.tsx` around lines 52
- 68, The hook useFormatSearchPath (formatSearchPath) currently returns a new
function on every render; update the hook in formatSearchPath.ts to memoize the
returned closure with React.useCallback so callers (e.g., SearchTop's
formatSearchPath) receive a stable function instance — include all relevant
dependencies (locale, base path, any translation or routing values used inside
the closure) in the useCallback dependency array to preserve correctness.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/core/src/components/search/SearchTop/SearchTop.tsx`:
- Around line 52-68: The hook useFormatSearchPath (formatSearchPath) currently
returns a new function on every render; update the hook in formatSearchPath.ts
to memoize the returned closure with React.useCallback so callers (e.g.,
SearchTop's formatSearchPath) receive a stable function instance — include all
relevant dependencies (locale, base path, any translation or routing values used
inside the closure) in the useCallback dependency array to preserve correctness.

Comment thread packages/core/src/sdk/ui/useLink.ts Resolved
Comment thread packages/core/src/sdk/ui/useLink.ts Resolved

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/core/src/sdk/ui/useLink.ts`:
- Around line 28-35: The locale-prefix branch in useLink (inside the useLink
hook) lacks the same storeConfig.localization?.enabled guard used by
addCustomPathPrefix and other localization utilities, so it may incorrectly
prepend router.locale when localization is defined but disabled; update the
conditional that builds `/${router.locale}${href}` to include
`storeConfig.localization?.enabled` (alongside the existing checks for
router.locale, defaultLocale, and !onCustomPath) so the locale prefix is only
applied when localization is enabled.

Comment thread packages/core/src/sdk/ui/useLink.ts Resolved
@hellofanny
hellofanny merged commit 8349318 into feat/multilanguage Feb 20, 2026
3 checks passed
@hellofanny
hellofanny deleted the chore/adjust-links-search branch February 20, 2026 20:57
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