Skip to content
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

feat: support global search in multiple environments and fix pipeline errors #2629

Merged
merged 2 commits into from
Dec 9, 2024

Conversation

zzcr
Copy link
Member

@zzcr zzcr commented Dec 9, 2024

… errors

PR

PR Checklist

Please check if your PR fulfills the following requirements:

  • The commit message follows our Commit Message Guidelines
  • Tests for the changes have been added (for bug fixes / features)
  • Docs have been added / updated (for bug fixes / features)

PR Type

What kind of change does this PR introduce?

  • Bugfix
  • Feature
  • Code style update (formatting, local variables)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • CI related changes
  • Documentation content changes
  • Other... Please describe:

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Does this PR introduce a breaking change?

  • Yes
  • No

Other information

Summary by CodeRabbit

  • New Features

    • Updated version to 3.20.5 for the project.
    • Added a new dependency for enhanced search functionality.
    • Introduced a new function to handle search click events and improve user navigation.
  • Bug Fixes

    • Simplified control flow for search initialization, ensuring consistent functionality across environments.

Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request introduces changes to the @opentiny/vue-docs project, specifically updating the package.json file to reflect a new version and the addition of a new dependency. It also modifies the main.js file to alter the control flow of the search functionality, ensuring it initializes under different environment conditions. Furthermore, a new file docsearch.js is added, which provides functionality for handling click events on search results, enhancing the user interaction with Algolia search.

Changes

File Path Change Summary
examples/sites/package.json - Version updated from 3.20.3 to 3.20.5
- Added dependency @docsearch/react as npm:@docsearch/css
examples/sites/src/main.js - Added import for doSearchEverySite
- Removed conditional check for envTarget === 'open' and modified logic to always initialize search functionality
examples/sites/src/tools/docsearch.js - Introduced new file with functions for handling Algolia search results and click events, including doSearchEverySite

Possibly related PRs

Suggested labels

bug

🐇 In the code we hop and play,
New features bloom, bright as day.
With search now swift, and links to find,
A joyful leap for all mankind!
Let's click and search, oh what a thrill,
In the rabbit's world, we code with skill! 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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.

@github-actions github-actions bot added the enhancement New feature or request (功能增强) label Dec 9, 2024
@zzcr zzcr changed the title feat: support global search in multiple environments and fix pipeline… feat: support global search in multiple environments and fix pipeline errors Dec 9, 2024
Copy link

github-actions bot commented Dec 9, 2024

[e2e-test-warn]
The component to be tested is missing.

The title of the Pull request should look like "fix(vue-renderless): [action-menu, alert] fix xxx bug".

Please make sure you've read our contributing guide

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

🧹 Outside diff range and nitpick comments (1)
examples/sites/src/main.js (1)

52-55: Consider environment-specific search configurations

The current implementation assumes default search behavior for non-open environments. Consider adding environment-specific configurations.

Consider creating a configuration file to manage environment-specific search settings:

// searchConfig.js
export const getSearchConfig = (envTarget) => ({
  open: {
    useGlobalSearch: false,
    // other open env specific settings
  },
  default: {
    useGlobalSearch: true,
    // other env specific settings
  }
}[envTarget] || config.default);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c79dd29 and 5e7c317.

📒 Files selected for processing (3)
  • examples/sites/package.json (2 hunks)
  • examples/sites/src/main.js (1 hunks)
  • examples/sites/src/tools/docsearch.js (1 hunks)
🧰 Additional context used
🪛 Gitleaks (8.21.2)
examples/sites/src/main.js

46-46: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Comment on lines +3 to +9
const findUrlLink = (target) => {
if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
return target.getAttribute('href')
} else if (target?.parentElement) {
return findUrlLink(target.parentElement)
}
}
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 error handling for recursive DOM traversal

The findUrlLink function could potentially cause a stack overflow with deeply nested DOM structures. Consider adding a maximum depth limit.

-const findUrlLink = (target) => {
+const findUrlLink = (target, depth = 0) => {
+  const MAX_DEPTH = 10;
+  if (depth > MAX_DEPTH) return null;
   if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
     return target.getAttribute('href')
   } else if (target?.parentElement) {
-    return findUrlLink(target.parentElement)
+    return findUrlLink(target.parentElement, depth + 1)
   }
 }
