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: 集成PageSpy #4820

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

feat: 集成PageSpy #4820

wants to merge 2 commits into from

Conversation

jinmao88
Copy link
Collaborator

@jinmao88 jinmao88 commented Nov 6, 2024

集成PageSpy 设置Drawer可上传离线日志

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced the CloudUpload icon for enhanced log upload functionality.
    • Added a log upload feature in the preferences drawer, allowing users to upload logs and receive feedback on the upload status.
  • Localization

    • Added new entries for log upload functionality in both English (US) and Chinese (Simplified) language files.
  • Enhancements

    • Integrated PageSpy SDK for improved analytics and monitoring capabilities in the playground.

Copy link

changeset-bot bot commented Nov 6, 2024

⚠️ No Changeset found

Latest commit: b8182b6

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request introduce a new CloudUpload icon to the lucide.ts file and enhance the preferences-drawer.vue component by integrating this icon for log upload functionality. Additionally, new localization entries for log upload messages are added in both English and Chinese JSON files. The playground/index.html file is updated to include PageSpy SDK scripts for enhanced analytics capabilities.

Changes

File Change Summary
packages/@core/base/icons/src/lucide.ts New export added: CloudUpload icon.
packages/effects/layouts/src/widgets/preferences/preferences-drawer.vue New icon CloudUpload imported; added handleUploadLog method and harbor computed property for log uploads. New VbenIconButton added for triggering uploads.
packages/locales/src/langs/en-US/preferences.json New entries added: "logUpload", "logUploadSuccess", "logUploadSuccessTitle".
packages/locales/src/langs/zh-CN/preferences.json New entries added: "logUpload", "logUploadSuccess", "logUploadSuccessTitle".
playground/index.html Added scripts for PageSpy SDK and its plugins; initialized PageSpy instance with project title.

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • vince292007
  • anncwb

Poem

In the meadow where icons play,
A CloudUpload joins the fray.
With logs to share and tales to tell,
A button clicks, all goes well!
🐇✨


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.

Copy link
Contributor

@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: 5

🧹 Outside diff range and nitpick comments (4)
playground/index.html (2)

30-31: Documentation: Improve comments for SDK configuration

The current comments could be more informative about the setup process and requirements.

Consider enhancing the comments:

-    <!-- 可以使用自己的部署的PageSpy的sdk 修改引入的地址即可 -->
-    <!--  https://pagespy.mufei88.com 为vben测试sdk地址 -->
+    <!-- PageSpy Integration:
+         - For production: Deploy your own PageSpy instance and update the URLs below
+         - Current URLs point to Vben's test environment (not for production use)
+         - Required scripts: core SDK, data-harbor plugin, and rrweb plugin
+         - Documentation: https://pagespy.mufei88.com/docs
+    -->

32-43: Performance: Optimize script loading strategy

The current implementation loads scripts synchronously, which could impact page load performance.

Consider these optimizations:

  1. Add defer attribute to all scripts
  2. Use preload hints for critical resources
  3. Consider dynamic loading based on user interaction
+ <!-- Preload hints for critical resources -->
+ <link rel="preload" href="https://pagespy.mufei88.com/page-spy/index.min.js" as="script" crossorigin="anonymous">

 <script
   crossorigin="anonymous"
+  defer
   src="https://pagespy.mufei88.com/page-spy/index.min.js"
 ></script>
packages/locales/src/langs/zh-CN/preferences.json (1)

31-33: LGTM! Consider adding more status messages for better UX.

The new localization entries for log upload functionality are clear and well-structured. However, consider adding these additional messages for a more complete user experience:

  • Upload confirmation message
  • Upload error message
  • Upload in progress message
 {
   "logUpload": "上传日志",
   "logUploadSuccess": "离线日志上传成功",
   "logUploadSuccessTitle": "上传成功",
+  "logUploadConfirm": "确认上传离线日志?",
+  "logUploadError": "日志上传失败",
+  "logUploadProgress": "正在上传日志..."
 }
packages/locales/src/langs/en-US/preferences.json (1)

31-33: Consider adding error handling messages.

To provide a better user experience, consider adding entries for:

  • Upload failure messages
  • Upload progress status
  • Upload confirmation prompts

Add these entries to handle various upload states:

  "logUpload": "Upload Log",
  "logUploadSuccess": "Log Upload Successful",
  "logUploadSuccessTitle": "Upload Successful",
