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: update version notice #4518

Closed

Conversation

LanceJiang
Copy link
Contributor

@LanceJiang LanceJiang commented Sep 26, 2024

Description

feat: check-updates.vue 检测更新提示窗 通过 worker 进行 请求 通过 message 触发 更新弹窗

Type of change

Please delete options that are not relevant.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

Copy link

changeset-bot bot commented Sep 26, 2024

⚠️ No Changeset found

Latest commit: f655e66

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 Sep 26, 2024

Walkthrough

The changes introduce a new watcher in the layout component to ensure the sidebar is visible when the layout is set to 'sidebar-mixed-nav'. Additionally, the update-checking logic in the check-updates widget is refactored to utilize a worker-based approach, enhancing performance and simplifying state management. A new utility file is added, providing functions to create workers and manage periodic update checks.

Changes

File Path Change Summary
packages/effects/layouts/src/basic/layout.vue Added a watcher for preferences.app.layout to ensure the sidebar is visible when the layout is 'sidebar-mixed-nav'.
packages/effects/layouts/src/widgets/check-updates/check-updates.vue Refactored update-checking logic to use a worker-based approach; removed getVersionTag and checkForUpdates functions; simplified state management; updated function signatures.
packages/effects/layouts/src/widgets/check-updates/utils.ts Introduced createWorker and createWorkFn functions for managing web workers and periodic update checks.

Possibly related PRs

  • fix: improve layout boundary issues #4450: This PR is directly related as it also adds a watcher to monitor changes to preferences.app.layout and ensures the sidebar is visible when the layout is set to 'sidebar-mixed-nav', similar to the changes made in the main PR.

Suggested reviewers

  • anncwb
  • vince292007

Poem

🐰 In the world of code, so bright and new,
A sidebar now shows, with a layout so true.
Workers now dance, checking updates with glee,
Simplifying tasks, as happy as can be!
Hooray for the changes, let’s hop with delight,
For every small tweak makes our app feel just right! 🌟


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 (6)
packages/effects/layouts/src/basic/layout.vue (1)

146-157: LGTM! Consider adding a user preference option.

The new watcher effectively ensures that the sidebar is visible when the 'sidebar-mixed-nav' layout is selected, which aligns with the PR objectives and improves user experience.

Consider adding a user preference option to allow users to override this behavior if they wish to keep the sidebar hidden even in the 'sidebar-mixed-nav' layout. This could be implemented as follows:

watch(
  () => preferences.app.layout,
  async (val) => {
    if (val === 'sidebar-mixed-nav' && preferences.sidebar.hidden) {
+     if (!preferences.sidebar.allowHiddenInMixedNav) {
        updatePreferences({
          sidebar: {
            hidden: false,
          },
        });
+     }
    }
  },
);

This change would require adding a new preference option allowHiddenInMixedNav to the sidebar preferences.

packages/effects/layouts/src/widgets/check-updates/utils.ts (2)

47-47: Use Appropriate Logging Method Instead of console.error

Currently, console.error is used to log the versionTag:

console.error(versionTag, 'versionTag');

Using console.error for non-error information can clutter the console and make it harder to spot actual errors.

Use console.log or console.info for informational messages:

-    console.error(versionTag, 'versionTag');
+    console.info(versionTag, 'versionTag');

20-20: Consider Adjusting the Default Update Interval

The default checkUpdatesInterval is set to 1 minute:

checkUpdatesInterval: 1, // min

Frequent update checks may increase server load and network traffic.

Consider setting a higher default interval, such as 5 or 10 minutes, to reduce unnecessary requests.

packages/effects/layouts/src/widgets/check-updates/check-updates.vue (3)

19-19: Avoid direct use of location for better SSR compatibility

Accessing location.origin directly can cause issues in server-side rendering (SSR) environments where window and location may not be defined. Consider using import.meta.env.BASE_URL or a similar approach to obtain the root path safely.

Apply this diff to use import.meta.env.BASE_URL:

- const rootPath = `${location.origin}/`;
+ const rootPath = import.meta.env.BASE_URL;

35-35: Specify the correct event type for better type safety

The event parameter e is currently typed as any. To improve type safety and leverage TypeScript's type checking, specify the event type as MessageEvent.

Apply this diff:

- worker.addEventListener('message', (e: any) => {
+ worker.addEventListener('message', (e: MessageEvent) => {

Ensure to import MessageEvent if it's not available in the current scope.


47-47: Remove unused commented-out parameter

The parameter /* versionTag: string*/ in the handleNotice function is commented out and not used within the function body. Consider removing it to clean up the code.

Apply this diff:

- function handleNotice(/* versionTag: string*/) {
+ function handleNotice() {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a72b8ac and f655e66.

📒 Files selected for processing (3)
  • packages/effects/layouts/src/basic/layout.vue (1 hunks)
  • packages/effects/layouts/src/widgets/check-updates/check-updates.vue (3 hunks)
  • packages/effects/layouts/src/widgets/check-updates/utils.ts (1 hunks)
🔇 Additional comments (2)
packages/effects/layouts/src/widgets/check-updates/check-updates.vue (2)

37-37: Clarify conditional check for non-production environments

The condition import.meta.env.MODE === 'production' prevents handleNotice from being called in non-production environments. If the intention is to test update notifications during development, consider adjusting this check or adding a comment to explain.

Is it intended to suppress update notifications in non-production modes? Verify if this aligns with the desired behavior.


85-85: Ensure immediate start behavior is consistent

When the document becomes visible, start(true) is called with immediate = true. Verify that this aligns with the desired behavior of checking for updates immediately upon visibility change.

Confirm that starting the worker with immediate = true after regaining visibility is intended and does not cause unintended side effects.

Comment on lines +64 to +68
const data = event.data.data;
if (data.checkUpdatesInterval)
opts.checkUpdatesInterval = data.checkUpdatesInterval;
if (data.fetchUrl) opts.fetchUrl = data.fetchUrl;
if (data.immediate) {
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

Validate Incoming Data in Message Handler

The code updates opts based on event.data.data without validation:

const data = event.data.data;
if (data.checkUpdatesInterval)
  opts.checkUpdatesInterval = data.checkUpdatesInterval;
if (data.fetchUrl) opts.fetchUrl = data.fetchUrl;
if (data.immediate) {
  await doFetch();
}

To prevent potential errors or security issues, validate the incoming data:

if (typeof data.checkUpdatesInterval === 'number' && data.checkUpdatesInterval > 0)
  opts.checkUpdatesInterval = data.checkUpdatesInterval;
if (typeof data.fetchUrl === 'string') opts.fetchUrl = data.fetchUrl;
if (typeof data.immediate === 'boolean' && data.immediate) {
  await doFetch();
}

const stop = () => {
clearInterval(timer);
};
const temp: Worker = globalThis as any;
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

Type Mismatch: globalThis Should Be WorkerGlobalScope

At line 28, temp is declared as Worker, but globalThis in a worker context refers to WorkerGlobalScope, not Worker. This mismatch can lead to type inconsistencies and confusion when using worker-specific properties and methods.

Update the type of temp to WorkerGlobalScope to accurately represent the worker's global context:

-  const temp: Worker = globalThis as any;
+  const temp: WorkerGlobalScope = globalThis as any;

Or, for more specific typing, use DedicatedWorkerGlobalScope:

-  const temp: Worker = globalThis as any;
+  const temp: DedicatedWorkerGlobalScope = globalThis as any;
📝 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 temp: Worker = globalThis as any;
const temp: WorkerGlobalScope = globalThis as any;
```
Alternatively, using the more specific type:
```suggestion
const temp: DedicatedWorkerGlobalScope = globalThis as any;

Comment on lines +43 to +45
const stop = () => {
worker.postMessage({ type: 'stop' });
};
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

Terminate the worker upon unmounting to prevent resource leaks

While the stop function sends a 'stop' message to the worker, it does not terminate it. When the component unmounts, the worker remains active, potentially leading to memory leaks. Consider terminating the worker in the onUnmounted hook.

Apply this diff to terminate the worker when the component unmounts:

 onUnmounted(() => {
   stop();
+  worker.terminate();
   document.removeEventListener('visibilitychange', handleVisibilitychange);
 });

Also applies to: 108-112

Comment on lines +27 to +32
watch(
() => props.checkUpdatesInterval,
() => {
opts.checkUpdatesInterval = props.checkUpdatesInterval;
},
);
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

Changes to checkUpdatesInterval may not affect the worker

The watch function updates opts.checkUpdatesInterval when props.checkUpdatesInterval changes. However, since the worker continues running with the initial options, the updated interval won't take effect unless the worker is notified. Consider sending an update message to the worker or restarting the worker to apply the new interval.

Apply this diff to send updated options to the worker when the interval changes:

 watch(
   () => props.checkUpdatesInterval,
   () => {
     opts.checkUpdatesInterval = props.checkUpdatesInterval;
+    worker.postMessage({ data: { ...opts }, type: 'updateOptions' });
   },
 );

Also, ensure the worker handles the 'updateOptions' message type to update its configuration accordingly.

Committable suggestion was skipped due to low confidence.

@LanceJiang LanceJiang changed the title Feature/update version notice feat: update version notice Sep 26, 2024
@LanceJiang LanceJiang closed this Sep 27, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Oct 28, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant