Giter VIP home page Giter VIP logo

stencil-router-v2's Introduction

stencil-router-v2

⚠️ This project has been archived. ⚠️

Stencil Router V2 was an experimental router that did not reach v1.0 status, and should be considered unsupported.

Individuals and teams looking for a Stencil-based router solution should see the Stencil Community Router project.

The project can continue to be downloaded in its current state from the NPM registry, and may be forked by individuals wishing to build directly off of it.

The documentation below is kept for historical purposes only.


Stencil Router V2 is an experimental new router for stencil that focus in:

  • Lightweight (600bytes)
  • Treeshakable (not used features are not included in the final build)
  • Simple, provide the bare mininum but it make it extendable with hooks.
  • No DOM: Router is not render any extra DOM element, to keep styling simple.
  • Fast: As fast and lightweight as writing your own router with if statements.

How does it work?

This router backs up the document.location in a @stencil/store, this way we can respond to changes in document.location is a much simpler, way, not more subscribes, no more event listeners events to connect and disconnect.

Functional Components are the used to collect the list of routes, finally the Switch renders only the selected route.

Install

npm install stencil-router-v2 --save-dev

Examples

import { createRouter, Route } from 'stencil-router-v2';

const Router = createRouter();

@Component({
  tag: 'app-root',
})
export class AppRoot {

  render() {
    return (
      <Host>
        <Router.Switch>

          <Route path="/">
            <h1>Welcome<h1>
            <p>Welcome to the new stencil-router demo</p>
          </Route>

          <Route path={/^\/account/}>
            <app-account></app-account>
          </Route>

        </Router.Switch>
      </Host>
    );
  }
}

Redirects

<Host>
  <Router.Switch>

    <Route path="/" to="/main"/>
    <Route path={/^account/} to="/error"/>

  </Router.Switch>
</Host>

Params

Route can take an optional render property that will pass down the params. This method should be used instead of JSX children.

Regex or functional matches have the chance to generate an object of params when the URL matches.

import { createRouter, Route, match } from 'stencil-router-v2';

const Router = createRouter();

<Host>
  <Router.Switch>

    <Route
      path={/^acc(ou)nt/}
      render={(params) => (
        <p>{params[1]}</p>
      )}
    />

    <Route
      path={match('/blog/:page')}
      render={({page}) => <blog-post page={page}>}
    />

    <Route
      path={(url) => {
        if (url.includes('hello')) {
          return {user: 'hello'}
        }
        return undefined;
      }}
      render={({user}) => (
        <h1>User: {user}</h1>
      )}
    />

  </Router.Switch>
</Host>

Links

The href() function will inject all the handles to an native anchor, without extra DOM.

import { createRouter, Route, href } from 'stencil-router-v2';

const Router = createRouter();

<Host>
  <Router.Switch>

    <Route path="/main">
      <a {...href('/main')} class="my-link">Go to blog</a>
    </Route>

    <Route path="/blog">
      <a {...href('/main')}>Go to main</a>
    </Route>

  </Router.Switch>
</Host>

Dynamic routes (guards)

@Component({
  tag: 'app-root',
})
export class AppRoot {

  @State() logged = false;
  render() {
    return (
      <Host>
        <Router.Switch>

          {this.logged && (
            <Route path="/account">
              <app-account></app-account>
            </Route>
          )}

          {!this.logged && (
            <Route path="/account" to="/error"/>
          )

        </Router.Switch>
      </Host>
    );
  }
}

Subscriptions to route changes

Because the router uses @stencil/store its trivial to subscribe to changes in the locations, activeRoute, or even the list of routes.

import { createRouter, Route } from 'stencil-router-v2';

const Router = createRouter();

@Component({
  tag: 'app-root',
})
export class AppRoot {
  componentWillLoad() {
    Router.onChange('url', (newValue: InternalRouterState['url'], _oldValue: InternalRouterState['url']) => {
      // Access fields such as pathname, search, etc. from newValue

      // This would be a good place to send a Google Analytics event, for example
    });
  }

  render() {
    const activePath = Router.state.activeRoute?.path;

    return (
      <Host>
        <aside>
          <a class={{'active': activePath === '/main'}}>Main</a>
          <a class={{'active': activePath === '/account'}}>Account</a>
        </aside>

        <Router.Switch>

          <Route path="/main">
            <h1>Welcome<h1>
            <p>Welcome to the new stencil-router demo</p>
          </Route>

          <Route path='/account'>
            <app-account></app-account>
          </Route>

        </Router.Switch>
      </Host>
    );
  }
}

The routes state includes:

  url: URL;
  activeRoute?: RouteEntry;
  urlParams: { [key: string]: string };
  routes: RouteEntry[];

stencil-router-v2's People

Contributors

adamdbradley avatar manucorporat avatar mlynch avatar peterpeterparker avatar rwaskiewicz avatar serabe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stencil-router-v2's Issues

Routing to same page with dynamic params

I have the problem when I am routing to the same page with dynamic parameters, that stencil-router is not rerendering.
I am using an input as a search field. The dropdown holds the link to a details page with and id as parameter (see scrennshot)
The route for the dynamic link: <stencil-route url='/details:id' component='app-details' /> When I am on the details page and change the dynamic id the site will not render again. My solution right now is to reload the page, but than I am loosing the search results and I have to input a new search again.

@Method()
    async goTo(e, route, data) {
      e.preventDefault();
      this.history.push(route, {data})
      window.location.reload()
    }

Link tho the repro: https://github.com/upstroke/tmdb-stencil-frontend

Bildschirmfoto 2020-12-02 um 11 11 18

[Important] 0.6.0 in npm is missing the helper function. Url change won't scroll to top!

This function is missing in the build.

const handlePushState = (win, loc, hstry, isFromPopState, newUrl) => {
    const pathBeforePush = urlToPath(loc);
    const newHref = newUrl.href;
    const hasHash = newUrl.hash.startsWith('#');
    if (shouldPushState(loc, newUrl)) {
        hstry.pushState(null, '', newHref);
    }
    if (!isFromPopState) {
        if (pathBeforePush !== urlToPath(newUrl)) {
            if (hasHash) {
                loc.href = newHref;
            }
            else {
                win.scrollTo(0, 0);
            }
        }
        else if (hasHash) {
            loc.href = newHref;
        }
    }
};

goto

Let's say user done modifying his profile at /profile/edit

How to programatically go to /dashboard after successful updating?

Thank you

Minor Bug: Example #1

Hi, a minor syntax error in the first example; with a second h1 open tag instead of a closing one:

<Route path="/">
     <h1>Welcome<h1>
     <p>Welcome to the new stencil-router demo</p>
</Route>

hash in url

Is it possible to use the v2 version with hash in path ?

for example http://localhost:3333/#/profile/stencil

don't match with <Route path={match('/profile/:name')} render={({ name }) => } />

or with <Route path={match('/#/profile/:name')} render={({ name }) => } />

Handle links clicks without calling href()?

Hi team,

Great work on such a tiny, but deadly router 🚀 . I do have a concern however:

How do I handle links that are not using the href() function? e.g links generated from .md files?

  • Do I add a global (or some parent) click handler to listen to link clicks and decide what to do afterwards?
  • Do I add a mutation observer and update link hrefs as they are added to the DOM?
  • Do I introduce custom renderers to my markdown files? (although i don't see how that could be achieved during compile time with href(). it will have to be during runtime)
  • Do I do nothing and just let them trigger a full page reload ? 😢

Also from what I can see from the code, href() is adding an onClick to the link, which means that we are potentially generating a large number of callback functions, which could be replaced with a single, global click handler instead

Would you accept a PR, that introduces a global click handler, that would remove the need of using href(), meaning the router would work on any anchor elements. Here's an example of what I am suggesting (my assumptions about Router.match and Router.push might be wrong, but I hope you get the overall idea) :

function setGlobalLinkHandler(enable: Boolean, target: EventTarget = document) {
  if (enable) {
    target.addEventListener('click', linkClicked)
  } else {
    target.removeEventListener('click', linkClicked)
  }
}

function linkClicked(event: MouseEvent) {
  const link = event.target.closest('a');

  if (
    link == null || // ignore click if not on or inside a link
    event.button !== 0 || // ignore non-left clicks
    event.ctrlKey || // ignore ctrl clicks, as it opens in new tab
    event.shiftKey || // ignore ctrl clicks, as it opens in new window
    event.metaKey || // ignore cmd clicks, as it opens in new tab (macos)
    link.hasAttribute('href') === false || // ignore links without href
    link.target === '_blank' || // ignore 'target="_blank"' (can be configurable)
    link.hasAttribute('download') || // ignore download links obviously
    link.rel.indexOf('external') > -1 || // ignore explicit external links
    Router.match(link.href) == null // finally ignore if href does not match a route
  ) {
    return;
  }

  event.preventDefault(); // prevent default to avoid full page reload
  Router.push(link.href); // navigate to route
}

Thank you :)

docs: navigating programmatically

I had a use case from router v1 like this:
https://github.com/ionic-team/stencil-router/wiki/Navigating-Programmatically

and in v2 I didn't see any recommendation so here is what I can up with:

using stencil store I have a router initialized there as readonly property:

// store.ts

import { createStore } from "@stencil/store";

type Store = {
    readonly router: Router
}

const { state } = createStore<Store>({
    router: createRouter()
});

export { state };

for app-root definitions:

// app-root component
import { href, Route } from 'stencil-router-v2';
import { state } from '../../store/store';
const Router = state.router;

@Component({
  tag: 'app-root',
  styleUrl: 'app-root.css',
  shadow: true,
})
export class AppRoot {
  render() {
    return (
      <Host>
          <Router.Switch>

            <Route path="/" to="/week-view"/>

            <Route path="/week-view">
              <week-view></week-view>
            </Route>

            <Route path="/other-path">
              <other-path></other-path>
            </Route>

          </Router.Switch>
      </Host>
    );
  }
}

and finally in other components I can call navigation from JS like:

// anywhere
state.router.push(`/other-path`);

Is there better approach ?
Cheers ;)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.