+ "logUploadError": "Log Upload Failed",
+ "logUploadErrorTitle": "Upload Failed",
+ "logUploadProgress": "Uploading Log...",
+ "logUploadConfirm": "Are you sure you want to upload the log?"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 488ccb5 and b8182b6.

📒 Files selected for processing (5)
  • packages/@core/base/icons/src/lucide.ts (1 hunks)
  • packages/effects/layouts/src/widgets/preferences/preferences-drawer.vue (4 hunks)
  • packages/locales/src/langs/en-US/preferences.json (1 hunks)
  • packages/locales/src/langs/zh-CN/preferences.json (1 hunks)
  • playground/index.html (1 hunks)
🔇 Additional comments (5)
packages/@core/base/icons/src/lucide.ts (1)

20-20: LGTM! The CloudUpload icon export is properly integrated.

The addition is well-placed in alphabetical order and follows the existing export pattern.

Let's verify the icon usage in the codebase:

✅ Verification successful

CloudUpload icon is properly imported and utilized

The verification confirms that:

  • The icon is correctly imported from @vben/icons in preferences-drawer.vue
  • It's actively used in the template with appropriate sizing and click handler
  • The usage aligns with the PR's log upload functionality objective
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify CloudUpload icon import and usage
# Expected: Should find usage in preferences-drawer.vue as mentioned in the summary

# Search for CloudUpload imports
echo "Checking CloudUpload imports:"
rg "CloudUpload.*from.*@vben/icons"

# Search for CloudUpload usage in templates
echo -e "\nChecking CloudUpload usage in vue templates:"
rg "<CloudUpload"

Length of output: 502

packages/locales/src/langs/zh-CN/preferences.json (1)

31-33: Verify corresponding English translations.

Let's ensure the English translations exist and are consistent.

✅ Verification successful

English translations are present and consistent

The corresponding English translations exist in packages/locales/src/langs/en-US/preferences.json with matching keys and appropriate translations:

  • logUpload: "Upload Log"
  • logUploadSuccess: "Log Upload Successful"
  • logUploadSuccessTitle: "Upload Successful"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the corresponding English translations exist
# Expected: Should find matching keys in the English locale file

rg -A 3 '"logUpload":|"logUploadSuccess":|"logUploadSuccessTitle":' packages/locales/src/langs/en-US/preferences.json

Length of output: 311

packages/locales/src/langs/en-US/preferences.json (1)

31-33: LGTM! The new localization entries follow existing patterns.

The added entries maintain consistency with the file's existing naming conventions and message structure.

packages/effects/layouts/src/widgets/preferences/preferences-drawer.vue (2)

220-220: 🛠️ Refactor suggestion

Add type safety for window.$harbor access

The direct access to window.$harbor lacks type safety. Consider defining a proper type interface for the harbor instance.

+interface Harbor {
+  onOfflineLog: (action: string) => void;
+}
+
+declare global {
+  interface Window {
+    $harbor?: Harbor;
+  }
+}
+
const harbor = computed(() => window.$harbor);

Likely invalid or redundant comment.


220-231: Verify PageSpy integration

Let's verify the PageSpy SDK initialization and harbor instance availability.

✅ Verification successful

PageSpy integration is properly configured

The verification shows that PageSpy is correctly integrated:

  • PageSpy SDK and plugins (data-harbor, rrweb) are properly included in playground/index.html
  • window.$harbor is correctly initialized as a DataHarborPlugin instance
  • The harbor instance is properly accessed in preferences-drawer.vue and the onOfflineLog method is being used as expected
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check PageSpy SDK integration and harbor instance initialization

# Test 1: Check if PageSpy SDK is included in HTML files
echo "Checking PageSpy SDK inclusion..."
rg -l "pagespy.*sdk"

# Test 2: Check for harbor instance initialization
echo "Checking harbor instance initialization..."
rg -l "\$harbor.*=.*PageSpy"

Length of output: 246


Script:

#!/bin/bash
# Let's check the PageSpy integration more thoroughly

# Check PageSpy related imports and usage
echo "Checking PageSpy related code..."
rg -A 5 "PageSpy|pagespy" --type ts --type vue --type js

# Check harbor initialization and usage patterns
echo "Checking harbor initialization and usage..."
rg -A 5 "window\.\$harbor|harbor\s*=" --type ts --type vue --type js

# Check the playground HTML content
echo "Checking playground/index.html content..."
cat playground/index.html

Length of output: 2578


Script:

#!/bin/bash
# Let's check for Vue files specifically since the previous command had issues with Vue file type

# Check PageSpy related code in Vue files
echo "Checking PageSpy in Vue files..."
rg -A 5 "PageSpy|pagespy" --type-add 'vue:*.vue' --type vue

# Check harbor initialization and usage in Vue files
echo "Checking harbor usage in Vue files..."
rg -A 5 "window\.\$harbor|harbor\s*=" --type-add 'vue:*.vue' --type vue

# Check for offline log related functionality
echo "Checking offline log related code..."
rg -A 5 "onOfflineLog" --type-add 'vue:*.vue' --type vue

Length of output: 1611

Comment on lines +52 to +56
window.$pageSpy = new PageSpy({
project: '<%= VITE_APP_TITLE %>',
autoRender: false,
title: 'Vben Admin',
});
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Configuration values need to be consistent with environment variables

The verification reveals inconsistencies in the configuration:

  • The project parameter correctly uses VITE_APP_TITLE from environment variables
  • However, the title parameter is hardcoded as 'Vben Admin' while it should also use VITE_APP_TITLE
  • 'Vben Admin' is actually the default value for VITE_APP_TITLE as seen in internal/vite-config/src/utils/env.ts

The configuration should be updated to:

window.$pageSpy = new PageSpy({
  project: '<%= VITE_APP_TITLE %>',
  autoRender: false,
  title: '<%= VITE_APP_TITLE %>',
});
🔗 Analysis chain

Verify configuration parameters

The configuration uses hardcoded values and mixes environment variables.

Let's verify the configuration values across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for PageSpy configuration and title usage

# Check for VITE_APP_TITLE usage
echo "Checking VITE_APP_TITLE usage:"
rg "VITE_APP_TITLE" -A 2

# Check for hardcoded 'Vben Admin' title
echo "\nChecking hardcoded title usage:"
rg "'Vben Admin'" -A 2

Length of output: 6028

Comment on lines +32 to +43
<script
crossorigin="anonymous"
src="https://pagespy.mufei88.com/page-spy/index.min.js"
></script>
<script
crossorigin="anonymous"
src="https://pagespy.mufei88.com/plugin/data-harbor/index.min.js"
></script>
<script
crossorigin="anonymous"
src="https://pagespy.mufei88.com/plugin/rrweb/index.min.js"
></script>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security: Enhance the security of external script loading

The current implementation loads scripts from an external domain without proper security measures:

  1. The domain pagespy.mufei88.com appears to be a test environment. Consider hosting these scripts on your own CDN for production.
  2. Add Subresource Integrity (SRI) hashes to ensure script integrity.
  3. Pin specific versions in URLs to prevent unexpected changes.

Apply these security enhancements:

 <script
   crossorigin="anonymous"
+  integrity="sha384-[HASH]"
+  defer
-  src="https://pagespy.mufei88.com/page-spy/index.min.js"
+  src="https://pagespy.mufei88.com/page-spy/1.x.x/index.min.js"
 ></script>

Note: Replace [HASH] with actual SHA-384 hash of the file and 1.x.x with specific version.

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

Comment on lines +44 to +58
<script>
window.$harbor = new DataHarborPlugin();
window.$rrweb = new RRWebPlugin();

[window.$harbor, window.$rrweb].forEach((p) => {
PageSpy.registerPlugin(p);
});
// 实例化的参数都是可选的
window.$pageSpy = new PageSpy({
project: '<%= VITE_APP_TITLE %>',
autoRender: false,
title: 'Vben Admin',
});
// 之后即可使用 PageSpy,前往 https://pagespy.mufei88.com 体验
</script>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve implementation robustness and environment handling

The current implementation has several areas for improvement:

  1. Global variables pollute the window object
  2. No error handling
  3. No environment-based conditional loading

Consider refactoring to:

 <script>