📝 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 findUrlLink = (target) => {
if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
return target.getAttribute('href')
} else if (target?.parentElement) {
return findUrlLink(target.parentElement)
}
}
const findUrlLink = (target, depth = 0) => {
const MAX_DEPTH = 10;
if (depth > MAX_DEPTH) return null;
if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
return target.getAttribute('href')
} else if (target?.parentElement) {
return findUrlLink(target.parentElement, depth + 1)
}
}

Comment on lines 14 to 26
export const doSearhEverySite = () => {
window.addEventListener('click', (event) => {
const target = event.target
if (isAlgoliaHitDom(target)) {
const openUrl = findUrlLink(target)
if (openUrl) {
const urlObj = new URL(openUrl)
event.preventDefault()
window.location.href = openUrl.replace(urlObj.origin, window.location.origin)
}
}
})
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add security measures for URL handling

The URL manipulation could be vulnerable to open redirect attacks. Consider implementing URL validation and allowlisting.

 export const doSearhEverySite = () => {
+  const isValidDomain = (url) => {
+    const allowedDomains = ['your-domain.com', 'other-domain.com'];
+    return allowedDomains.some(domain => url.includes(domain));
+  };
   window.addEventListener('click', (event) => {
     const target = event.target
     if (isAlgoliaHitDom(target)) {
       const openUrl = findUrlLink(target)
-      if (openUrl) {
+      if (openUrl && isValidDomain(openUrl)) {
         const urlObj = new URL(openUrl)
         event.preventDefault()
         window.location.href = openUrl.replace(urlObj.origin, window.location.origin)
+      } else {
+        console.warn('Invalid URL detected:', openUrl);
       }
     }
   })
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +44 to +50
docsearch({
appId: 'AGPA5UXHMH',
apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
indexName: 'opentiny',
container: '.search-box',
debug: false
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Move API credentials to environment variables

The Algolia API credentials are exposed in client-side code, which poses a security risk. These should be moved to environment variables.

 docsearch({
-  appId: 'AGPA5UXHMH',
-  apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
+  appId: import.meta.env.VITE_ALGOLIA_APP_ID,
+  apiKey: import.meta.env.VITE_ALGOLIA_API_KEY,
   indexName: 'opentiny',
   container: '.search-box',
   debug: false
 })
📝 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
docsearch({
appId: 'AGPA5UXHMH',
apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
indexName: 'opentiny',
container: '.search-box',
debug: false
})
docsearch({
appId: import.meta.env.VITE_ALGOLIA_APP_ID,
apiKey: import.meta.env.VITE_ALGOLIA_API_KEY,
indexName: 'opentiny',
container: '.search-box',
debug: false
})
🧰 Tools
🪛 Gitleaks (8.21.2)

46-46: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Comment on lines +52 to +53
"@docsearch/css": "^3.8.0",
"@docsearch/react": "npm:@docsearch/css"
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

🛠️ Refactor suggestion

The @docsearch/react dependency configuration is incorrect and should be fixed

The codebase is using @docsearch/js and @docsearch/css directly, as evidenced in main.js:

import docsearch from '@docsearch/js'
import '@docsearch/css'

The @docsearch/react dependency is incorrectly aliased to @docsearch/css and should be removed since:

  1. The project uses the vanilla JS version (@docsearch/js), not the React version
  2. CSS is already properly imported via the direct @docsearch/css dependency
     "@docsearch/js": "^3.8.0",
     "@docsearch/css": "^3.8.0",
-    "@docsearch/react": "npm:@docsearch/css"
🔗 Analysis chain

Verify @docsearch/react dependency configuration

The dependency configuration appears unusual:

  1. @docsearch/react is aliased to @docsearch/css
  2. @docsearch/css is also listed as a direct dependency

This might lead to duplicate CSS imports and potential version conflicts.

Consider using the proper @docsearch/react package instead of the CSS alias:

     "@docsearch/js": "^3.8.0",
     "@docsearch/css": "^3.8.0",
-    "@docsearch/react": "npm:@docsearch/css"
+    "@docsearch/react": "^3.8.0"

The previous commands didn't provide enough context. Let's search more broadly for docsearch usage and check package configurations to understand the dependency setup better.


Let's examine how docsearch is actually being used in the project to better understand the dependency configuration.


Let's examine how docsearch is actually implemented in the main.js file and if there are any other relevant files to understand the dependency setup better.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential duplicate CSS imports
rg -l "from ['|\"]@docsearch/(css|react)['|\"]" 

# Verify package resolution
npm ls @docsearch/css @docsearch/react

Length of output: 146


Script:

#!/bin/bash
# Let's check for any imports or usage patterns of @docsearch in the codebase
rg -l "@docsearch" --type js --type ts --type vue

# Check if there are any other package.json files that might be using @docsearch
fd package.json --type f --exec grep -l "@docsearch" {}

# Look for any CSS imports related to docsearch
rg -l "docsearch" --type css

Length of output: 223


Script:

#!/bin/bash
# Let's examine the content of style.css to understand how docsearch is being used
cat examples/sites/src/style.css

# Check the exact content around docsearch in package.json for more context
grep -A 5 -B 5 "@docsearch" examples/sites/package.json

# Look for any JavaScript/TypeScript files that might be using docsearch
rg -l "docsearch" --type js --type ts

Length of output: 1830


Script:

#!/bin/bash
# Let's check the main.js file to see how docsearch is being used
cat examples/sites/src/main.js

# Check if there are any other JS files that might contain docsearch configuration
rg -l "docsearch" --type js --type ts -g '!main.js'

# Look for any Vue components that might be using docsearch
fd -e vue -x grep -l "docsearch" {}

Length of output: 2682

@@ -33,21 +33,25 @@ import css from 'highlight.js/lib/languages/css'
import html from 'highlight.js/lib/languages/xml'
import docsearch from '@docsearch/js'
import '@docsearch/css'
import { doSearhEverySite } from './tools/docsearch'
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
import { doSearhEverySite } from './tools/docsearch'
import { doSearchEverySite } from './tools/docsearch'

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

🧹 Outside diff range and nitpick comments (1)
examples/sites/src/main.js (1)

52-54: Consider improving environment handling and error handling

While the functionality is correct, consider these improvements:

  1. Use a more explicit environment constant instead of the string literal 'open'
  2. Add error handling for the doSearchEverySite function
  3. Document supported environments in comments
+// Define supported environments
+const ENVIRONMENTS = {
+  OPEN: 'open',
+  INTERNAL: 'internal',
+  LOCAL: 'local'
+}

-if (envTarget !== 'open') {
+if (envTarget !== ENVIRONMENTS.OPEN) {
   // 支持本地开发和内网使用全局搜索
-  doSearchEverySite()
+  try {
+    doSearchEverySite()
+  } catch (error) {
+    console.error('Failed to initialize global search:', error)
+  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5e7c317 and 770a226.

📒 Files selected for processing (2)
  • examples/sites/src/main.js (1 hunks)
  • examples/sites/src/tools/docsearch.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/sites/src/tools/docsearch.js
🧰 Additional context used
🪛 Gitleaks (8.21.2)
examples/sites/src/main.js

46-46: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (3)
examples/sites/src/main.js (3)

36-36: LGTM: Import statement is properly placed

The import of the new search functionality follows proper conventions.


44-50: ⚠️ Potential issue

Critical: Move API credentials to environment variables

The Algolia API credentials are still exposed in client-side code, which poses a security risk. These should be moved to environment variables.

 docsearch({
-  appId: 'AGPA5UXHMH',
-  apiKey: '5fa09fc20270efa61d68e2c2eb0f56df',
+  appId: import.meta.env.VITE_ALGOLIA_APP_ID,
+  apiKey: import.meta.env.VITE_ALGOLIA_API_KEY,
   indexName: 'opentiny',
   container: '.search-box',
   debug: false
 })
🧰 Tools
🪛 Gitleaks (8.21.2)

46-46: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


36-36: Verify doSearchEverySite implementation

Let's verify the implementation of the new search functionality.

Also applies to: 52-54

✅ Verification successful

Implementation verified and looks correct

The doSearchEverySite function is properly implemented in the tools directory. It:

  • Adds a click event listener to handle search result interactions
  • Correctly identifies Algolia search hits using the HIT_CLASS constant
  • Handles URL transformation to maintain consistent origin across site navigation
  • Implements proper DOM traversal to find anchor links
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of doSearchEverySite
echo "Checking doSearchEverySite implementation..."
fd docsearch.js --type f --exec cat {}

Length of output: 923

@kagol kagol merged commit ba839e0 into release-3.20.0 Dec 9, 2024
6 checks passed
kagol pushed a commit that referenced this pull request Dec 11, 2024
… errors (#2629)

* feat: support global search in multiple environments and fix pipeline errors

* feat: support global search in multiple environments and fix pipeline errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request (功能增强)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants