IBM / pwa-lit-template

A template for building Progressive Web Applications using Lit and Vaadin Router.

Home Page:https://pwa-lit-template.mybluemix.net

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Research the router export

abdonrd opened this issue · comments

Right now we lazy import and initialize the router here:

private async initializeRouter() {
const router = await import('../router/index');
router.init(this.main);
}
firstUpdated() {
this.initializeRouter();
}

This router.init() function doesn't export anything:

export const init = (outlet: HTMLElement) => {
const router = new Router(outlet, { baseUrl: config.routerBaseUrl });
router.setRoutes([
// Redirect to URL without trailing slash
{
path: '(.*)/',
action: (context, commands) => {
const newPath = context.pathname.slice(0, -1);
return commands.redirect(newPath);
}
},
...routes
]);
};

Doing it this way, we found a problem:
We can't import the router instance to use the router helpers.

For example, we want to replace the hardcoded link in the not found page to use the router name. From this:

<a href="/">Back to home</a>

To something like this:

<a href="${router.urlForName('home')}">Back to home</a> 

And the same for the navigation links:

<nav>
<a href="/">Home</a>
<span>-</span>
<a href="/about">About</a>
</nav>

A proposal: #20

This is also important to inherit the baseUrl property from the Vaadin Router in the routes.

I would consider using async directive for urlForName helpers.

let routerInstance;

export const initRouter = async (outlet) => {
  if (!routerInstance && outlet) {
    const router = await import('../router/index');
    routerInstance = router.init(outlet);
  }
  return routerInstance;
};

export const waitForRouter = () => {
  return new Promise((resolve) => {
    if (routerInstance) {
      resolve(routerInstance);
    } else {
      setTimeout(() => waitForRouter(), 100);
    }
  });
};

// use "until" directive to use helpers asynchronously
export const urlForName = (name) => {
  return until(waitForRouter().then((r) => r.urlForName(name)), '');
};

Thanks @web-padawan! 👏

I will try it as soon as I can! (busy days 😅 )

@web-padawan I'm missing something, right? Because I have not managed to make it work.

You can see it here: https://github.com/IBM/pwa-lit-template/compare/router-helper

I will experiment with your branch later today, and will try to come up with a better approach.

Submitted a PR with a proposed change: #64