+  // Only initialize in non-production environments or based on configuration
+  if (import.meta.env.DEV || window._VBEN_ADMIN_PRO_APP_CONF_.enablePageSpy) {
+    try {
+      const harbor = new DataHarborPlugin();
+      const rrweb = new RRWebPlugin();
 
-      [window.$harbor, window.$rrweb].forEach((p) => {
+      [harbor, rrweb].forEach((p) => {
         PageSpy.registerPlugin(p);
       });
-      window.$pageSpy = new PageSpy({
+      const pageSpy = new PageSpy({
         project: '<%= VITE_APP_TITLE %>',
         autoRender: false,
         title: 'Vben Admin',
       });
+
+      // If needed, expose through a namespaced object instead of directly on window
+      window.__VBEN__ = {
+        ...window.__VBEN__,
+        debug: { pageSpy, harbor, rrweb }
+      };
+    } catch (error) {
+      console.error('Failed to initialize PageSpy:', error);
+    }
+  }
 </script>

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

Comment on lines +243 to +249
<VbenIconButton
:disabled="!harbor"
:tooltip="$t('preferences.logUpload')"
class="relative"
>
<CloudUpload class="size-4" @click="handleUploadLog" />
</VbenIconButton>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve upload button UX and accessibility

The upload button implementation has several areas for improvement:

  1. Click handler should be on the button, not the icon
  2. Loading state should be reflected in the UI
  3. Missing accessibility attributes
 <VbenIconButton
   :disabled="!harbor"
   :tooltip="$t('preferences.logUpload')"
+  :loading="isUploading"
   class="relative"
+  aria-label="Upload logs"
+  @click="handleUploadLog"
 >
-  <CloudUpload class="size-4" @click="handleUploadLog" />
+  <CloudUpload class="size-4" />
 </VbenIconButton>

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

Comment on lines +221 to +231
// 防抖
const handleUploadLog = useThrottleFn(() => {
if (!harbor.value) {
return;
}
harbor.value.onOfflineLog('upload');
message.copyPreferencesSuccess?.(
$t('preferences.logUploadSuccessTitle'),
$t('preferences.logUploadSuccess'),
);
}, 5000);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and user feedback in log upload

The log upload function needs improvements in several areas:

  1. Error handling is missing
  2. No loading state during upload
  3. Hard-coded throttle duration
  4. Comment should be in English for consistency
-// 防抖
+// Throttle log upload to prevent excessive calls
-const handleUploadLog = useThrottleFn(() => {
+const UPLOAD_THROTTLE_MS = 5000;
+const isUploading = ref(false);
+
+const handleUploadLog = useThrottleFn(async () => {
   if (!harbor.value) {
+    message.error?.($t('preferences.logUploadNoHarbor'));
     return;
   }
-  harbor.value.onOfflineLog('upload');
-  message.copyPreferencesSuccess?.(
-    $t('preferences.logUploadSuccessTitle'),
-    $t('preferences.logUploadSuccess'),
-  );
-}, 5000);
+  try {
+    isUploading.value = true;
+    await harbor.value.onOfflineLog('upload');
+    message.success?.(
+      $t('preferences.logUploadSuccessTitle'),
+      $t('preferences.logUploadSuccess'),
+    );
+  } catch (error) {
+    message.error?.(
+      $t('preferences.logUploadError'),
+      error instanceof Error ? error.message : 'Unknown error'
+    );
+  } finally {
+    isUploading.value = false;
+  }
+}, UPLOAD_THROTTLE_MS);
📝 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 handleUploadLog = useThrottleFn(() => {
if (!harbor.value) {
return;
}
harbor.value.onOfflineLog('upload');
message.copyPreferencesSuccess?.(
$t('preferences.logUploadSuccessTitle'),
$t('preferences.logUploadSuccess'),
);
}, 5000);
// Throttle log upload to prevent excessive calls
const UPLOAD_THROTTLE_MS = 5000;
const isUploading = ref(false);
const handleUploadLog = useThrottleFn(async () => {
if (!harbor.value) {
message.error?.($t('preferences.logUploadNoHarbor'));
return;
}
try {
isUploading.value = true;
await harbor.value.onOfflineLog('upload');
message.success?.(
$t('preferences.logUploadSuccessTitle'),
$t('preferences.logUploadSuccess'),
);
} catch (error) {
message.error?.(
$t('preferences.logUploadError'),
error instanceof Error ? error.message : 'Unknown error'
);
} finally {
isUploading.value = false;
}
}, UPLOAD_THROTTLE_MS);

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

Successfully merging this pull request may close these issues.

2 participants