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 shortcut keys to search multiple websites #2637

Merged
merged 1 commit into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/sites/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@opentiny/vue-docs",
"version": "3.20.5",
"version": "3.20.7",
"license": "MIT",
"scripts": {
"start": "vite",
Expand Down
29 changes: 8 additions & 21 deletions examples/sites/src/tools/docsearch.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,13 @@
const HIT_CLASS = 'DocSearch-Hit'

const findUrlLink = (target) => {
if (target?.nodeName?.toLocaleLowerCase?.() === 'a') {
return target.getAttribute('href')
} else if (target?.parentElement) {
return findUrlLink(target.parentElement)
}
}

const isAlgoliaHitDom = (dom) =>
dom?.className?.includes?.(HIT_CLASS) || dom?.parentElement?.className?.includes?.(HIT_CLASS)
const OPEN_TINY_URL = 'https://opentiny.design'

export const doSearchEverySite = () => {
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)
window.handleGlobalSearchData = (resolve) => {
return (data) => {
if (typeof data.content === 'string') {
data.content = data.content.replaceAll(OPEN_TINY_URL, window.location.origin)
}

resolve(data)
}
})
}
}
Comment on lines +4 to +12
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security concern: Exposing function on window object

Exposing functions on the window object could lead to potential security vulnerabilities as it becomes globally accessible. Consider:

  1. Using a more scoped approach
  2. Adding input validation
  3. Implementing proper error handling
-  window.handleGlobalSearchData = (resolve) => {
+  const handleGlobalSearchData = (resolve) => {
     return (data) => {
+      if (!data || typeof data !== 'object') {
+        console.error('Invalid data format received');
+        return;
+      }
       if (typeof data.content === 'string') {
         data.content = data.content.replaceAll(OPEN_TINY_URL, window.location.origin)
       }
 
       resolve(data)
     }
   }
+  // Expose through a controlled interface if necessary
+  if (typeof window !== 'undefined') {
+    Object.defineProperty(window, 'handleGlobalSearchData', {
+      value: handleGlobalSearchData,
+      writable: false,
+      configurable: 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
window.handleGlobalSearchData = (resolve) => {
return (data) => {
if (typeof data.content === 'string') {
data.content = data.content.replaceAll(OPEN_TINY_URL, window.location.origin)
}
resolve(data)
}
})
}
const handleGlobalSearchData = (resolve) => {
return (data) => {
if (!data || typeof data !== 'object') {
console.error('Invalid data format received');
return;
}
if (typeof data.content === 'string') {
data.content = data.content.replaceAll(OPEN_TINY_URL, window.location.origin)
}
resolve(data)
}
}
// Expose through a controlled interface if necessary
if (typeof window !== 'undefined') {
Object.defineProperty(window, 'handleGlobalSearchData', {
value: handleGlobalSearchData,
writable: false,
configurable: false
});
}

18 changes: 18 additions & 0 deletions examples/sites/vite-dosearch-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export default function viteDosearchPlugin() {
return {
name: 'vite-dosearch-plugin',
enforce: 'pre',
transform(code, id) {
if (id.includes('@docsearch')) {
const newCode = code.replace(
'Promise((function(t){var n=new XMLHttpRequest;',
'Promise((function(t){t=window.handleGlobalSearchData(t);var n=new XMLHttpRequest;'
)
Comment on lines +7 to +10
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fragile code transformation pattern

The current string replacement approach is brittle and might break with future updates of the @docsearch library. Consider:

  1. Using AST transformation instead of string replacement
  2. Adding version checks for @docsearch
  3. Implementing error handling for failed transformations
-        const newCode = code.replace(
-          'Promise((function(t){var n=new XMLHttpRequest;',
-          'Promise((function(t){t=window.handleGlobalSearchData(t);var n=new XMLHttpRequest;'
-        )
+        try {
+          const parser = require('@babel/parser');
+          const traverse = require('@babel/traverse').default;
+          const generate = require('@babel/generator').default;
+          
+          const ast = parser.parse(code);
+          
+          traverse(ast, {
+            NewExpression(path) {
+              if (path.node.callee.name === 'Promise' &&
+                  path.parent.type === 'CallExpression') {
+                // Insert the transformation here using AST
+              }
+            }
+          });
+          
+          const newCode = generate(ast).code;
+          return {
+            code: newCode,
+            map: null
+          }
+        } catch (error) {
+          console.error('Failed to transform @docsearch code:', error);
+          return null;
+        }

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

return {
code: newCode,
map: null
}
}
}
}
}
5 changes: 4 additions & 1 deletion examples/sites/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteDosearchPlugin from './vite-dosearch-plugin'
import Unocss from 'unocss/vite'
import path from 'node:path'
import UnoCssConfig from './uno.config'
Expand Down Expand Up @@ -42,6 +43,7 @@ export default defineConfig((config) => {
const env = loadEnv(config.mode, process.cwd() + '/env', '')
const isSaas = env.VITE_TINY_THEME === 'saas'
const isPlus = env.VITE_APP_MODE === 'plus'
const isInner = env.VITE_BUILD_TARGET === 'inner'
const demosPath = isPlus ? '../plusdocs/pc' : `./demos/${env.VITE_APP_MODE}`
const apisPath = isPlus ? '../plusdocs/apis' : './demos/apis'
const menuPath = isSaas ? path.resolve('./demos/saas') : path.resolve(demosPath)
Expand Down Expand Up @@ -115,7 +117,8 @@ export default defineConfig((config) => {
viteStaticCopy({
targets: copyTarget
}),
delStatic()
delStatic(),
isInner ? viteDosearchPlugin() : null
],
optimizeDeps: getOptimizeDeps(3),
build: {
Expand Down
Loading