chore: format
This commit is contained in:
@@ -1,79 +1,98 @@
|
||||
export {
|
||||
applyMixins,
|
||||
subscribeWhen,
|
||||
unsubscribeWhen,
|
||||
filterWhen,
|
||||
bufferDebounceTime,
|
||||
fetchRx,
|
||||
fragmentFromString,
|
||||
createMutationObservable,
|
||||
getScrollHeight,
|
||||
getScrollLeft,
|
||||
getScrollTop,
|
||||
matches,
|
||||
matchesAncestors
|
||||
} from '@hydecorp/component';
|
||||
applyMixins,
|
||||
subscribeWhen,
|
||||
unsubscribeWhen,
|
||||
filterWhen,
|
||||
bufferDebounceTime,
|
||||
fetchRx,
|
||||
fragmentFromString,
|
||||
createMutationObservable,
|
||||
getScrollHeight,
|
||||
getScrollLeft,
|
||||
getScrollTop,
|
||||
matches,
|
||||
matchesAncestors,
|
||||
} from "@hydecorp/component";
|
||||
|
||||
export enum Cause {
|
||||
Init = "init",
|
||||
Hint = "hint",
|
||||
Push = "push",
|
||||
Pop = "pop",
|
||||
};
|
||||
Init = "init",
|
||||
Hint = "hint",
|
||||
Push = "push",
|
||||
Pop = "pop",
|
||||
}
|
||||
|
||||
export interface Context {
|
||||
cause: Cause,
|
||||
url: URL,
|
||||
oldURL?: URL,
|
||||
cacheNr?: number,
|
||||
replace?: boolean,
|
||||
error?: any,
|
||||
anchor?: HTMLAnchorElement,
|
||||
cause: Cause;
|
||||
url: URL;
|
||||
oldURL?: URL;
|
||||
cacheNr?: number;
|
||||
replace?: boolean;
|
||||
error?: any;
|
||||
anchor?: HTMLAnchorElement;
|
||||
}
|
||||
|
||||
export interface ClickContext extends Context {
|
||||
event: MouseEvent,
|
||||
event: MouseEvent;
|
||||
}
|
||||
|
||||
export function isExternal(
|
||||
url?: { protocol: string, host: string } | null,
|
||||
location: { protocol: string, host: string } = window.location,
|
||||
url?: { protocol: string; host: string } | null,
|
||||
location: { protocol: string; host: string } = window.location,
|
||||
) {
|
||||
return url != null && (url.protocol !== location.protocol || url.host !== location.host);
|
||||
return (
|
||||
url != null &&
|
||||
(url.protocol !== location.protocol || url.host !== location.host)
|
||||
);
|
||||
}
|
||||
|
||||
export function isHash(
|
||||
{ hash, origin, pathname }: { hash: string, origin: string, pathname: string },
|
||||
location: { hash: string, origin: string, pathname: string } = window.location,
|
||||
{
|
||||
hash,
|
||||
origin,
|
||||
pathname,
|
||||
}: { hash: string; origin: string; pathname: string },
|
||||
location: {
|
||||
hash: string;
|
||||
origin: string;
|
||||
pathname: string;
|
||||
} = window.location,
|
||||
) {
|
||||
return hash !== "" && origin === location.origin && pathname === location.pathname;
|
||||
return (
|
||||
hash !== "" && origin === location.origin && pathname === location.pathname
|
||||
);
|
||||
}
|
||||
|
||||
export function shouldLoadAnchor(anchor?: HTMLAnchorElement | null) {
|
||||
return anchor && anchor.target === "";
|
||||
return anchor && anchor.target === "";
|
||||
}
|
||||
|
||||
export function isPushEvent({ url, anchor, event: { metaKey, ctrlKey } }: ClickContext, location: Location) {
|
||||
return !!(
|
||||
!metaKey &&
|
||||
!ctrlKey &&
|
||||
shouldLoadAnchor(anchor) &&
|
||||
!isExternal(url, location)
|
||||
);
|
||||
export function isPushEvent(
|
||||
{ url, anchor, event: { metaKey, ctrlKey } }: ClickContext,
|
||||
location: Location,
|
||||
) {
|
||||
return !!(
|
||||
!metaKey &&
|
||||
!ctrlKey &&
|
||||
shouldLoadAnchor(anchor) &&
|
||||
!isExternal(url, location)
|
||||
);
|
||||
}
|
||||
|
||||
export function isHintEvent({ url, anchor }: Context, location: Location) {
|
||||
return !!(
|
||||
shouldLoadAnchor(anchor) &&
|
||||
!isExternal(url, location) &&
|
||||
!isHash(url, location)
|
||||
);
|
||||
return !!(
|
||||
shouldLoadAnchor(anchor) &&
|
||||
!isExternal(url, location) &&
|
||||
!isHash(url, location)
|
||||
);
|
||||
}
|
||||
|
||||
export function isHashChange({
|
||||
cause,
|
||||
url: { pathname, hash },
|
||||
oldURL,
|
||||
cause,
|
||||
url: { pathname, hash },
|
||||
oldURL,
|
||||
}: Context) {
|
||||
return pathname === oldURL?.pathname && (cause === Cause.Pop || (cause === Cause.Push && hash !== ''));
|
||||
return (
|
||||
pathname === oldURL?.pathname &&
|
||||
(cause === Cause.Pop || (cause === Cause.Push && hash !== ""))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,93 +1,126 @@
|
||||
import { Subject, Observable, from, fromEvent, of, merge, NEVER } from "rxjs";
|
||||
|
||||
import { matchesAncestors, createMutationObservable, subscribeWhen, bufferDebounceTime } from "./common";
|
||||
import { map, filter, startWith, tap, mergeMap, mergeAll, switchMap } from "rxjs/operators";
|
||||
import {
|
||||
matchesAncestors,
|
||||
createMutationObservable,
|
||||
subscribeWhen,
|
||||
bufferDebounceTime,
|
||||
} from "./common";
|
||||
import {
|
||||
map,
|
||||
filter,
|
||||
startWith,
|
||||
tap,
|
||||
mergeMap,
|
||||
mergeAll,
|
||||
switchMap,
|
||||
} from "rxjs/operators";
|
||||
|
||||
const flat = <T>(x: Array<Array<T>>): Array<T> => Array.prototype.concat.apply([], x);
|
||||
const flat = <T>(x: Array<Array<T>>): Array<T> =>
|
||||
Array.prototype.concat.apply([], x);
|
||||
|
||||
type MiniRecord = { addedNodes: Iterable<Node>, removedNodes: Iterable<Node> };
|
||||
type MiniRecord = { addedNodes: Iterable<Node>; removedNodes: Iterable<Node> };
|
||||
|
||||
const combineRecords = (records: MiniRecord[]) => ({
|
||||
addedNodes: new Set(flat(records.map(r => Array.from(r.addedNodes)))),
|
||||
removedNodes: new Set(flat(records.map(r => Array.from(r.removedNodes)))),
|
||||
addedNodes: new Set(flat(records.map((r) => Array.from(r.addedNodes)))),
|
||||
removedNodes: new Set(flat(records.map((r) => Array.from(r.removedNodes)))),
|
||||
});
|
||||
|
||||
export class EventListenersMixin {
|
||||
el!: HTMLElement;
|
||||
el!: HTMLElement;
|
||||
|
||||
linkSelector!: string;
|
||||
linkSelector!: string;
|
||||
|
||||
$!: {
|
||||
linkSelector: Subject<string>;
|
||||
prefetch: Subject<boolean>;
|
||||
}
|
||||
$!: {
|
||||
linkSelector: Subject<string>;
|
||||
prefetch: Subject<boolean>;
|
||||
};
|
||||
|
||||
// LINKS 2
|
||||
setupEventListeners() {
|
||||
const pushEvent$ = fromEvent(this.el, "click").pipe(
|
||||
map(event => {
|
||||
const anchor = matchesAncestors(<Element>event.target, this.linkSelector);
|
||||
if (anchor instanceof HTMLAnchorElement) {
|
||||
return [event, anchor] as [MouseEvent, HTMLAnchorElement];
|
||||
}
|
||||
}),
|
||||
filter(x => !!x),
|
||||
);
|
||||
// LINKS 2
|
||||
setupEventListeners() {
|
||||
const pushEvent$ = fromEvent(this.el, "click").pipe(
|
||||
map((event) => {
|
||||
const anchor = matchesAncestors(
|
||||
<Element>event.target,
|
||||
this.linkSelector,
|
||||
);
|
||||
if (anchor instanceof HTMLAnchorElement) {
|
||||
return [event, anchor] as [MouseEvent, HTMLAnchorElement];
|
||||
}
|
||||
}),
|
||||
filter((x) => !!x),
|
||||
);
|
||||
|
||||
const matchOrQuery = (el: Element, selector: string): Observable<HTMLAnchorElement> => {
|
||||
if (el.matches(selector) && el instanceof HTMLAnchorElement) {
|
||||
return of(el);
|
||||
} else {
|
||||
return from(el.querySelectorAll(selector)).pipe(
|
||||
filter((el): el is HTMLAnchorElement => el instanceof HTMLAnchorElement),
|
||||
);
|
||||
}
|
||||
}
|
||||
const matchOrQuery = (
|
||||
el: Element,
|
||||
selector: string,
|
||||
): Observable<HTMLAnchorElement> => {
|
||||
if (el.matches(selector) && el instanceof HTMLAnchorElement) {
|
||||
return of(el);
|
||||
} else {
|
||||
return from(el.querySelectorAll(selector)).pipe(
|
||||
filter(
|
||||
(el): el is HTMLAnchorElement => el instanceof HTMLAnchorElement,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const addEventListeners = (link: HTMLAnchorElement) => {
|
||||
return merge(
|
||||
fromEvent(link, "mouseenter", { passive: true }),
|
||||
fromEvent(link, "touchstart", { passive: true }),
|
||||
fromEvent(link, "focus", { passive: true }),
|
||||
).pipe(map(event => [event, link] as [Event, HTMLAnchorElement]))
|
||||
};
|
||||
const addEventListeners = (link: HTMLAnchorElement) => {
|
||||
return merge(
|
||||
fromEvent(link, "mouseenter", { passive: true }),
|
||||
fromEvent(link, "touchstart", { passive: true }),
|
||||
fromEvent(link, "focus", { passive: true }),
|
||||
).pipe(map((event) => [event, link] as [Event, HTMLAnchorElement]));
|
||||
};
|
||||
|
||||
const hintEvent$ = this.$.linkSelector.pipe(switchMap((linkSelector) => {
|
||||
const links = new Map<HTMLAnchorElement, Observable<[Event, HTMLAnchorElement]>>();
|
||||
const hintEvent$ = this.$.linkSelector.pipe(
|
||||
switchMap((linkSelector) => {
|
||||
const links = new Map<
|
||||
HTMLAnchorElement,
|
||||
Observable<[Event, HTMLAnchorElement]>
|
||||
>();
|
||||
|
||||
const addLink = (link: HTMLAnchorElement) => {
|
||||
if (!links.has(link)) {
|
||||
links.set(link, addEventListeners(link));
|
||||
}
|
||||
}
|
||||
const removeLink = (link: HTMLAnchorElement) => {
|
||||
links.delete(link);
|
||||
}
|
||||
const addLink = (link: HTMLAnchorElement) => {
|
||||
if (!links.has(link)) {
|
||||
links.set(link, addEventListeners(link));
|
||||
}
|
||||
};
|
||||
const removeLink = (link: HTMLAnchorElement) => {
|
||||
links.delete(link);
|
||||
};
|
||||
|
||||
return createMutationObservable(this.el, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
}).pipe(
|
||||
startWith({ addedNodes: [this.el], removedNodes: [] }),
|
||||
bufferDebounceTime(500),
|
||||
map(combineRecords),
|
||||
switchMap(({ addedNodes, removedNodes }) => {
|
||||
from(removedNodes)
|
||||
.pipe(
|
||||
filter((el): el is Element => el instanceof Element),
|
||||
mergeMap((el) => matchOrQuery(el, linkSelector)),
|
||||
tap(removeLink),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
return createMutationObservable(this.el, { childList: true, subtree: true }).pipe(
|
||||
startWith({ addedNodes: [this.el], removedNodes: [] }),
|
||||
bufferDebounceTime(500),
|
||||
map(combineRecords),
|
||||
switchMap(({ addedNodes, removedNodes }) => {
|
||||
from(removedNodes).pipe(
|
||||
filter((el): el is Element => el instanceof Element),
|
||||
mergeMap(el => matchOrQuery(el, linkSelector)),
|
||||
tap(removeLink)
|
||||
).subscribe()
|
||||
from(addedNodes)
|
||||
.pipe(
|
||||
filter((el): el is Element => el instanceof Element),
|
||||
mergeMap((el) => matchOrQuery(el, linkSelector)),
|
||||
tap(addLink),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
from(addedNodes).pipe(
|
||||
filter((el): el is Element => el instanceof Element),
|
||||
mergeMap(el => matchOrQuery(el, linkSelector)),
|
||||
tap(addLink)
|
||||
).subscribe()
|
||||
return from(links.values()).pipe(mergeAll());
|
||||
}),
|
||||
subscribeWhen(this.$.prefetch),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return from(links.values()).pipe(mergeAll());
|
||||
}),
|
||||
subscribeWhen(this.$.prefetch),
|
||||
);
|
||||
}));
|
||||
|
||||
return { hintEvent$, pushEvent$ }
|
||||
}
|
||||
return { hintEvent$, pushEvent$ };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,68 +1,68 @@
|
||||
import { Context } from './common';
|
||||
import { ResponseContextErr } from './fetch';
|
||||
import { Context } from "./common";
|
||||
import { ResponseContextErr } from "./fetch";
|
||||
import { HyPushState } from "./index";
|
||||
|
||||
const timeout = (t: number) => new Promise(r => setTimeout(r, t));
|
||||
const timeout = (t: number) => new Promise((r) => setTimeout(r, t));
|
||||
|
||||
export class EventManager {
|
||||
private parent: HyPushState;
|
||||
private parent: HyPushState;
|
||||
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
onStart(context: Context) {
|
||||
this.parent.animPromise = timeout(this.parent.duration);
|
||||
onStart(context: Context) {
|
||||
this.parent.animPromise = timeout(this.parent.duration);
|
||||
|
||||
const transitionUntil = (promise: Promise<{}>) => {
|
||||
this.parent.animPromise = Promise.all([this.parent.animPromise, promise]);
|
||||
};
|
||||
const transitionUntil = (promise: Promise<{}>) => {
|
||||
this.parent.animPromise = Promise.all([this.parent.animPromise, promise]);
|
||||
};
|
||||
|
||||
this.parent.fireEvent('start', { detail: { ...context, transitionUntil } });
|
||||
}
|
||||
this.parent.fireEvent("start", { detail: { ...context, transitionUntil } });
|
||||
}
|
||||
|
||||
emitDOMError(error: any) {
|
||||
if (process.env.DEBUG) console.error(error);
|
||||
emitDOMError(error: any) {
|
||||
if (process.env.DEBUG) console.error(error);
|
||||
|
||||
// To open the link directly, we first pop one entry off the browser history.
|
||||
// We have to do this because some browsers (Safari) won't handle the back button correctly otherwise.
|
||||
// We then wait for a short time and change the document's location.
|
||||
// TODO: If we didn't call `pushState` optimistically we wouldn't have to do this.
|
||||
// TODO: Use browser sniffing instead?
|
||||
const url = location.href;
|
||||
window.history.back();
|
||||
setTimeout(() => document.location.assign(url), 100);
|
||||
}
|
||||
// To open the link directly, we first pop one entry off the browser history.
|
||||
// We have to do this because some browsers (Safari) won't handle the back button correctly otherwise.
|
||||
// We then wait for a short time and change the document's location.
|
||||
// TODO: If we didn't call `pushState` optimistically we wouldn't have to do this.
|
||||
// TODO: Use browser sniffing instead?
|
||||
const url = location.href;
|
||||
window.history.back();
|
||||
setTimeout(() => document.location.assign(url), 100);
|
||||
}
|
||||
|
||||
emitNetworkError(context: ResponseContextErr) {
|
||||
if (process.env.DEBUG) console.error(context);
|
||||
this.parent.fireEvent('networkerror', { detail: context });
|
||||
}
|
||||
emitNetworkError(context: ResponseContextErr) {
|
||||
if (process.env.DEBUG) console.error(context);
|
||||
this.parent.fireEvent("networkerror", { detail: context });
|
||||
}
|
||||
|
||||
emitError(context: Context) {
|
||||
if (process.env.DEBUG) console.error(context);
|
||||
this.parent.fireEvent('error', { detail: context });
|
||||
}
|
||||
emitError(context: Context) {
|
||||
if (process.env.DEBUG) console.error(context);
|
||||
this.parent.fireEvent("error", { detail: context });
|
||||
}
|
||||
|
||||
emitReady(context: Context) {
|
||||
this.parent.fireEvent('ready', { detail: context });
|
||||
}
|
||||
emitReady(context: Context) {
|
||||
this.parent.fireEvent("ready", { detail: context });
|
||||
}
|
||||
|
||||
emitAfter(context: Context) {
|
||||
this.parent.fadePromise = timeout(this.parent.duration);
|
||||
emitAfter(context: Context) {
|
||||
this.parent.fadePromise = timeout(this.parent.duration);
|
||||
|
||||
const transitionUntil = (promise: Promise<{}>) => {
|
||||
this.parent.fadePromise = Promise.all([this.parent.fadePromise, promise]);
|
||||
};
|
||||
const transitionUntil = (promise: Promise<{}>) => {
|
||||
this.parent.fadePromise = Promise.all([this.parent.fadePromise, promise]);
|
||||
};
|
||||
|
||||
this.parent.fireEvent('after', { detail: { ...context, transitionUntil } });
|
||||
}
|
||||
this.parent.fireEvent("after", { detail: { ...context, transitionUntil } });
|
||||
}
|
||||
|
||||
emitProgress(context: Context) {
|
||||
this.parent.fireEvent('progress', { detail: context });
|
||||
}
|
||||
emitProgress(context: Context) {
|
||||
this.parent.fireEvent("progress", { detail: context });
|
||||
}
|
||||
|
||||
emitLoad(context: Context) {
|
||||
this.parent.fireEvent('load', { detail: context });
|
||||
}
|
||||
};
|
||||
emitLoad(context: Context) {
|
||||
this.parent.fireEvent("load", { detail: context });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,56 +2,63 @@ import { of, zip, Observable } from "rxjs";
|
||||
import { catchError, map, take, switchMap } from "rxjs/operators";
|
||||
|
||||
import { fetchRx, Context } from "./common";
|
||||
import { HyPushState } from './index';
|
||||
import { HyPushState } from "./index";
|
||||
|
||||
export interface ResponseContext extends Context {
|
||||
responseText: string | null;
|
||||
error?: any;
|
||||
};
|
||||
responseText: string | null;
|
||||
error?: any;
|
||||
}
|
||||
|
||||
export interface ResponseContextOk extends ResponseContext {
|
||||
responseText: string;
|
||||
};
|
||||
responseText: string;
|
||||
}
|
||||
|
||||
export interface ResponseContextErr extends ResponseContext {
|
||||
responseText: null;
|
||||
error: any;
|
||||
};
|
||||
responseText: null;
|
||||
error: any;
|
||||
}
|
||||
|
||||
export class FetchManager {
|
||||
private parent: HyPushState;
|
||||
private parent: HyPushState;
|
||||
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
fetchPage(context: Context): Observable<ResponseContext> {
|
||||
return fetchRx(context.url.href, {
|
||||
method: "GET",
|
||||
mode: 'cors', ///isExternal(this.parent) ? 'cors' : undefined,
|
||||
headers: { Accept: "text/html" },
|
||||
})
|
||||
.pipe(
|
||||
switchMap(response => response.text()),
|
||||
map(responseText => ({ ...context, responseText })),
|
||||
catchError(error => of({ ...context, error, responseText: null })),
|
||||
);
|
||||
}
|
||||
fetchPage(context: Context): Observable<ResponseContext> {
|
||||
return fetchRx(context.url.href, {
|
||||
method: "GET",
|
||||
mode: "cors", ///isExternal(this.parent) ? 'cors' : undefined,
|
||||
headers: { Accept: "text/html" },
|
||||
}).pipe(
|
||||
switchMap((response) => response.text()),
|
||||
map((responseText) => ({ ...context, responseText })),
|
||||
catchError((error) => of({ ...context, error, responseText: null })),
|
||||
);
|
||||
}
|
||||
|
||||
private selectPrefetch({ href }: URL, latestPrefetch: ResponseContext, prefetch$: Observable<ResponseContext>) {
|
||||
return href === latestPrefetch.url.href // && latestPrefetch.error == null
|
||||
? of(latestPrefetch)
|
||||
: prefetch$.pipe(take(1));
|
||||
}
|
||||
private selectPrefetch(
|
||||
{ href }: URL,
|
||||
latestPrefetch: ResponseContext,
|
||||
prefetch$: Observable<ResponseContext>,
|
||||
) {
|
||||
return href === latestPrefetch.url.href // && latestPrefetch.error == null
|
||||
? of(latestPrefetch)
|
||||
: prefetch$.pipe(take(1));
|
||||
}
|
||||
|
||||
// Returns an observable that emits exactly one notice, which contains the response.
|
||||
// It will not emit until an (optional) page transition animation completes.
|
||||
getResponse(prefetch$: Observable<ResponseContext>, context: Context, latestPrefetch: ResponseContext) {
|
||||
return zip(
|
||||
this.selectPrefetch(context.url, latestPrefetch, prefetch$),
|
||||
this.parent.animPromise,
|
||||
).pipe(
|
||||
map(([prefetch]) => ({ ...prefetch, ...context }) as ResponseContext),
|
||||
);
|
||||
}
|
||||
};
|
||||
// Returns an observable that emits exactly one notice, which contains the response.
|
||||
// It will not emit until an (optional) page transition animation completes.
|
||||
getResponse(
|
||||
prefetch$: Observable<ResponseContext>,
|
||||
context: Context,
|
||||
latestPrefetch: ResponseContext,
|
||||
) {
|
||||
return zip(
|
||||
this.selectPrefetch(context.url, latestPrefetch, prefetch$),
|
||||
this.parent.animPromise,
|
||||
).pipe(
|
||||
map(([prefetch]) => ({ ...prefetch, ...context }) as ResponseContext),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,80 +1,96 @@
|
||||
import { isExternal, getScrollTop, getScrollHeight, Cause, Context } from "./common";
|
||||
import {
|
||||
isExternal,
|
||||
getScrollTop,
|
||||
getScrollHeight,
|
||||
Cause,
|
||||
Context,
|
||||
} from "./common";
|
||||
|
||||
import { ReplaceContext } from "./update";
|
||||
|
||||
// @ts-ignore
|
||||
window.HashChangeEvent = window.HashChangeEvent || function HashChangeEvent(type, { oldURL = '', newURL = '' } = {}) {
|
||||
const e = new CustomEvent(type)
|
||||
// @ts-ignore
|
||||
e.oldURL = oldURL;
|
||||
// @ts-ignore
|
||||
e.newURL = newURL;
|
||||
return e;
|
||||
}
|
||||
window.HashChangeEvent =
|
||||
window.HashChangeEvent ||
|
||||
function HashChangeEvent(type, { oldURL = "", newURL = "" } = {}) {
|
||||
const e = new CustomEvent(type);
|
||||
// @ts-ignore
|
||||
e.oldURL = oldURL;
|
||||
// @ts-ignore
|
||||
e.newURL = newURL;
|
||||
return e;
|
||||
};
|
||||
|
||||
function simHashChange(newURL: URL, oldURL: URL) {
|
||||
if (newURL.hash !== oldURL.hash) {
|
||||
window.dispatchEvent(new HashChangeEvent('hashchange', { newURL: newURL.href, oldURL: oldURL.href }));
|
||||
}
|
||||
if (newURL.hash !== oldURL.hash) {
|
||||
window.dispatchEvent(
|
||||
new HashChangeEvent("hashchange", {
|
||||
newURL: newURL.href,
|
||||
oldURL: oldURL.href,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class HistoryManager {
|
||||
private parent: Location & { histId: string, simulateHashChange: boolean };
|
||||
private parent: Location & { histId: string; simulateHashChange: boolean };
|
||||
|
||||
constructor(parent: Location & { histId: string, simulateHashChange: boolean }) {
|
||||
this.parent = parent;
|
||||
}
|
||||
constructor(
|
||||
parent: Location & { histId: string; simulateHashChange: boolean },
|
||||
) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
updateHistoryState({ cause, replace, url, oldURL }: Context) {
|
||||
if (isExternal(this.parent)) return;
|
||||
updateHistoryState({ cause, replace, url, oldURL }: Context) {
|
||||
if (isExternal(this.parent)) return;
|
||||
|
||||
switch (cause) {
|
||||
case Cause.Init:
|
||||
case Cause.Push: {
|
||||
const { histId } = this.parent;
|
||||
switch (cause) {
|
||||
case Cause.Init:
|
||||
case Cause.Push: {
|
||||
const { histId } = this.parent;
|
||||
|
||||
if (replace || url.href === location.href) {
|
||||
const state = { ...history.state, [histId]: {} };
|
||||
history.replaceState(state, document.title, url.href);
|
||||
} else {
|
||||
history.pushState({ [histId]: {} }, document.title, url.href);
|
||||
}
|
||||
// no break
|
||||
}
|
||||
case Cause.Pop: {
|
||||
if (this.parent.simulateHashChange && oldURL) simHashChange(url, oldURL);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// if (process.env.DEBUG) console.warn(`Type '${cause}' not reconginzed`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (replace || url.href === location.href) {
|
||||
const state = { ...history.state, [histId]: {} };
|
||||
history.replaceState(state, document.title, url.href);
|
||||
} else {
|
||||
history.pushState({ [histId]: {} }, document.title, url.href);
|
||||
}
|
||||
// no break
|
||||
}
|
||||
case Cause.Pop: {
|
||||
if (this.parent.simulateHashChange && oldURL)
|
||||
simHashChange(url, oldURL);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// if (process.env.DEBUG) console.warn(`Type '${cause}' not reconginzed`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateTitle({ cause, title }: ReplaceContext) {
|
||||
document.title = title;
|
||||
if (!isExternal(this.parent) && cause === Cause.Push) {
|
||||
history.replaceState(history.state, title);
|
||||
}
|
||||
}
|
||||
updateTitle({ cause, title }: ReplaceContext) {
|
||||
document.title = title;
|
||||
if (!isExternal(this.parent) && cause === Cause.Push) {
|
||||
history.replaceState(history.state, title);
|
||||
}
|
||||
}
|
||||
|
||||
updateHistoryScrollPosition = () => {
|
||||
if (isExternal(this.parent)) return;
|
||||
updateHistoryScrollPosition = () => {
|
||||
if (isExternal(this.parent)) return;
|
||||
|
||||
const state = this.assignScrollPosition(history.state || {});
|
||||
history.replaceState(state, document.title);
|
||||
}
|
||||
const state = this.assignScrollPosition(history.state || {});
|
||||
history.replaceState(state, document.title);
|
||||
};
|
||||
|
||||
private assignScrollPosition(state: any) {
|
||||
const { histId } = this.parent;
|
||||
return {
|
||||
...state,
|
||||
[histId]: {
|
||||
...state[histId],
|
||||
scrollTop: getScrollTop(),
|
||||
scrollHeight: getScrollHeight(),
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
private assignScrollPosition(state: any) {
|
||||
const { histId } = this.parent;
|
||||
return {
|
||||
...state,
|
||||
[histId]: {
|
||||
...state[histId],
|
||||
scrollTop: getScrollTop(),
|
||||
scrollHeight: getScrollHeight(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,366 +17,424 @@
|
||||
* @license
|
||||
* @nocompile
|
||||
*/
|
||||
import { property, customElement } from 'lit/decorators.js';
|
||||
|
||||
import { Observable, Subject, BehaviorSubject, merge, defer, fromEvent, animationFrameScheduler } from 'rxjs';
|
||||
import {
|
||||
map,
|
||||
filter,
|
||||
tap,
|
||||
takeUntil,
|
||||
startWith,
|
||||
pairwise,
|
||||
share,
|
||||
mapTo,
|
||||
switchMap,
|
||||
distinctUntilChanged,
|
||||
withLatestFrom,
|
||||
catchError,
|
||||
observeOn,
|
||||
} from 'rxjs/operators';
|
||||
|
||||
import { RxLitElement, createResolvablePromise, matchesAncestors } from '@hydecorp/component';
|
||||
import { property, customElement } from "lit/decorators.js";
|
||||
|
||||
import {
|
||||
applyMixins,
|
||||
Context,
|
||||
Cause,
|
||||
ClickContext,
|
||||
isPushEvent,
|
||||
isHashChange,
|
||||
isHintEvent,
|
||||
filterWhen,
|
||||
isExternal,
|
||||
} from './common';
|
||||
Observable,
|
||||
Subject,
|
||||
BehaviorSubject,
|
||||
merge,
|
||||
defer,
|
||||
fromEvent,
|
||||
animationFrameScheduler,
|
||||
} from "rxjs";
|
||||
import {
|
||||
map,
|
||||
filter,
|
||||
tap,
|
||||
takeUntil,
|
||||
startWith,
|
||||
pairwise,
|
||||
share,
|
||||
mapTo,
|
||||
switchMap,
|
||||
distinctUntilChanged,
|
||||
withLatestFrom,
|
||||
catchError,
|
||||
observeOn,
|
||||
} from "rxjs/operators";
|
||||
|
||||
import { FetchManager, ResponseContext, ResponseContextErr, ResponseContextOk } from './fetch';
|
||||
import { UpdateManager } from './update';
|
||||
import { EventListenersMixin } from './event-listeners';
|
||||
import { EventManager } from './event';
|
||||
import { HistoryManager } from './history';
|
||||
import { ScrollManager } from './scroll';
|
||||
import {
|
||||
RxLitElement,
|
||||
createResolvablePromise,
|
||||
matchesAncestors,
|
||||
} from "@hydecorp/component";
|
||||
|
||||
import {
|
||||
applyMixins,
|
||||
Context,
|
||||
Cause,
|
||||
ClickContext,
|
||||
isPushEvent,
|
||||
isHashChange,
|
||||
isHintEvent,
|
||||
filterWhen,
|
||||
isExternal,
|
||||
} from "./common";
|
||||
|
||||
import {
|
||||
FetchManager,
|
||||
ResponseContext,
|
||||
ResponseContextErr,
|
||||
ResponseContextOk,
|
||||
} from "./fetch";
|
||||
import { UpdateManager } from "./update";
|
||||
import { EventListenersMixin } from "./event-listeners";
|
||||
import { EventManager } from "./event";
|
||||
import { HistoryManager } from "./history";
|
||||
import { ScrollManager } from "./scroll";
|
||||
|
||||
function compareContext(p: Context, q: Context) {
|
||||
return p.url.href === q.url.href && p.error === q.error && p.cacheNr === q.cacheNr;
|
||||
return (
|
||||
p.url.href === q.url.href && p.error === q.error && p.cacheNr === q.cacheNr
|
||||
);
|
||||
}
|
||||
|
||||
@customElement('hy-push-state')
|
||||
@customElement("hy-push-state")
|
||||
export class HyPushState
|
||||
extends applyMixins(RxLitElement, [EventListenersMixin])
|
||||
implements Location, EventListenersMixin
|
||||
extends applyMixins(RxLitElement, [EventListenersMixin])
|
||||
implements Location, EventListenersMixin
|
||||
{
|
||||
el: HTMLElement = this;
|
||||
el: HTMLElement = this;
|
||||
|
||||
createRenderRoot() {
|
||||
return this;
|
||||
}
|
||||
createRenderRoot() {
|
||||
return this;
|
||||
}
|
||||
|
||||
@property({ type: String, reflect: true, attribute: 'replace-selector' }) replaceSelector?: string;
|
||||
@property({ type: String, reflect: true, attribute: 'link-selector' }) linkSelector: string =
|
||||
'a[href]:not([data-no-push])';
|
||||
@property({ type: String, reflect: true, attribute: 'script-selector' }) scriptSelector?: string;
|
||||
@property({ type: Boolean, reflect: true }) prefetch: boolean = false;
|
||||
@property({ type: Number, reflect: true }) duration: number = 0;
|
||||
// @property({ type: Boolean, reflect: true, attribute: 'simulate-load' }) simulateLoad: boolean = false;
|
||||
@property({ type: Boolean, reflect: true, attribute: 'hashchange' }) simulateHashChange: boolean = false;
|
||||
@property({ type: String, reflect: true, attribute: "replace-selector" })
|
||||
replaceSelector?: string;
|
||||
@property({ type: String, reflect: true, attribute: "link-selector" })
|
||||
linkSelector: string = "a[href]:not([data-no-push])";
|
||||
@property({ type: String, reflect: true, attribute: "script-selector" })
|
||||
scriptSelector?: string;
|
||||
@property({ type: Boolean, reflect: true }) prefetch: boolean = false;
|
||||
@property({ type: Number, reflect: true }) duration: number = 0;
|
||||
// @property({ type: Boolean, reflect: true, attribute: 'simulate-load' }) simulateLoad: boolean = false;
|
||||
@property({ type: Boolean, reflect: true, attribute: "hashchange" })
|
||||
simulateHashChange: boolean = false;
|
||||
|
||||
@property({ type: String }) baseURL: string = window.location.href;
|
||||
@property({ type: String }) baseURL: string = window.location.href;
|
||||
|
||||
#initialized = createResolvablePromise();
|
||||
get initialized() {
|
||||
return this.#initialized;
|
||||
}
|
||||
#initialized = createResolvablePromise();
|
||||
get initialized() {
|
||||
return this.#initialized;
|
||||
}
|
||||
|
||||
$!: {
|
||||
linkSelector: Subject<string>;
|
||||
prefetch: Subject<boolean>;
|
||||
};
|
||||
$!: {
|
||||
linkSelector: Subject<string>;
|
||||
prefetch: Subject<boolean>;
|
||||
};
|
||||
|
||||
animPromise: Promise<any> = Promise.resolve(null);
|
||||
fadePromise: Promise<any> = Promise.resolve(null);
|
||||
animPromise: Promise<any> = Promise.resolve(null);
|
||||
fadePromise: Promise<any> = Promise.resolve(null);
|
||||
|
||||
#scrollManager = new ScrollManager(this);
|
||||
#historyManager = new HistoryManager(this);
|
||||
#fetchManager = new FetchManager(this);
|
||||
#updateManager = new UpdateManager(this);
|
||||
#eventManager = new EventManager(this);
|
||||
#scrollManager = new ScrollManager(this);
|
||||
#historyManager = new HistoryManager(this);
|
||||
#fetchManager = new FetchManager(this);
|
||||
#updateManager = new UpdateManager(this);
|
||||
#eventManager = new EventManager(this);
|
||||
|
||||
#url = new URL(this.baseURL);
|
||||
#url = new URL(this.baseURL);
|
||||
|
||||
#setLocation = (
|
||||
key: 'hash' | 'host' | 'hostname' | 'href' | 'pathname' | 'port' | 'protocol' | 'search',
|
||||
value: string,
|
||||
) => {
|
||||
const u = new URL(this.#url.href);
|
||||
u[key] = value;
|
||||
this.assign(u.href);
|
||||
};
|
||||
#setLocation = (
|
||||
key:
|
||||
| "hash"
|
||||
| "host"
|
||||
| "hostname"
|
||||
| "href"
|
||||
| "pathname"
|
||||
| "port"
|
||||
| "protocol"
|
||||
| "search",
|
||||
value: string,
|
||||
) => {
|
||||
const u = new URL(this.#url.href);
|
||||
u[key] = value;
|
||||
this.assign(u.href);
|
||||
};
|
||||
|
||||
// Implement Location
|
||||
get hash() {
|
||||
return this.#url.hash;
|
||||
}
|
||||
get host() {
|
||||
return this.#url.host;
|
||||
}
|
||||
get hostname() {
|
||||
return this.#url.hostname;
|
||||
}
|
||||
get href() {
|
||||
return this.#url.href;
|
||||
}
|
||||
get pathname() {
|
||||
return this.#url.pathname;
|
||||
}
|
||||
get port() {
|
||||
return this.#url.port;
|
||||
}
|
||||
get protocol() {
|
||||
return this.#url.protocol;
|
||||
}
|
||||
get search() {
|
||||
return this.#url.search;
|
||||
}
|
||||
get origin() {
|
||||
return this.#url.origin;
|
||||
}
|
||||
get ancestorOrigins() {
|
||||
return window.location.ancestorOrigins;
|
||||
}
|
||||
// Implement Location
|
||||
get hash() {
|
||||
return this.#url.hash;
|
||||
}
|
||||
get host() {
|
||||
return this.#url.host;
|
||||
}
|
||||
get hostname() {
|
||||
return this.#url.hostname;
|
||||
}
|
||||
get href() {
|
||||
return this.#url.href;
|
||||
}
|
||||
get pathname() {
|
||||
return this.#url.pathname;
|
||||
}
|
||||
get port() {
|
||||
return this.#url.port;
|
||||
}
|
||||
get protocol() {
|
||||
return this.#url.protocol;
|
||||
}
|
||||
get search() {
|
||||
return this.#url.search;
|
||||
}
|
||||
get origin() {
|
||||
return this.#url.origin;
|
||||
}
|
||||
get ancestorOrigins() {
|
||||
return window.location.ancestorOrigins;
|
||||
}
|
||||
|
||||
set hash(value) {
|
||||
this.#setLocation('hash', value);
|
||||
}
|
||||
set host(value) {
|
||||
this.#setLocation('host', value);
|
||||
}
|
||||
set hostname(value) {
|
||||
this.#setLocation('hostname', value);
|
||||
}
|
||||
set href(value) {
|
||||
this.#setLocation('href', value);
|
||||
}
|
||||
set pathname(value) {
|
||||
this.#setLocation('pathname', value);
|
||||
}
|
||||
set port(value) {
|
||||
this.#setLocation('port', value);
|
||||
}
|
||||
set protocol(value) {
|
||||
this.#setLocation('protocol', value);
|
||||
}
|
||||
set search(value) {
|
||||
this.#setLocation('search', value);
|
||||
}
|
||||
set hash(value) {
|
||||
this.#setLocation("hash", value);
|
||||
}
|
||||
set host(value) {
|
||||
this.#setLocation("host", value);
|
||||
}
|
||||
set hostname(value) {
|
||||
this.#setLocation("hostname", value);
|
||||
}
|
||||
set href(value) {
|
||||
this.#setLocation("href", value);
|
||||
}
|
||||
set pathname(value) {
|
||||
this.#setLocation("pathname", value);
|
||||
}
|
||||
set port(value) {
|
||||
this.#setLocation("port", value);
|
||||
}
|
||||
set protocol(value) {
|
||||
this.#setLocation("protocol", value);
|
||||
}
|
||||
set search(value) {
|
||||
this.#setLocation("search", value);
|
||||
}
|
||||
|
||||
// EventListenersMixin
|
||||
setupEventListeners!: () => {
|
||||
pushEvent$: Observable<[MouseEvent, HTMLAnchorElement]>;
|
||||
hintEvent$: Observable<[Event, HTMLAnchorElement]>;
|
||||
};
|
||||
// EventListenersMixin
|
||||
setupEventListeners!: () => {
|
||||
pushEvent$: Observable<[MouseEvent, HTMLAnchorElement]>;
|
||||
hintEvent$: Observable<[Event, HTMLAnchorElement]>;
|
||||
};
|
||||
|
||||
#cacheNr = 0;
|
||||
#cacheNr = 0;
|
||||
|
||||
get histId() {
|
||||
return this.id || this.tagName;
|
||||
}
|
||||
get histId() {
|
||||
return this.id || this.tagName;
|
||||
}
|
||||
|
||||
#reload$ = new Subject<Context>();
|
||||
#reload$ = new Subject<Context>();
|
||||
|
||||
@property()
|
||||
assign(url: string) {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(url, this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
});
|
||||
}
|
||||
@property()
|
||||
assign(url: string) {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(url, this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
});
|
||||
}
|
||||
|
||||
@property()
|
||||
reload() {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
@property()
|
||||
reload() {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
|
||||
@property()
|
||||
replace(url: string) {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(url, this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
@property()
|
||||
replace(url: string) {
|
||||
this.#reload$.next({
|
||||
cause: Cause.Push,
|
||||
url: new URL(url, this.href),
|
||||
cacheNr: ++this.#cacheNr,
|
||||
replace: true,
|
||||
});
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
|
||||
this.$ = {
|
||||
linkSelector: new BehaviorSubject(this.linkSelector),
|
||||
prefetch: new BehaviorSubject(this.prefetch),
|
||||
};
|
||||
this.$ = {
|
||||
linkSelector: new BehaviorSubject(this.linkSelector),
|
||||
prefetch: new BehaviorSubject(this.prefetch),
|
||||
};
|
||||
|
||||
// Remember the current scroll position (for F5/reloads).
|
||||
window.addEventListener('beforeunload', this.#historyManager.updateHistoryScrollPosition);
|
||||
// Remember the current scroll position (for F5/reloads).
|
||||
window.addEventListener(
|
||||
"beforeunload",
|
||||
this.#historyManager.updateHistoryScrollPosition,
|
||||
);
|
||||
|
||||
// Remember scroll position for backward/forward navigation cache.
|
||||
// Technically, this is only necessary for Safari, because other browsers will not use the BFN cache
|
||||
// when a beforeunload event is registered...
|
||||
document.documentElement.addEventListener('click', this.#updateHistoryScrollPosition);
|
||||
// Remember scroll position for backward/forward navigation cache.
|
||||
// Technically, this is only necessary for Safari, because other browsers will not use the BFN cache
|
||||
// when a beforeunload event is registered...
|
||||
document.documentElement.addEventListener(
|
||||
"click",
|
||||
this.#updateHistoryScrollPosition,
|
||||
);
|
||||
|
||||
this.updateComplete.then(this.#upgrade);
|
||||
}
|
||||
this.updateComplete.then(this.#upgrade);
|
||||
}
|
||||
|
||||
#updateHistoryScrollPosition = (event: MouseEvent) => {
|
||||
const anchor = matchesAncestors(event.target as Element, 'a[href]') as HTMLAnchorElement | null;
|
||||
if (isExternal(anchor)) {
|
||||
this.#historyManager.updateHistoryScrollPosition();
|
||||
}
|
||||
};
|
||||
#updateHistoryScrollPosition = (event: MouseEvent) => {
|
||||
const anchor = matchesAncestors(
|
||||
event.target as Element,
|
||||
"a[href]",
|
||||
) as HTMLAnchorElement | null;
|
||||
if (isExternal(anchor)) {
|
||||
this.#historyManager.updateHistoryScrollPosition();
|
||||
}
|
||||
};
|
||||
|
||||
#response$!: Observable<ResponseContext>;
|
||||
#response$!: Observable<ResponseContext>;
|
||||
|
||||
#upgrade = () => {
|
||||
const { pushEvent$, hintEvent$ } = this.setupEventListeners();
|
||||
#upgrade = () => {
|
||||
const { pushEvent$, hintEvent$ } = this.setupEventListeners();
|
||||
|
||||
const push$: Observable<ClickContext> = pushEvent$.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
map(([event, anchor]) => ({
|
||||
cause: Cause.Push,
|
||||
url: new URL(anchor.href, this.href),
|
||||
anchor,
|
||||
event,
|
||||
cacheNr: this.#cacheNr,
|
||||
})),
|
||||
filter((x) => isPushEvent(x, this)),
|
||||
tap(({ event }) => {
|
||||
event.preventDefault();
|
||||
this.#historyManager.updateHistoryScrollPosition();
|
||||
}),
|
||||
);
|
||||
const push$: Observable<ClickContext> = pushEvent$.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
map(([event, anchor]) => ({
|
||||
cause: Cause.Push,
|
||||
url: new URL(anchor.href, this.href),
|
||||
anchor,
|
||||
event,
|
||||
cacheNr: this.#cacheNr,
|
||||
})),
|
||||
filter((x) => isPushEvent(x, this)),
|
||||
tap(({ event }) => {
|
||||
event.preventDefault();
|
||||
this.#historyManager.updateHistoryScrollPosition();
|
||||
}),
|
||||
);
|
||||
|
||||
const pop$: Observable<Context> = fromEvent(window, 'popstate').pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filter(() => window.history.state && window.history.state[this.histId]),
|
||||
map((event) => ({
|
||||
cause: Cause.Pop,
|
||||
url: new URL(window.location.href),
|
||||
cacheNr: this.#cacheNr,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
const pop$: Observable<Context> = fromEvent(window, "popstate").pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filter(() => window.history.state && window.history.state[this.histId]),
|
||||
map((event) => ({
|
||||
cause: Cause.Pop,
|
||||
url: new URL(window.location.href),
|
||||
cacheNr: this.#cacheNr,
|
||||
event,
|
||||
})),
|
||||
);
|
||||
|
||||
const reload$ = this.#reload$; // .pipe(takeUntil(this.subjects.disconnect));
|
||||
const reload$ = this.#reload$; // .pipe(takeUntil(this.subjects.disconnect));
|
||||
|
||||
const merged$: Observable<Context> = merge(push$, pop$, reload$).pipe(
|
||||
startWith({ url: new URL(window.location.href) } as Context),
|
||||
pairwise(),
|
||||
map(([old, current]) => Object.assign(current, { oldURL: old.url })),
|
||||
share(),
|
||||
);
|
||||
const merged$: Observable<Context> = merge(push$, pop$, reload$).pipe(
|
||||
startWith({ url: new URL(window.location.href) } as Context),
|
||||
pairwise(),
|
||||
map(([old, current]) => Object.assign(current, { oldURL: old.url })),
|
||||
share(),
|
||||
);
|
||||
|
||||
const page$ = merged$.pipe(
|
||||
filter((p) => !isHashChange(p)),
|
||||
share(),
|
||||
);
|
||||
const page$ = merged$.pipe(
|
||||
filter((p) => !isHashChange(p)),
|
||||
share(),
|
||||
);
|
||||
|
||||
const hash$ = merged$.pipe(
|
||||
filter((p) => isHashChange(p)),
|
||||
filter(() => history.state && history.state[this.histId]),
|
||||
observeOn<Context>(animationFrameScheduler),
|
||||
tap((context) => {
|
||||
this.#historyManager.updateHistoryState(context);
|
||||
this.#scrollManager.manageScrollPosition(context);
|
||||
}),
|
||||
);
|
||||
const hash$ = merged$.pipe(
|
||||
filter((p) => isHashChange(p)),
|
||||
filter(() => history.state && history.state[this.histId]),
|
||||
observeOn<Context>(animationFrameScheduler),
|
||||
tap((context) => {
|
||||
this.#historyManager.updateHistoryState(context);
|
||||
this.#scrollManager.manageScrollPosition(context);
|
||||
}),
|
||||
);
|
||||
|
||||
const pauser$ = defer(() => merge(page$.pipe(mapTo(true)), this.#response$.pipe(mapTo(false)))).pipe(
|
||||
startWith(false),
|
||||
);
|
||||
const pauser$ = defer(() =>
|
||||
merge(page$.pipe(mapTo(true)), this.#response$.pipe(mapTo(false))),
|
||||
).pipe(startWith(false));
|
||||
|
||||
const hint$: Observable<Context> = hintEvent$.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(pauser$.pipe(map((x) => !x))),
|
||||
map(([event, anchor]) => ({
|
||||
cause: Cause.Hint,
|
||||
url: new URL(anchor.href, this.href),
|
||||
anchor,
|
||||
event,
|
||||
cacheNr: this.#cacheNr,
|
||||
})),
|
||||
filter((x) => isHintEvent(x, this)),
|
||||
);
|
||||
const hint$: Observable<Context> = hintEvent$.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(pauser$.pipe(map((x) => !x))),
|
||||
map(([event, anchor]) => ({
|
||||
cause: Cause.Hint,
|
||||
url: new URL(anchor.href, this.href),
|
||||
anchor,
|
||||
event,
|
||||
cacheNr: this.#cacheNr,
|
||||
})),
|
||||
filter((x) => isHintEvent(x, this)),
|
||||
);
|
||||
|
||||
const prefetchResponse$ = merge(hint$, page$).pipe(
|
||||
distinctUntilChanged((x, y) => compareContext(x, y)),
|
||||
switchMap((x) => this.#fetchManager.fetchPage(x)),
|
||||
startWith({ url: {} } as ResponseContext),
|
||||
share(),
|
||||
);
|
||||
const prefetchResponse$ = merge(hint$, page$).pipe(
|
||||
distinctUntilChanged((x, y) => compareContext(x, y)),
|
||||
switchMap((x) => this.#fetchManager.fetchPage(x)),
|
||||
startWith({ url: {} } as ResponseContext),
|
||||
share(),
|
||||
);
|
||||
|
||||
const response$ = (this.#response$ = page$.pipe(
|
||||
tap((context) => {
|
||||
this.#eventManager.onStart(context);
|
||||
this.#historyManager.updateHistoryState(context);
|
||||
this.#url = context.url;
|
||||
}),
|
||||
withLatestFrom(prefetchResponse$),
|
||||
switchMap((args) => this.#fetchManager.getResponse(prefetchResponse$, ...args)),
|
||||
share(),
|
||||
));
|
||||
const response$ = (this.#response$ = page$.pipe(
|
||||
tap((context) => {
|
||||
this.#eventManager.onStart(context);
|
||||
this.#historyManager.updateHistoryState(context);
|
||||
this.#url = context.url;
|
||||
}),
|
||||
withLatestFrom(prefetchResponse$),
|
||||
switchMap((args) =>
|
||||
this.#fetchManager.getResponse(prefetchResponse$, ...args),
|
||||
),
|
||||
share(),
|
||||
));
|
||||
|
||||
const responseOk$ = response$.pipe(filter((ctx): ctx is ResponseContextOk => !ctx.error));
|
||||
const responseErr$ = response$.pipe(filter((ctx): ctx is ResponseContextErr => !!ctx.error));
|
||||
const responseOk$ = response$.pipe(
|
||||
filter((ctx): ctx is ResponseContextOk => !ctx.error),
|
||||
);
|
||||
const responseErr$ = response$.pipe(
|
||||
filter((ctx): ctx is ResponseContextErr => !!ctx.error),
|
||||
);
|
||||
|
||||
const main$ = responseOk$.pipe(
|
||||
map((context) => this.#updateManager.responseToContent(context)),
|
||||
tap((context) => this.#eventManager.emitReady(context)),
|
||||
observeOn(animationFrameScheduler),
|
||||
tap((context) => {
|
||||
this.#updateManager.updateDOM(context);
|
||||
this.#historyManager.updateTitle(context);
|
||||
this.#eventManager.emitAfter(context);
|
||||
}),
|
||||
startWith({
|
||||
cause: Cause.Init,
|
||||
url: this.#url,
|
||||
scripts: [],
|
||||
}),
|
||||
observeOn(animationFrameScheduler),
|
||||
tap((context) => this.#scrollManager.manageScrollPosition(context)),
|
||||
tap({ error: (e) => this.#eventManager.emitDOMError(e) }),
|
||||
catchError((_, c) => c),
|
||||
switchMap((x) => this.fadePromise.then(() => x)),
|
||||
switchMap((x) => this.#updateManager.reinsertScriptTags(x)),
|
||||
tap({ error: (e) => this.#eventManager.emitError(e) }),
|
||||
catchError((_, c) => c),
|
||||
tap((context) => this.#eventManager.emitLoad(context)),
|
||||
);
|
||||
const main$ = responseOk$.pipe(
|
||||
map((context) => this.#updateManager.responseToContent(context)),
|
||||
tap((context) => this.#eventManager.emitReady(context)),
|
||||
observeOn(animationFrameScheduler),
|
||||
tap((context) => {
|
||||
this.#updateManager.updateDOM(context);
|
||||
this.#historyManager.updateTitle(context);
|
||||
this.#eventManager.emitAfter(context);
|
||||
}),
|
||||
startWith({
|
||||
cause: Cause.Init,
|
||||
url: this.#url,
|
||||
scripts: [],
|
||||
}),
|
||||
observeOn(animationFrameScheduler),
|
||||
tap((context) => this.#scrollManager.manageScrollPosition(context)),
|
||||
tap({ error: (e) => this.#eventManager.emitDOMError(e) }),
|
||||
catchError((_, c) => c),
|
||||
switchMap((x) => this.fadePromise.then(() => x)),
|
||||
switchMap((x) => this.#updateManager.reinsertScriptTags(x)),
|
||||
tap({ error: (e) => this.#eventManager.emitError(e) }),
|
||||
catchError((_, c) => c),
|
||||
tap((context) => this.#eventManager.emitLoad(context)),
|
||||
);
|
||||
|
||||
const error$ = responseErr$.pipe(tap((e) => this.#eventManager.emitNetworkError(e)));
|
||||
const error$ = responseErr$.pipe(
|
||||
tap((e) => this.#eventManager.emitNetworkError(e)),
|
||||
);
|
||||
|
||||
const progress$ = page$.pipe(
|
||||
switchMap((context) => defer(() => this.animPromise).pipe(takeUntil(response$), mapTo(context))),
|
||||
tap((context) => this.#eventManager.emitProgress(context)),
|
||||
);
|
||||
const progress$ = page$.pipe(
|
||||
switchMap((context) =>
|
||||
defer(() => this.animPromise).pipe(
|
||||
takeUntil(response$),
|
||||
mapTo(context),
|
||||
),
|
||||
),
|
||||
tap((context) => this.#eventManager.emitProgress(context)),
|
||||
);
|
||||
|
||||
// Subscriptions
|
||||
main$.subscribe();
|
||||
hash$.subscribe();
|
||||
error$.subscribe();
|
||||
progress$.subscribe();
|
||||
// Subscriptions
|
||||
main$.subscribe();
|
||||
hash$.subscribe();
|
||||
error$.subscribe();
|
||||
progress$.subscribe();
|
||||
|
||||
this.#initialized.resolve(this);
|
||||
this.fireEvent('init');
|
||||
};
|
||||
this.#initialized.resolve(this);
|
||||
this.fireEvent("init");
|
||||
};
|
||||
|
||||
disconnectedCallback() {
|
||||
window.removeEventListener('beforeunload', this.#historyManager.updateHistoryScrollPosition);
|
||||
document.documentElement.removeEventListener('click', this.#updateHistoryScrollPosition);
|
||||
}
|
||||
disconnectedCallback() {
|
||||
window.removeEventListener(
|
||||
"beforeunload",
|
||||
this.#historyManager.updateHistoryScrollPosition,
|
||||
);
|
||||
document.documentElement.removeEventListener(
|
||||
"click",
|
||||
this.#updateHistoryScrollPosition,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,80 +2,94 @@
|
||||
// relative URLs will be resolved relative to the current `window.location`.
|
||||
// We can rewrite URL to absolute urls
|
||||
export function rewriteURLs(replaceEls: (Element | null)[], base: string) {
|
||||
replaceEls.forEach((el) => {
|
||||
if (!el) return;
|
||||
el.querySelectorAll("[href]").forEach(rewriteURL("href", base));
|
||||
el.querySelectorAll("[src]").forEach(rewriteURL("src", base));
|
||||
el.querySelectorAll("img[srcset]").forEach(rewriteURLSrcSet("srcset", base));
|
||||
el.querySelectorAll("blockquote[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("del[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("ins[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("q[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("img[longdesc]").forEach(rewriteURL("longdesc", base));
|
||||
el.querySelectorAll("frame[longdesc]").forEach(rewriteURL("longdesc", base));
|
||||
el.querySelectorAll("iframe[longdesc]").forEach(rewriteURL("longdesc", base));
|
||||
el.querySelectorAll("img[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("input[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("object[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("form[action]").forEach(rewriteURL("action", base));
|
||||
el.querySelectorAll("button[formaction]").forEach(rewriteURL("formaction", base));
|
||||
el.querySelectorAll("input[formaction]").forEach(rewriteURL("formaction", base));
|
||||
el.querySelectorAll("video[poster]").forEach(rewriteURL("poster", base));
|
||||
el.querySelectorAll("object[data]").forEach(rewriteURL("data", base));
|
||||
el.querySelectorAll("object[codebase]").forEach(rewriteURL("codebase", base));
|
||||
el.querySelectorAll("object[archive]").forEach(rewriteURLList("archive", base));
|
||||
/* el.querySelectorAll("command[icon]").forEach(this.rewriteURL("icon")); */ // obsolte
|
||||
});
|
||||
replaceEls.forEach((el) => {
|
||||
if (!el) return;
|
||||
el.querySelectorAll("[href]").forEach(rewriteURL("href", base));
|
||||
el.querySelectorAll("[src]").forEach(rewriteURL("src", base));
|
||||
el.querySelectorAll("img[srcset]").forEach(
|
||||
rewriteURLSrcSet("srcset", base),
|
||||
);
|
||||
el.querySelectorAll("blockquote[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("del[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("ins[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("q[cite]").forEach(rewriteURL("cite", base));
|
||||
el.querySelectorAll("img[longdesc]").forEach(rewriteURL("longdesc", base));
|
||||
el.querySelectorAll("frame[longdesc]").forEach(
|
||||
rewriteURL("longdesc", base),
|
||||
);
|
||||
el.querySelectorAll("iframe[longdesc]").forEach(
|
||||
rewriteURL("longdesc", base),
|
||||
);
|
||||
el.querySelectorAll("img[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("input[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("object[usemap]").forEach(rewriteURL("usemap", base));
|
||||
el.querySelectorAll("form[action]").forEach(rewriteURL("action", base));
|
||||
el.querySelectorAll("button[formaction]").forEach(
|
||||
rewriteURL("formaction", base),
|
||||
);
|
||||
el.querySelectorAll("input[formaction]").forEach(
|
||||
rewriteURL("formaction", base),
|
||||
);
|
||||
el.querySelectorAll("video[poster]").forEach(rewriteURL("poster", base));
|
||||
el.querySelectorAll("object[data]").forEach(rewriteURL("data", base));
|
||||
el.querySelectorAll("object[codebase]").forEach(
|
||||
rewriteURL("codebase", base),
|
||||
);
|
||||
el.querySelectorAll("object[archive]").forEach(
|
||||
rewriteURLList("archive", base),
|
||||
);
|
||||
/* el.querySelectorAll("command[icon]").forEach(this.rewriteURL("icon")); */ // obsolte
|
||||
});
|
||||
}
|
||||
|
||||
function rewriteURL(attr: string, base: string) {
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(attr, new URL(attrVal, base).href);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URL in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(attr, new URL(attrVal, base).href);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URL in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function rewriteURLSrcSet(attr: string, base: string) {
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(
|
||||
attr,
|
||||
attrVal
|
||||
.split(/\s*,\s*/)
|
||||
.map(str => {
|
||||
const pair = str.split(/\s+/);
|
||||
pair[0] = new URL(pair[0], base).href;
|
||||
return pair.join(" ");
|
||||
})
|
||||
.join(", ")
|
||||
);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URLs in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(
|
||||
attr,
|
||||
attrVal
|
||||
.split(/\s*,\s*/)
|
||||
.map((str) => {
|
||||
const pair = str.split(/\s+/);
|
||||
pair[0] = new URL(pair[0], base).href;
|
||||
return pair.join(" ");
|
||||
})
|
||||
.join(", "),
|
||||
);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URLs in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function rewriteURLList(attr: string, base: string) {
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(
|
||||
attr,
|
||||
attrVal
|
||||
.split(/[\s,]+/)
|
||||
.map(str => new URL(str, base).href)
|
||||
.join(", ")
|
||||
);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URLs in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
}
|
||||
return (el: Element) => {
|
||||
try {
|
||||
const attrVal = el.getAttribute(attr);
|
||||
if (attrVal == null) return;
|
||||
el.setAttribute(
|
||||
attr,
|
||||
attrVal
|
||||
.split(/[\s,]+/)
|
||||
.map((str) => new URL(str, base).href)
|
||||
.join(", "),
|
||||
);
|
||||
} catch (e) {
|
||||
// if (process.env.DEBUG) console.warn(`Couldn't rewrite URLs in attribute ${attr} on element`, el);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,71 +4,86 @@ import { concatMap, catchError, finalize, mapTo } from "rxjs/operators";
|
||||
import { HyPushState } from ".";
|
||||
|
||||
function cloneScript(script: HTMLScriptElement) {
|
||||
const newScript = document.createElement('script');
|
||||
Array.from(script.attributes).forEach(attr => newScript.setAttributeNode(attr.cloneNode() as Attr));
|
||||
newScript.innerHTML = script.innerHTML;
|
||||
return newScript;
|
||||
const newScript = document.createElement("script");
|
||||
Array.from(script.attributes).forEach((attr) =>
|
||||
newScript.setAttributeNode(attr.cloneNode() as Attr),
|
||||
);
|
||||
newScript.innerHTML = script.innerHTML;
|
||||
return newScript;
|
||||
}
|
||||
|
||||
export class ScriptManager {
|
||||
private parent: HyPushState;
|
||||
private parent: HyPushState;
|
||||
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
get scriptSelector() { return this.parent.scriptSelector }
|
||||
get scriptSelector() {
|
||||
return this.parent.scriptSelector;
|
||||
}
|
||||
|
||||
removeScriptTags(replaceEls: (Element|null)[]) {
|
||||
const scripts: Array<[HTMLScriptElement, HTMLScriptElement]> = [];
|
||||
removeScriptTags(replaceEls: (Element | null)[]) {
|
||||
const scripts: Array<[HTMLScriptElement, HTMLScriptElement]> = [];
|
||||
|
||||
replaceEls.forEach(el => {
|
||||
if (el && this.scriptSelector) {
|
||||
el.querySelectorAll(this.scriptSelector).forEach((script) => {
|
||||
if (script instanceof HTMLScriptElement) {
|
||||
const newScript = cloneScript(script);
|
||||
const pair: [HTMLScriptElement, HTMLScriptElement] = [newScript, script];
|
||||
scripts.push(pair);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
replaceEls.forEach((el) => {
|
||||
if (el && this.scriptSelector) {
|
||||
el.querySelectorAll(this.scriptSelector).forEach((script) => {
|
||||
if (script instanceof HTMLScriptElement) {
|
||||
const newScript = cloneScript(script);
|
||||
const pair: [HTMLScriptElement, HTMLScriptElement] = [
|
||||
newScript,
|
||||
script,
|
||||
];
|
||||
scripts.push(pair);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return scripts;
|
||||
}
|
||||
return scripts;
|
||||
}
|
||||
|
||||
reinsertScriptTags(context: { scripts: Array<[HTMLScriptElement, HTMLScriptElement]> }) {
|
||||
if (!this.scriptSelector) return Promise.resolve(context);
|
||||
reinsertScriptTags(context: {
|
||||
scripts: Array<[HTMLScriptElement, HTMLScriptElement]>;
|
||||
}) {
|
||||
if (!this.scriptSelector) return Promise.resolve(context);
|
||||
|
||||
const { scripts } = context;
|
||||
const { scripts } = context;
|
||||
|
||||
const originalWrite = document.write;
|
||||
const originalWrite = document.write;
|
||||
|
||||
return from(scripts).pipe(
|
||||
concatMap(script => this.insertScript(script)),
|
||||
catchError(error => of({ ...context, error })),
|
||||
finalize(() => (document.write = originalWrite)),
|
||||
mapTo(context),
|
||||
)
|
||||
.toPromise();
|
||||
}
|
||||
return from(scripts)
|
||||
.pipe(
|
||||
concatMap((script) => this.insertScript(script)),
|
||||
catchError((error) => of({ ...context, error })),
|
||||
finalize(() => (document.write = originalWrite)),
|
||||
mapTo(context),
|
||||
)
|
||||
.toPromise();
|
||||
}
|
||||
|
||||
private insertScript([script, ref]: [HTMLScriptElement, HTMLScriptElement]): Promise<{}> {
|
||||
document.write = (...args) => {
|
||||
const temp = document.createElement("div");
|
||||
temp.innerHTML = args.join();
|
||||
Array.from(temp.childNodes).forEach(node => ref.parentNode?.insertBefore(node, ref));
|
||||
};
|
||||
private insertScript([script, ref]: [
|
||||
HTMLScriptElement,
|
||||
HTMLScriptElement,
|
||||
]): Promise<{}> {
|
||||
document.write = (...args) => {
|
||||
const temp = document.createElement("div");
|
||||
temp.innerHTML = args.join();
|
||||
Array.from(temp.childNodes).forEach((node) =>
|
||||
ref.parentNode?.insertBefore(node, ref),
|
||||
);
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
if (script.src !== "") {
|
||||
script.addEventListener("load", resolve);
|
||||
script.addEventListener("error", reject);
|
||||
ref.parentNode?.replaceChild(script, ref);
|
||||
} else {
|
||||
ref.parentNode?.replaceChild(script, ref);
|
||||
resolve({});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
if (script.src !== "") {
|
||||
script.addEventListener("load", resolve);
|
||||
script.addEventListener("error", reject);
|
||||
ref.parentNode?.replaceChild(script, ref);
|
||||
} else {
|
||||
ref.parentNode?.replaceChild(script, ref);
|
||||
resolve({});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,78 @@
|
||||
import { getScrollTop, Cause } from "./common";
|
||||
|
||||
interface ScrollState {
|
||||
[k: string]: any;
|
||||
scrollTop?: number;
|
||||
scrollHeight?: number;
|
||||
[k: string]: any;
|
||||
scrollTop?: number;
|
||||
scrollHeight?: number;
|
||||
}
|
||||
|
||||
export class ScrollManager {
|
||||
private parent: { histId: string } & HTMLElement;
|
||||
private parent: { histId: string } & HTMLElement;
|
||||
|
||||
constructor(parent: { histId: string } & HTMLElement) {
|
||||
this.parent = parent;
|
||||
if ('scrollRestoration' in history) {
|
||||
history.scrollRestoration = 'manual';
|
||||
}
|
||||
}
|
||||
constructor(parent: { histId: string } & HTMLElement) {
|
||||
this.parent = parent;
|
||||
if ("scrollRestoration" in history) {
|
||||
history.scrollRestoration = "manual";
|
||||
}
|
||||
}
|
||||
|
||||
manageScrollPosition({ cause, url: { hash } }: { cause: Cause, url: URL }) {
|
||||
switch (cause) {
|
||||
case Cause.Push: {
|
||||
// FIXME: make configurable
|
||||
this.scrollHashIntoView(hash, { behavior: "smooth", block: "start", inline: "nearest" });
|
||||
break;
|
||||
}
|
||||
case Cause.Pop: {
|
||||
this.restoreScrollPosition();
|
||||
break;
|
||||
}
|
||||
case Cause.Init: {
|
||||
this.restoreScrollPositionOnReload();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
manageScrollPosition({ cause, url: { hash } }: { cause: Cause; url: URL }) {
|
||||
switch (cause) {
|
||||
case Cause.Push: {
|
||||
// FIXME: make configurable
|
||||
this.scrollHashIntoView(hash, {
|
||||
behavior: "smooth",
|
||||
block: "start",
|
||||
inline: "nearest",
|
||||
});
|
||||
break;
|
||||
}
|
||||
case Cause.Pop: {
|
||||
this.restoreScrollPosition();
|
||||
break;
|
||||
}
|
||||
case Cause.Init: {
|
||||
this.restoreScrollPositionOnReload();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private elementFromHash(hash: string) {
|
||||
return document.getElementById(decodeURIComponent(hash.substr(1)))
|
||||
}
|
||||
private elementFromHash(hash: string) {
|
||||
return document.getElementById(decodeURIComponent(hash.substr(1)));
|
||||
}
|
||||
|
||||
private scrollHashIntoView(hash: string, options: boolean | ScrollIntoViewOptions) {
|
||||
if (hash) {
|
||||
const el = this.elementFromHash(hash);
|
||||
if (el) el.scrollIntoView(options);
|
||||
} else {
|
||||
window.scroll(window.pageXOffset, 0);
|
||||
}
|
||||
}
|
||||
private scrollHashIntoView(
|
||||
hash: string,
|
||||
options: boolean | ScrollIntoViewOptions,
|
||||
) {
|
||||
if (hash) {
|
||||
const el = this.elementFromHash(hash);
|
||||
if (el) el.scrollIntoView(options);
|
||||
} else {
|
||||
window.scroll(window.pageXOffset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private restoreScrollPosition() {
|
||||
const { histId } = this.parent;
|
||||
const { scrollTop } = (history.state && history.state[histId]) || {} as ScrollState;
|
||||
private restoreScrollPosition() {
|
||||
const { histId } = this.parent;
|
||||
const { scrollTop } =
|
||||
(history.state && history.state[histId]) || ({} as ScrollState);
|
||||
|
||||
if (scrollTop != null) {
|
||||
window.scroll(window.pageXOffset, scrollTop);
|
||||
}
|
||||
}
|
||||
if (scrollTop != null) {
|
||||
window.scroll(window.pageXOffset, scrollTop);
|
||||
}
|
||||
}
|
||||
|
||||
private restoreScrollPositionOnReload() {
|
||||
const { histId } = this.parent;
|
||||
const scrollState = history.state && history.state[histId];
|
||||
// FIXME: As far as I can tell there is no better way of figuring out if the user has scrolled
|
||||
// and it doesn't work on hash links b/c the scroll position is going to be non-null by definition
|
||||
if (scrollState && getScrollTop() === 0) {
|
||||
this.restoreScrollPosition();
|
||||
} else if (location.hash) {
|
||||
requestAnimationFrame(() => this.scrollHashIntoView(location.hash, true));
|
||||
}
|
||||
}
|
||||
};
|
||||
private restoreScrollPositionOnReload() {
|
||||
const { histId } = this.parent;
|
||||
const scrollState = history.state && history.state[histId];
|
||||
// FIXME: As far as I can tell there is no better way of figuring out if the user has scrolled
|
||||
// and it doesn't work on hash links b/c the scroll position is going to be non-null by definition
|
||||
if (scrollState && getScrollTop() === 0) {
|
||||
this.restoreScrollPosition();
|
||||
} else if (location.hash) {
|
||||
requestAnimationFrame(() => this.scrollHashIntoView(location.hash, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,112 +3,133 @@ import { isExternal, fragmentFromString } from "./common";
|
||||
import { ScriptManager } from "./script";
|
||||
import { rewriteURLs } from "./rewrite-urls";
|
||||
|
||||
import { ResponseContext, ResponseContextOk } from './fetch';
|
||||
import { ResponseContext, ResponseContextOk } from "./fetch";
|
||||
import { HyPushState } from ".";
|
||||
|
||||
const CANONICAL_SEL = 'link[rel=canonical]';
|
||||
const META_DESC_SEL = 'meta[name=description]';
|
||||
const CANONICAL_SEL = "link[rel=canonical]";
|
||||
const META_DESC_SEL = "meta[name=description]";
|
||||
|
||||
export interface ReplaceContext extends ResponseContext {
|
||||
title: string;
|
||||
document: Document,
|
||||
replaceEls: (Element | null)[];
|
||||
scripts: Array<[HTMLScriptElement, HTMLScriptElement]>;
|
||||
};
|
||||
title: string;
|
||||
document: Document;
|
||||
replaceEls: (Element | null)[];
|
||||
scripts: Array<[HTMLScriptElement, HTMLScriptElement]>;
|
||||
}
|
||||
|
||||
export class UpdateManager {
|
||||
private parent!: HyPushState;
|
||||
private scriptManager!: ScriptManager;
|
||||
private parent!: HyPushState;
|
||||
private scriptManager!: ScriptManager;
|
||||
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
this.scriptManager = new ScriptManager(parent);
|
||||
}
|
||||
constructor(parent: HyPushState) {
|
||||
this.parent = parent;
|
||||
this.scriptManager = new ScriptManager(parent);
|
||||
}
|
||||
|
||||
get el() { return this.parent; }
|
||||
get replaceSelector() { return this.parent.replaceSelector; }
|
||||
get scriptSelector() { return this.parent.scriptSelector; }
|
||||
get el() {
|
||||
return this.parent;
|
||||
}
|
||||
get replaceSelector() {
|
||||
return this.parent.replaceSelector;
|
||||
}
|
||||
get scriptSelector() {
|
||||
return this.parent.scriptSelector;
|
||||
}
|
||||
|
||||
// Extracts the elements to be replaced
|
||||
private getReplaceElements(doc: Document): (Element | null)[] {
|
||||
if (this.replaceSelector) {
|
||||
return this.replaceSelector.split(',').map(sel => doc.querySelector(sel));
|
||||
} else if (this.el.id) {
|
||||
return [doc.getElementById(this.el.id)];
|
||||
} else {
|
||||
const index = Array.from(document.getElementsByTagName(this.el.tagName)).indexOf(this.el);
|
||||
return [doc.getElementsByTagName(this.el.tagName)[index]];
|
||||
}
|
||||
}
|
||||
// Extracts the elements to be replaced
|
||||
private getReplaceElements(doc: Document): (Element | null)[] {
|
||||
if (this.replaceSelector) {
|
||||
return this.replaceSelector
|
||||
.split(",")
|
||||
.map((sel) => doc.querySelector(sel));
|
||||
} else if (this.el.id) {
|
||||
return [doc.getElementById(this.el.id)];
|
||||
} else {
|
||||
const index = Array.from(
|
||||
document.getElementsByTagName(this.el.tagName),
|
||||
).indexOf(this.el);
|
||||
return [doc.getElementsByTagName(this.el.tagName)[index]];
|
||||
}
|
||||
}
|
||||
|
||||
// Takes the response string and turns it into document fragments
|
||||
// that can be inserted into the DOM.
|
||||
responseToContent(context: ResponseContextOk): ReplaceContext {
|
||||
const { responseText } = context;
|
||||
// Takes the response string and turns it into document fragments
|
||||
// that can be inserted into the DOM.
|
||||
responseToContent(context: ResponseContextOk): ReplaceContext {
|
||||
const { responseText } = context;
|
||||
|
||||
const doc = new DOMParser().parseFromString(responseText, 'text/html');
|
||||
const { title = '' } = doc;
|
||||
const replaceEls = this.getReplaceElements(doc);
|
||||
const doc = new DOMParser().parseFromString(responseText, "text/html");
|
||||
const { title = "" } = doc;
|
||||
const replaceEls = this.getReplaceElements(doc);
|
||||
|
||||
if (replaceEls.every(el => el == null)) {
|
||||
throw new Error(`Couldn't find any element in the document at '${location}'.`);
|
||||
}
|
||||
if (replaceEls.every((el) => el == null)) {
|
||||
throw new Error(
|
||||
`Couldn't find any element in the document at '${location}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const scripts = this.scriptSelector
|
||||
? this.scriptManager.removeScriptTags(replaceEls)
|
||||
: [];
|
||||
const scripts = this.scriptSelector
|
||||
? this.scriptManager.removeScriptTags(replaceEls)
|
||||
: [];
|
||||
|
||||
return { ...context, document: doc, title, replaceEls, scripts };
|
||||
}
|
||||
return { ...context, document: doc, title, replaceEls, scripts };
|
||||
}
|
||||
|
||||
// Replaces the old elements with the new one, one-by-one.
|
||||
private replaceContentWithSelector(replaceSelector: string, elements: (Element | null)[]) {
|
||||
replaceSelector
|
||||
.split(',')
|
||||
.map(sel => document.querySelector(sel))
|
||||
.forEach((oldElement, i) => {
|
||||
const el = elements[i];
|
||||
if (el) oldElement?.parentNode?.replaceChild(el, oldElement);
|
||||
});
|
||||
}
|
||||
// Replaces the old elements with the new one, one-by-one.
|
||||
private replaceContentWithSelector(
|
||||
replaceSelector: string,
|
||||
elements: (Element | null)[],
|
||||
) {
|
||||
replaceSelector
|
||||
.split(",")
|
||||
.map((sel) => document.querySelector(sel))
|
||||
.forEach((oldElement, i) => {
|
||||
const el = elements[i];
|
||||
if (el) oldElement?.parentNode?.replaceChild(el, oldElement);
|
||||
});
|
||||
}
|
||||
|
||||
// When no `replaceIds` are set, replace the entire content of the component (slow).
|
||||
private replaceContentWholesale([el]: (Element | null)[]) {
|
||||
if (el) this.el.innerHTML = el.innerHTML;
|
||||
}
|
||||
// When no `replaceIds` are set, replace the entire content of the component (slow).
|
||||
private replaceContentWholesale([el]: (Element | null)[]) {
|
||||
if (el) this.el.innerHTML = el.innerHTML;
|
||||
}
|
||||
|
||||
private replaceContent(replaceEls: (Element | null)[]) {
|
||||
if (this.replaceSelector) {
|
||||
this.replaceContentWithSelector(this.replaceSelector, replaceEls);
|
||||
} else {
|
||||
this.replaceContentWholesale(replaceEls);
|
||||
}
|
||||
}
|
||||
private replaceContent(replaceEls: (Element | null)[]) {
|
||||
if (this.replaceSelector) {
|
||||
this.replaceContentWithSelector(this.replaceSelector, replaceEls);
|
||||
} else {
|
||||
this.replaceContentWholesale(replaceEls);
|
||||
}
|
||||
}
|
||||
|
||||
private replaceHead(doc: Document) {
|
||||
const { head } = this.el.ownerDocument;
|
||||
private replaceHead(doc: Document) {
|
||||
const { head } = this.el.ownerDocument;
|
||||
|
||||
const canonicalEl = head.querySelector(CANONICAL_SEL) as HTMLLinkElement|null;
|
||||
const cEl = doc.head.querySelector(CANONICAL_SEL) as HTMLLinkElement|null;
|
||||
if (canonicalEl && cEl) canonicalEl.href = cEl.href;
|
||||
const canonicalEl = head.querySelector(
|
||||
CANONICAL_SEL,
|
||||
) as HTMLLinkElement | null;
|
||||
const cEl = doc.head.querySelector(CANONICAL_SEL) as HTMLLinkElement | null;
|
||||
if (canonicalEl && cEl) canonicalEl.href = cEl.href;
|
||||
|
||||
const metaDescEl = head.querySelector(META_DESC_SEL) as HTMLMetaElement|null;
|
||||
const mEl = doc.head.querySelector(META_DESC_SEL) as HTMLMetaElement|null;
|
||||
if (metaDescEl && mEl) metaDescEl.content = mEl.content;
|
||||
}
|
||||
const metaDescEl = head.querySelector(
|
||||
META_DESC_SEL,
|
||||
) as HTMLMetaElement | null;
|
||||
const mEl = doc.head.querySelector(META_DESC_SEL) as HTMLMetaElement | null;
|
||||
if (metaDescEl && mEl) metaDescEl.content = mEl.content;
|
||||
}
|
||||
|
||||
updateDOM(context: ReplaceContext) {
|
||||
try {
|
||||
const { replaceEls, document } = context;
|
||||
if (isExternal(this.parent)) rewriteURLs(replaceEls, this.parent.href);
|
||||
this.replaceHead(document)
|
||||
this.replaceContent(replaceEls);
|
||||
} catch (error) {
|
||||
throw { ...context, error };
|
||||
}
|
||||
}
|
||||
updateDOM(context: ReplaceContext) {
|
||||
try {
|
||||
const { replaceEls, document } = context;
|
||||
if (isExternal(this.parent)) rewriteURLs(replaceEls, this.parent.href);
|
||||
this.replaceHead(document);
|
||||
this.replaceContent(replaceEls);
|
||||
} catch (error) {
|
||||
throw { ...context, error };
|
||||
}
|
||||
}
|
||||
|
||||
reinsertScriptTags(context: { scripts: Array<[HTMLScriptElement, HTMLScriptElement]> }) {
|
||||
return this.scriptManager.reinsertScriptTags(context);
|
||||
}
|
||||
reinsertScriptTags(context: {
|
||||
scripts: Array<[HTMLScriptElement, HTMLScriptElement]>;
|
||||
}) {
|
||||
return this.scriptManager.reinsertScriptTags(context);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user