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: stronger useRouter #38

Merged
merged 5 commits into from
Jan 17, 2024
Merged

Conversation

edwinhuish
Copy link
Collaborator

@edwinhuish edwinhuish commented Jan 17, 2024

Description 描述

Reopen of #36

  1. 去除每次 useRouter 都新建对象的副作用。
  2. 加入路由跳转的函数封装。无须再区分 tabbar 路由和页面路由。
  3. 为了消歧义,将 page 和 route 改为 current 和 currentUrl
  4. route 属性有歧义,容易误解为和vue router 一样的 route,但在uniapp里仅仅是个 url。(已添加 @deprecated 标识)

Linked Issues 关联的 Issues

Additional context 额外上下文

Summary by CodeRabbit

  • New Features

    • Introduced router utility for enhanced navigation within the mobile app.
    • Added new routing operations like switching tabs, navigating to pages, redirecting, and relaunching the app.
    • Implemented a method to navigate back within the app's navigation stack.
  • Documentation

    • Updated useRoute documentation, recommending useRouter().currentUrl for current routing needs.
  • Refactor

    • Deprecated certain properties in useRouter to streamline routing functionality.
  • Bug Fixes

    • Fixed path resolution with new pathResolve function to improve navigation reliability.

Copy link

coderabbitai bot commented Jan 17, 2024

Walkthrough

The project has introduced new TypeScript type utilities for enhanced property manipulation, deprecated the useRoute function in favor of useRouter().currentUrl, and expanded the useRouter utility with additional functionality for navigation management in a mobile app context. This includes new methods for tab management, navigation, and routing stack manipulation, along with a utility function to resolve paths.

Changes

File Path Change Summary
src/types.ts Added new type declarations for Optional, RequiredProperty, and RequiredOnly to manipulate object properties.
src/useRoute/index.ts Deprecated the useRoute function and suggested using useRouter().currentUrl instead.
src/useRouter/index.ts
src/useRouter/readme.md
Updated useRouter with new imports, functions, and deprecated properties. Added navigation utility methods and documentation.
src/utils.ts Added a new function pathResolve to resolve a target path based on the current path.
build.config.ts Added @dcloudio/uni-cli-shared to the externals in the build configuration.

Poem

🐇 "Hop through the code, with ease and fun,
📱 Navigating paths, one by one.
💾 Deprecated old, welcomed the new,
🌟 With every commit, our project grew."

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>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 7dcb2ae and 104fb9e.
Files selected for processing (5)
  • src/types.ts (1 hunks)
  • src/useRoute/index.ts (1 hunks)
  • src/useRouter/index.ts (1 hunks)
  • src/useRouter/readme.md (1 hunks)
  • src/utils.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • src/useRoute/index.ts
Additional comments: 20
src/types.ts (3)
  • 11-11: The Optional type is correctly defined and follows TypeScript's utility types pattern.
  • 13-13: The RequiredProperty type is correctly implemented, ensuring that the specified properties are required in the type.
  • 15-15: The RequiredOnly type is a proper combination of Partial and RequiredProperty, which is a useful utility type for TypeScript.
src/utils.ts (1)
  • 17-17: The pathResolve function uses a hardcoded base URL ('http://no-exists.com') to create a full URL object. Verify that this approach is compatible with the expected behavior in all use cases and does not introduce any side effects.
src/useRouter/readme.md (1)
  • 10-22: The documentation updates in the useRouter readme provide clear examples of how to use the new router functionality, including the tryTabBar option and tabBarList.
src/useRouter/index.ts (15)
  • 28-41: The initIfNotInited function is correctly checking if the router has been initialized before setting up interceptors and refreshing the current pages.
  • 44-46: The refreshCurrentPages function correctly updates the pages ref with the current pages from getCurrentPages().
  • 48-60: The warpPromiseOptions function correctly wraps the options object with success and fail handlers that resolve or reject the promise.
  • 66-71: The switchTab function is correctly returning a promise that resolves or rejects based on the outcome of uni.switchTab.
  • 74-79: The navigateTo function is correctly returning a promise that resolves or rejects based on the outcome of uni.navigateTo.
  • 82-87: The redirectTo function is correctly returning a promise that resolves or rejects based on the outcome of uni.redirectTo.
  • 93-98: The reLaunch function is correctly returning a promise that resolves or rejects based on the outcome of uni.reLaunch.
  • 104-109: The back function is correctly returning a promise that resolves or rejects based on the outcome of uni.navigateBack.
  • 116-135: The trySwitchTab function is correctly handling the logic to determine whether to use switchTab or navigate functions based on the tryTabBar flag and the presence of tabBarList.
  • 139-142: The isTabBarPath function is correctly determining if a given path is a tab bar path using the pathResolve function and the tabBarList.
  • 149-161: The UseRouterOptions interface is correctly defined with optional properties for tryTabBar and tabBarList.
  • 170-188: The useRouter function is correctly initializing the router if not already done and setting up a back press interceptor.
  • 193-195: The navigate function is correctly using trySwitchTab to handle navigation with the tryTabBar logic.
  • 200-201: The redirect function is correctly using trySwitchTab to handle redirection with the tryTabBar logic.
  • 202-233: The useRouter function is correctly returning an object with properties and methods for managing routing, including deprecated properties with clear comments.

src/utils.ts Outdated
Comment on lines 8 to 17
export function pathResolve(target: string, current?: string) {
if (!current) {
const pages = getCurrentPages();
current = pages[pages.length - 1].route;
}

if (!current) {
throw new Error('The current path is undefined and cannot be found.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;
Copy link

Choose a reason for hiding this comment

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

The pathResolve function assumes that getCurrentPages() will always return an array with at least one page, which may not be the case. It should handle the scenario where getCurrentPages() is empty.

- current = pages[pages.length - 1].route;
+ current = pages.length > 0 ? pages[pages.length - 1].route : undefined;

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.

Suggested change
export function pathResolve(target: string, current?: string) {
if (!current) {
const pages = getCurrentPages();
current = pages[pages.length - 1].route;
}
if (!current) {
throw new Error('The current path is undefined and cannot be found.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;
export function pathResolve(target: string, current?: string) {
if (!current) {
const pages = getCurrentPages();
current = pages.length > 0 ? pages[pages.length - 1].route : undefined;
}
if (!current) {
throw new Error('The current path is undefined and cannot be found.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;
}

Comment on lines +14 to +17
if (!current) {
throw new Error('The current path is undefined and cannot be found.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;
Copy link

Choose a reason for hiding this comment

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

The error message in the pathResolve function is misleading because it suggests that the current path is always undefined, which may not be the case. The error should be thrown only if getCurrentPages() returns an empty array.

- throw new Error('The current path is undefined and cannot be found.');
+ throw new Error('No pages found in the current stack.');

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.

Suggested change
if (!current) {
throw new Error('The current path is undefined and cannot be found.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;
if (!current) {
throw new Error('No pages found in the current stack.');
}
return new URL(target, new URL(current, 'http://no-exists.com')).pathname;

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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 104fb9e and 3791a43.
Files ignored due to path filters (1)
  • package.json is excluded by: !**/*.json
Files selected for processing (3)
  • build.config.ts (1 hunks)
  • src/useRouter/index.ts (1 hunks)
  • src/utils.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/utils.ts
Additional comments: 16
build.config.ts (1)
  • 7-9: The addition of @dcloudio/uni-cli-shared to the externals array in the build configuration is noted and appears to be correctly implemented.
src/useRouter/index.ts (15)
  • 2-5: The new imports for pathResolve, AppJson, RequiredOnly, and onBackPress are correctly added to the file.
  • 28-42: The initIfNotInited function is well implemented to ensure the router is only initialized once.
  • 44-46: The refreshCurrentPages function correctly updates the pages ref with the current pages.
  • 48-60: The warpPromiseOptions function is correctly implemented to wrap the options with success and fail handlers.
  • 66-71: The switchTab function is correctly implemented as a Promise, encapsulating the uni.switchTab call.
  • 74-79: The navigateTo function is correctly implemented as a Promise, encapsulating the uni.navigateTo call.
  • 82-87: The redirectTo function is correctly implemented as a Promise, encapsulating the uni.redirectTo call.
  • 93-98: The reLaunch function is correctly implemented as a Promise, encapsulating the uni.reLaunch call.
  • 104-109: The back function is correctly implemented as a Promise, encapsulating the uni.navigateBack call.
  • 116-135: The trySwitchTab function is correctly implemented to handle conditional tab bar navigation.
  • 139-142: The isTabBarPath function is correctly implemented to check if a path corresponds to a tab bar item.
  • 149-161: The UseRouterOptions interface is correctly updated to include the new tryTabBar and tabBarList properties.
  • 170-188: The modifications to the useRouter function, including the initialization logic and the onBackPress event handler, are correctly implemented.
  • 193-202: The navigate and redirect functions are correctly implemented to utilize the trySwitchTab logic.
  • 209-233: The return object of the useRouter function correctly exposes the new navigation methods and deprecates the old properties.

@edwinhuish edwinhuish merged commit ee34b6c into uni-helper:main Jan 17, 2024
0 of 2 checks passed
@edwinhuish edwinhuish deleted the useRouter2 branch January 17, 2024 03:41
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.

1 participant