Skip to content

Commit

Permalink
feat(lib): start of generic lib. Routemonitor (#508)
Browse files Browse the repository at this point in the history
  • Loading branch information
SanderElias authored Apr 27, 2020
1 parent edbdcc3 commit 78a2e9a
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 2 deletions.
62 changes: 62 additions & 0 deletions generics/lib/src/routeMonitor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {interval, merge, of, Subject} from 'rxjs';
import {distinctUntilChanged, filter, map, repeat, switchMap, take, takeWhile, tap} from 'rxjs/operators';

interface Mc {
prev: URL;
}
const hasChanged = new Subject<string>();
const mightChange = new Subject<Mc>();

if (window && history) {
window.addEventListener('popstate', ev => hasChanged.next(location.href));

/**
* monkeyPath ps
* used to monitor route changes, this is a 'route-start'
*/
const hps = history.pushState.bind(history);
history.pushState = (data: any, tile: string, url: string) => {
// console.log('push', url);
mightChange.next({prev: new URL(location.href)});
hps(data, tile, url);
};

const maxTime = 1000; // use 1 second for now
const pollInterval = 5;
const maxTakes = maxTime / pollInterval;

/**
* While the polling might seem overkill, it is needed
* if a framework is doing things like authentication on routes, or data fetching
* it might take longer before the route change is finalized.
*/
mightChange
.pipe(
switchMap(mc =>
/** start polling */
interval(pollInterval).pipe(
tap(() => console.log('interval')),
/** take while its not changed */
takeWhile(() => location.pathname === mc.prev.pathname),
/** OR the timeout is reached */
take(maxTakes),
map(() => mc)
)
),
/** filter out non-url changing pushes */
filter(({prev}) => location.pathname !== prev.pathname),
/** take 1 change */
take(1),
/** and start over */
repeat(),
/** map to the current URL */
map(() => location.href)
)
.subscribe(hasChanged);
}

// tslint:disable-next-line: deprecation
export const route$ = merge(of(location.href), hasChanged).pipe(
distinctUntilChanged(),
map(u => new URL(u))
);
2 changes: 1 addition & 1 deletion scully/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion scully/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@scullyio/scully",
"version": "0.0.87",
"version": "0.0.88",
"description": "Scully CLI",
"repository": {
"type": "GIT",
Expand Down

0 comments on commit 78a2e9a

Please sign in to comment.