目录

HMRouter-based Page Redirection

Overview

HMRouter is a solution for page redirection on HarmonyOS applications. You can install, configure, and quickly get started with HMRouter by referring to HMRouter Usage Guide. This topic describes how to use the HMRouter framework in various development scenarios. The following features are provided:

The bottom layer of the framework encapsulates related Navigation capabilities to help you reduce the attention to Navigation details and improve development efficiency. In addition, the framework enhances the page redirection capability, such as route interception and singleton pages. The following describes how to use the HMRouter framework in the scenarios such as page redirection, dialog box, transition animation, data loading, and maintenance and debugging.

Page Redirection

[h2]Page Redirection and Return

HMRouter provides the page redirection and return function based on custom annotations. The procedure is as follows:

  1. Add the @HMRouter annotation to the page that needs redirection and set the pageUrl parameter. In the sample code, the parameter is set to ProductContent.
    @HMRouter({ pageUrl: 'ProductContent' })
    @Component
    export struct ProductContent {
      // ...
      @State param: ParamsType | null = null;
    
      aboutToAppear(): void {
        this.param = HMRouterMgr.getCurrentParam() as ParamsType;
      }
    
      // ...
    }
  2. Call the to method provided by HMRouterMgr at positions requiring page redirection, configuring the target page's address in the parameters. Use the withParam argument to pass any required parameters. You can also configure the unique navigationId for the page stack. You are advised to manually specify a navigationId when using multiple HMNavigation instances, whereas for a single instance, this parameter can be omitted as the system will handle it automatically. The onResult parameter is used to set a callback triggered when the user returns to the current page from another page. Within this callback, obtain the source page that initiated the navigation via srcPageInfo.name and retrieve any data returned to the current page via the result property.
    HMRouterMgr.to('ProductContent')
      .withNavigation('mainNavigationId')
      .withParam({ a: 1, b: 2 })
      .onResult((popInfo: HMPopInfo) => {
        const pageName = popInfo.srcPageInfo.name;
        const params = popInfo.result;
        console.log(`page name is ${pageName}, params is ${JSON.stringify(params)}`);
      })
      .pushAsync()
  3. On the target page, use HMRouterMgr.getCurrentParam() to obtain the passed page parameters.
    @Component
    export struct ProductContent {
      // ...
      @State param: ParamsType | null = null;
    
      aboutToAppear(): void {
        this.param = HMRouterMgr.getCurrentParam() as ParamsType;
      }
    
      // ...
    }
  4. To use the page return function, you can use pop() provided by HMRouterMgr in the corresponding service logic location to return the page. This method supports navigationId. In addition, HMRouter can pass parameters to the returned page by configuring the param.
    HMRouterMgr.pop({ navigationId: 'mainNavigationId', param: this.param })

[h2]Returning to the Target Page After Multiple Page Redirection

If the page redirection path is HomePage > PageA > PageB > PageC and you want to directly return to HomePage from PageC with parameters, simply use the to() method provided by HMRouterMgr with the target page address and relevant parameters. This enables a direct return to the specified page along with the passed data.

HMRouterMgr.to('MainPage')
  .withNavigation('mainNavigationId')
  .withParam(0)
  .pushAsync()
Figure 1 Returning to a specified page

[h2]Redirecting to the Login Page When the Application is not Logged In

When a user does not log in to an application, the login page is automatically redirected to when the user taps some application content. To implement this scenario by using the HMRouter, perform the following steps:

  1. Define the interceptor class LoginCheckInterceptor to implement the IHMInterceptor API.
  2. Add the @HMInterceptor annotation to the defined interceptor class and set interceptorName to LoginCheckInterceptor.
  3. Implement the asynchronous intercept method of the IHMInterceptor. In this method, control the navigation target based on the current login status.
    1. If the user has logged in, call chain.onContinue() to proceed with the original navigation.
    2. If the user has not logged in, prompt the user to log in with a toast, then navigate to the login page, and finally call chain.onIntercept() to intercept the navigation request.
      @HMInterceptor({ interceptorName: 'LoginCheckInterceptor' })
      export class LoginCheckInterceptor implements IHMInterceptor {
        async intercept(chain: IHMInterceptorChain): Promise<void> {
          const info = chain.getRouterInfo();
          const context = chain.getContext();
          // ...
            if (!!AppStorage.get('isLogin')) {
              await chain.onContinue()
            } else {
              info.context.getPromptAction().showToast({ message: 'Please log in first.' });
              HMRouterMgr.push({
                pageUrl: 'loginPage',
                skipAllInterceptor: true
              });
              await chain.onIntercept();
            }
            // ...
        }
      }
  4. Set the interceptors parameter of @HMRouter on the page to be intercepted. Multiple interceptors can be configured on one page. Therefore, the associated interceptor names need to be encapsulated into an array for input.

The figure below shows the effect.

[h2]Redirecting to a Singleton Page

If an application has pages that consume resources greatly during initialization and need to be reused, you can use a singleton page. The video playback page in a video application is one of the typical service scenarios. This page requires video decoder resources and initialization, and this page frequently appears in the video application. To solve this problem, set the singleton parameter in the @HMRouter annotation to true.

@HMRouter({
  pageUrl: 'liveHome',
  singleton: true,
  animator: 'liveInteractiveAnimator',
  lifecycle: 'liveHomeLifecycle'
})
@Component
export struct LiveHome {
  // ...
}

Dialog Box

[h2]Setting a Page to the Dialog Box Type

In the HMRouter framework, set dialog of the @HMRouter annotation to true and then the current page can be used as a dialog box.

@HMRouter({
  pageUrl: PageConstant.PRIVACY_DIALOG_DETAIL,
  dialog: true,
  // ...
})
@Component
export struct PrivacyDialogDetail {
  // ...
}

[h2]Displaying a Dialog Box for Confirmation

When a user returns from a specific page, the application requires the user to confirm the return operation on a dialog box. For example, when a user wants to exit the order payment page, a dialog box is displayed to ask for confirmation. The page exit logic is executed only after the user confirms. In this scenario, you can use a dialog-type page combined with a custom lifecycle to implement this feature. The procedure is as follows:
  1. You need to develop a custom dialog box based on service requirements.
    @HMRouter({ pageUrl: 'PayCancel', dialog: true,animator:'PayCancelDialog' })
    @Component
    export struct PayCancel {
      // ...
      build() {
        Stack({ alignContent: Alignment.Center }) {
          ConfirmDialog({
            title: 'Cancel Order',
            content: 'Are you sure you want to cancel the order?',
            leftButtonName: 'No',
            rightButtonName: 'Yes',
            leftButtonFunc: () => {
              HMRouterMgr.popAsync({
                navigationId: this.queryNavigationInfo()?.navigationId
              });
            },
            rightButtonFunc: () => {
              // ...
            }
          });
        }
        .width('100%')
        .height('100%')
        .position({
          x: '50%',
          y: '50%'
        })
        .markAnchor({
          x: '50%',
          y: '50%'
        });
      }
    }
  2. Define the ExitPayLifecycle class to implement the IHMLifecycle API. Add the @HMLifecycle annotation to the ExitPayLifecycle class, set the lifecycleName to ExitPayLifecycle, and override the onBackPressed callback function in the class. When a user performs the return operation, the callback function is triggered, and the defined PayCancel dialog box pops up.
    @HMLifecycle({ lifecycleName: 'ExitPayLifecycle' })
    export class ExitPayLifecycle implements IHMLifecycle {
      model: ObservedModel = new ObservedModel();
    
      onBackPressed(): boolean {
        HMRouterMgr.to('PayCancel')
          .withParam(this.model.pageUrl)
          .pushAsync()
        return true;
      }
    }
  3. To bind the defined lifecycle to the payment page, you only need to pass in ExitPayLifecycle to the lifecycle parameter of the @HMRouter.
    @HMRouter({
      pageUrl: 'PayDialogContent',
      dialog: true,
      lifecycle: 'ExitPayDialog',
      interceptors: ['LoginCheckInterceptor']
    })
    @Component
    export struct PayDialogContent {
      // ...
    }

The figure below shows the effect.

[h2]Returning Twice to Exit the Application

In this scenario, when a user performs the return operation for the first time, a toast "Return again to exit the app" is displayed. When performs the return operation for the second time, the user exits the application successfully. The procedure is as follows:

  1. Define a lifecycle class ExitAppLifecycle to implement the IHMLifecycle API.
  2. Use the @HMLifecycle annotation to pass ExitAppLifecycle to the lifecycleName parameter.
  3. Rewrite the onBackPressed method (for reference only) to determine the duration between the last return operation and the current one. Then perform the return operation based on the following logic:
    1. If the duration between two return operations is greater than the configured value (1000 ms in this example), a dialog box is displayed and true is returned, indicating the default return logic is not executed.
    2. If the duration between two return operations is less than the configured value (1000 ms in this example), false is returned, indicating that the default return logic is executed and the user can exit the application.
      @HMLifecycle({ lifecycleName: 'ExitAppLifecycle' })
      export class ExitAppLifecycle implements IHMLifecycle {
        private lastTime: number = 0;
      
        onBackPressed(ctx: HMLifecycleContext): boolean {
          let time = new Date().getTime();
          if (time - this.lastTime > 1000) {
            this.lastTime = time;
            ctx.uiContext.getPromptAction().showToast({
              message: 'Go back and exit the application again',
              duration: 1000
            });
            return true;
          } else {
            return false;
          }
        }
      }
  4. Associate the defined lifecycle class with the page. You only need to set lifecycle to the name of the lifecycle to be associated in the @HMRouter annotation.

The figure below shows the effect.

Transition Animation

[h2]Global Custom Transition Animation

[h2]Setting Custom Transition for Specific Pages

You can customize the animation class and implement the effect method in the IHMAnimator API. This method will pass the effect objects enterHandle and exitHandle as parameters. You can use the start or finish methods of the parameter objects to set the start and end states of the corresponding effect. The following common attributes are available as well:

The following sample code indicates that the entrance animation moves from bottom to the top of the screen at a linear speed for 400 ms and the exit animation moves from top to the bottom of the screen at a linear speed for 400 ms.

@HMAnimator({ animatorName: 'CustomAnimator' })
export class CustomAnimator implements IHMAnimator {
  effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
    // to animator
    enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '100%' }).scale({ x: 0.7 }).opacity(0.3)
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '0' }).scale({ x: 1 }).opacity(1)
    })
    enterHandle.duration = 400;
    enterHandle.curve = Curve.Linear;

    // cut animator
    exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '0' }).scale({ x: 1 }).opacity(1)
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '100%' }).scale({ x: 0.7 }).opacity(0.3)
    })
    exitHandle.duration = 400;
    enterHandle.curve = Curve.Linear;
  }
}

After the custom animation is defined, the instance can be passed as the animator parameter of the new chainable page navigation API.

HMRouterMgr.to('ProductContent')
  .withAnimator(new CustomAnimator())
  .pushAsync()

The figure below shows the effect.

[h2]Displaying Different Transition Animations in Different Situations

The same page may have different transition effects in different situations. Take the comment page transition in the video playback page as an example.

Assumed that the comment component is enabled. The entrance and exit animation of comment page is defined as follows when video playback page is in portrait mode:

@HMAnimator({ animatorName: 'myAnimator1' })
export class MyAnimator1 implements IHMAnimator {
  effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
    enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '100%' })
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '0' })
    })

    exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '0' })
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ y: '100%' })
    })
  }
}

The entrance and exit animation of comment page is defined as follows when video playback page is in landscape mode:

@HMAnimator({ animatorName: 'myAnimator2' })
export class MyAnimator2 implements IHMAnimator {
  effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
    enterHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ x: '100%', y: '0' })
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ x: 0 })
    })
    enterHandle.duration = 500;

    exitHandle.start((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ x: '0' })
    }).finish((modifier: AttributeUpdater<NavDestinationAttribute>) => {
      modifier.attribute?.translate({ x: '100%' })
    })
    exitHandle.duration = 500;
  }
}

Finally, set animation effect based on the situation. For example, different animator values are used during page redirection based on whether the video is played in landscape mode.

@Component
export struct CommentInput {
  // ...

  build() {
    Row() {
      Image($r('app.media.icon_comments'))
        .width(24)
        .height(24)
        .margin({ right: 16 })
        .onClick(() => {
          if (this.isLandscape) {
            HMRouterMgr.to('liveComments')
              .withNavigation(this.queryNavigationInfo()?.navigationId)
              .withParam({commentRenderNode: ''})
              .withAnimator(new MyAnimator2())
              .onResult((paramInfo: PopInfo)=>{
                this.videoWidth = '100%';
              })
              .pushAsync()
            this.videoWidth = '50%';
          } else {
            HMRouterMgr.to('liveComments')
              .withNavigation(this.queryNavigationInfo()?.navigationId)
              .withParam({commentRenderNode: ''})
              .withAnimator(new MyAnimator1())
              .onResult((paramInfo: PopInfo)=>{
                this.videoHeight = '100%';
              })
              .pushAsync()
            this.videoHeight = '30%'
          }
        });
    }
  }
}

The figure below shows the effect.

[h2]Interactive Transition

When an application has a requirement for synchronizing an entrance/exit effect of a page with a gesture operation of a user, that is, when a finger of the user moves on the screen, the page moves with the gesture of the user. In the following sample code, you can control the animation playback progress by calling interactive() of the IHMAnimator; determine whether to move rightward to perform the page return operation using actionStart; update the animation progress using updateProgress; obtain the final state of the animation using actionEnd to determine whether to continue the animation and return to the previous page.

@HMAnimator({ animatorName: 'liveInteractiveAnimator' })
export class LiveInteractiveAnimator implements IHMAnimator {
  effect(enterHandle: HMAnimatorHandle, exitHandle: HMAnimatorHandle): void {
    // ...
  }

  interactive(handle: HMAnimatorHandle): void {
    handle.actionStart((event: GestureEvent) => {
      if (event.offsetX > 0) {
        HMRouterMgr.popAsync();
      }
      handle.startOffset = event.fingerList[0].localX;
    });
    handle.updateProgress((event, proxy, operation, startOffset) => {
      if (!proxy?.updateTransition || !startOffset) {
        return;
      }
      let offset = 0;
      if (event.fingerList[0]) {
        offset = Math.abs(event.fingerList[0].localX - startOffset);
      }
      if (offset < 0) {
        proxy?.updateTransition(0);
        return;
      }
      let rectWidth = event.target.area.width as number;
      let rate = offset / rectWidth;
      proxy?.updateTransition(rate);
    });
    handle.actionEnd((event, proxy, operation, startOffset) => {
      if (!startOffset) {
        return;
      }
      let rectWidth = event.target.area.width as number;
      let rate = 0;
      if (event.fingerList[0]) {
        rate = Math.abs(event.fingerList[0].localX - startOffset) / rectWidth;
      }
      if (rate > 0.4) {
        proxy?.finishTransition();
      } else {
        proxy?.cancelTransition?.();
      }
    });
  }
}

The figure below shows the effect.

Data Loading

[h2]Data Request Preloading and Page Redirection in Parallel

In this scenario, you want to preload the network request and execute the network request in other threads without blocking the main thread. The code implementation is as follows:

  1. Define the networkRequest function. You can use TaskPool to execute network requests in other threads and return request results.
    @Concurrent
    async function networkRequest(lifecycle: string): Promise<string> {
      // ...
    }
  2. Define the lifecycle. In the onPrepare callback function, execute the corresponding network request function. The callback is triggered after the interceptor is executed and before the route stack is pushed.
    @HMLifecycle({ lifecycleName: 'requestLifecycle' })
    export class ExampleLifecycle implements IHMLifecycle {
      private requestModel: RequestModel = new RequestModel();
    
      onPrepare(): void {
        console.log(this.requestModel.data);
        let task: taskpool.Task = new taskpool.Task(networkRequest, 'onPrepare');
        taskpool.execute(task).then((res: Object) => {
          console.log(res + '');
        });
      }
    
      // ...
    }
  3. Associate the lifecycle with the corresponding component. The lifecycleName is passed as the lifecycle parameter of the @HMRouter annotation to complete the association.
Figure 2 Preloading process of data request

[h2]Restoring Data After Page Re-opening

In this scenario, the browsing history (such as the scroll position) persists even after the page is closed. A typical case is the comments section of a short video: when a user opens it, scrolls to a point, and then closes it, the comments will remain at that same scroll position upon reopening. The code implementation is as follows:

  1. Use BuilderNode to construct the comment component. In the makeNode function, if the comment component does not exist, create one; if it exists, return the component.
    @Builder
    function buildComment(liveComments: LiveCommentsProduct[]) {
      // ...
    }
    
    export class CommentNodeController extends NodeController {
      commentList: BuilderNode<[LiveCommentsProduct[]]> | null = null;
      commentListData: LiveCommentsProduct[] = new LiveCommentsModel().getLiveCommentsList();
    
      constructor() {
        super();
      }
    
      makeNode(context: UIContext): FrameNode | null {
        if (this.commentList === null) {
          this.nodeBuild(context);
        }
        return this.commentList!.getFrameNode();
      }
    
      nodeBuild(context: UIContext) {
        this.commentList = new BuilderNode(context);
        if (this.commentList !== null) {
          this.commentList.build(wrapBuilder<[LiveCommentsProduct[]]>(buildComment), this.commentListData);
        }
      }
    
      dispose() {
        if (this.commentList !== null) {
          this.commentList.dispose();
        }
      }
    }
  2. In the @HMLifecycle lifecycle, the instance of the CommentNodeController class is created and released along with the lifecycle of the video playback page, instead of the lifecycle of the comment page component. In this way, when a user is on the video playback page, the BuilderNode of the comment page component is stored in the memory. Therefore, when the user closes the comment page and reopens it, the browsing progress remains.
    @HMLifecycle({ lifecycleName: 'liveHomeLifecycle' })
    export class LiveHomeLifecycle implements IHMLifecycle {
      commentRenderNode: CommentNodeController = new CommentNodeController();
      // ...
      onAppear(ctx: HMLifecycleContext): void {
        this.commentRenderNode.makeNode(ctx.uiContext);
      }
    
      onDisAppear(ctx: HMLifecycleContext): void {
        this.commentRenderNode.dispose();
      }
    }
  3. Obtain the commentRenderNode within the lifecycle from the corresponding UI component and use NodeContainer to mount the commentRenderNode in the subsequent service logic.
    @Component
    export struct CommentInput {
      @StorageLink('changeVideoHeight') videoHeight: string | number = CommonConstants.FULL_PERCENT;
      commentRenderNode: CommentNodeController = new CommentNodeController();
    
      // ...
      }
Figure 3 Data restoration process after page re-opening

Maintenance and Debugging

[h2]Page Tracking Development

If you need to collect statistics on the page loading duration or other custom dotting data, you can use the lifecycle callbacks to perform dotting at the corresponding position. The following example shows how to collect statistics on the page stay duration. The implementation is as follows:

  1. Define the PageDurationLifecycle class to implement the IHMLifecycle API.
  2. Add the @HMLifecycle annotation to this class and set global to true to configure the lifecycle globally so that all pages will execute the same lifecycle.
  3. Call onShown() to record the current timestamp. Call onHidden() to calculate the page stay duration.
    @HMLifecycle({ lifecycleName: 'PageDurationLifecycle', global: true })
    export class PageDurationLifecycle implements IHMLifecycle {
      private time: number = 0;
    
      onShown(): void {
        this.time = new Date().getTime();
      }
    
      onHidden(ctx: HMLifecycleContext): void {
        const duration = new Date().getTime() - this.time;
        console.log(`Page ${ctx.navContext?.pathInfo.name} stay ${duration}`);
      }
    }
Figure 4 Page tracking log

Sample Code