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(lib): start of generic lib. Routemonitor #508

Merged
merged 1 commit into from
Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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