chore: format
This commit is contained in:
@@ -1,70 +1,70 @@
|
||||
{
|
||||
"name": "@honeymachine/search",
|
||||
"version": "1.0.0",
|
||||
"description": "A search component for the modern web",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hm-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hm-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hm-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Sebastian Krüger <sk@honeymachine.io> (https://honeymachine.io/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/w3c-css-typed-object-model-level-1": "20180410.0.4",
|
||||
"lunr": "^2.3.9"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/honeymachine/search.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/honeymachine/search/issues"
|
||||
},
|
||||
"homepage": "https://honeymachine.github.io/search/",
|
||||
"tags": [
|
||||
"search",
|
||||
"touch-events",
|
||||
"swipe-gestures",
|
||||
"webcomponent",
|
||||
"jquery",
|
||||
"rxjs",
|
||||
"pivoine",
|
||||
"jquery-plugin",
|
||||
"vanilla-js",
|
||||
"search-layout",
|
||||
"custom-element",
|
||||
"vanilla",
|
||||
"web-components",
|
||||
"ui-component",
|
||||
"reactive",
|
||||
"menu",
|
||||
"menu-navigation"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/lunr": "^2.3.7"
|
||||
}
|
||||
"name": "@honeymachine/search",
|
||||
"version": "1.0.0",
|
||||
"description": "A search component for the modern web",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hm-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hm-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hm-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Sebastian Krüger <sk@honeymachine.io> (https://honeymachine.io/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/w3c-css-typed-object-model-level-1": "20180410.0.4",
|
||||
"lunr": "^2.3.9"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/honeymachine/search.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/honeymachine/search/issues"
|
||||
},
|
||||
"homepage": "https://honeymachine.github.io/search/",
|
||||
"tags": [
|
||||
"search",
|
||||
"touch-events",
|
||||
"swipe-gestures",
|
||||
"webcomponent",
|
||||
"jquery",
|
||||
"rxjs",
|
||||
"pivoine",
|
||||
"jquery-plugin",
|
||||
"vanilla-js",
|
||||
"search-layout",
|
||||
"custom-element",
|
||||
"vanilla",
|
||||
"web-components",
|
||||
"ui-component",
|
||||
"reactive",
|
||||
"menu",
|
||||
"menu-navigation"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/lunr": "^2.3.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import terser from '@rollup/plugin-terser';
|
||||
import resolve from "@rollup/plugin-node-resolve";
|
||||
import commonjs from "@rollup/plugin-commonjs";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
|
||||
export default [
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hm-search.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
{
|
||||
input: "src/index.ts",
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hm-search.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1 +1 @@
|
||||
export { applyMixins } from '@hydecorp/component';
|
||||
export { applyMixins } from "@hydecorp/component";
|
||||
|
||||
@@ -17,76 +17,80 @@
|
||||
* @license
|
||||
* @nocompile
|
||||
*/
|
||||
import { html } from 'lit';
|
||||
import { customElement, property, query, eventOptions } from 'lit/decorators.js';
|
||||
import { RxLitElement } from '@hydecorp/component';
|
||||
import lunr from 'lunr';
|
||||
import { applyMixins } from './common';
|
||||
import { styles } from './styles';
|
||||
import { Key } from 'readline';
|
||||
import { html } from "lit";
|
||||
import {
|
||||
customElement,
|
||||
property,
|
||||
query,
|
||||
eventOptions,
|
||||
} from "lit/decorators.js";
|
||||
import { RxLitElement } from "@hydecorp/component";
|
||||
import lunr from "lunr";
|
||||
import { applyMixins } from "./common";
|
||||
import { styles } from "./styles";
|
||||
import { Key } from "readline";
|
||||
|
||||
@customElement('hm-search')
|
||||
@customElement("hm-search")
|
||||
export class HmSearch extends applyMixins(RxLitElement, []) {
|
||||
static styles = styles;
|
||||
static styles = styles;
|
||||
|
||||
@query('.hm-search-input') inputEl!: HTMLInputElement;
|
||||
@query(".hm-search-input") inputEl!: HTMLInputElement;
|
||||
|
||||
@property({ type: String, reflect: true }) placeholder: string = 'Search...';
|
||||
@property({ type: Array, reflect: true }) documents: Array<any> = [];
|
||||
@property({ type: Array, reflect: true }) fields: Array<string> = [];
|
||||
@property({ type: String, reflect: true }) placeholder: string = "Search...";
|
||||
@property({ type: Array, reflect: true }) documents: Array<any> = [];
|
||||
@property({ type: Array, reflect: true }) fields: Array<string> = [];
|
||||
|
||||
idx!: lunr.Index;
|
||||
idx!: lunr.Index;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
handleKeyup(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
const query = this.inputEl.value;
|
||||
if (!query) {
|
||||
this.fireEvent('search', { detail: [] });
|
||||
return;
|
||||
}
|
||||
this.fireEvent('search', { detail: this.idx.search(query) });
|
||||
}
|
||||
handleKeyup(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") {
|
||||
this.clear();
|
||||
return;
|
||||
}
|
||||
const query = this.inputEl.value;
|
||||
if (!query) {
|
||||
this.fireEvent("search", { detail: [] });
|
||||
return;
|
||||
}
|
||||
this.fireEvent("search", { detail: this.idx.search(query) });
|
||||
}
|
||||
|
||||
updated(): void {
|
||||
const documents = this.documents;
|
||||
const fields = this.fields;
|
||||
this.idx = lunr(function () {
|
||||
fields.forEach((field) => {
|
||||
this.field(field);
|
||||
});
|
||||
|
||||
updated(): void {
|
||||
const documents = this.documents;
|
||||
const fields = this.fields;
|
||||
this.idx = lunr(function () {
|
||||
fields.forEach((field) => {
|
||||
this.field(field);
|
||||
});
|
||||
documents.forEach((doc) => {
|
||||
this.add(doc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
documents.forEach((doc) => {
|
||||
this.add(doc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
render() {
|
||||
return html`
|
||||
<div class="hm-search">
|
||||
<input class="hm-search-input" type="text" placeholder="${this.placeholder}" name="hm-search-input" @keyup="${this.handleKeyup}" />
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
focus() {
|
||||
this.inputEl.focus();
|
||||
}
|
||||
focus() {
|
||||
this.inputEl.focus();
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.inputEl.value = '';
|
||||
this.fireEvent('search', { detail: [] });
|
||||
}
|
||||
clear() {
|
||||
this.inputEl.value = "";
|
||||
this.fireEvent("search", { detail: [] });
|
||||
}
|
||||
|
||||
get active() {
|
||||
return this.inputEl === document.activeElement;
|
||||
}
|
||||
get active() {
|
||||
return this.inputEl === document.activeElement;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { css } from 'lit';
|
||||
import { css } from "lit";
|
||||
|
||||
export const styles = css`
|
||||
@media screen {
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["typings/**/*.ts", "src/**/*.ts"]
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["typings/**/*.ts", "src/**/*.ts"]
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
type Constructor<T> = {
|
||||
new (...args: unknown[]): T
|
||||
new (...args: unknown[]): T;
|
||||
};
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassDescriptor {
|
||||
kind: 'class';
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
kind: "class";
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
}
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassElement {
|
||||
kind: 'field'|'method';
|
||||
key: PropertyKey;
|
||||
placement: 'static'|'prototype'|'own';
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
kind: "field" | "method";
|
||||
key: PropertyKey;
|
||||
placement: "static" | "prototype" | "own";
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
{
|
||||
"name": "@hydecorp/component",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"typings",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib",
|
||||
"test": "exit 0",
|
||||
"build": "tsc --outDir lib",
|
||||
"watch": "tsc --outDir lib -w",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/resize-observer-browser": "^0.1.7"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
"name": "@hydecorp/component",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"typings",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib",
|
||||
"test": "exit 0",
|
||||
"build": "tsc --outDir lib",
|
||||
"watch": "tsc --outDir lib -w",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/resize-observer-browser": "^0.1.7"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"typescript": "^4.5.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,54 @@
|
||||
import { Observable, animationFrames } from "rxjs";
|
||||
import { map, takeWhile, endWith } from "rxjs/operators";
|
||||
|
||||
export function fetchRx(input: RequestInfo, init?: RequestInit): Observable<Response> {
|
||||
return new Observable(observer => {
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
export function fetchRx(
|
||||
input: RequestInfo,
|
||||
init?: RequestInit,
|
||||
): Observable<Response> {
|
||||
return new Observable((observer) => {
|
||||
const controller = new AbortController();
|
||||
const { signal } = controller;
|
||||
|
||||
let response: Response | null = null;
|
||||
fetch(input, { ...init, signal })
|
||||
.then(r => {
|
||||
response = r;
|
||||
observer.next(r);
|
||||
observer.complete();
|
||||
})
|
||||
.catch(x => observer.error(x));
|
||||
let response: Response | null = null;
|
||||
fetch(input, { ...init, signal })
|
||||
.then((r) => {
|
||||
response = r;
|
||||
observer.next(r);
|
||||
observer.complete();
|
||||
})
|
||||
.catch((x) => observer.error(x));
|
||||
|
||||
return () => { if (!response) controller.abort(); };
|
||||
});
|
||||
return () => {
|
||||
if (!response) controller.abort();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function fromMediaQuery(mql: MediaQueryList): Observable<MediaQueryListEvent> {
|
||||
return new Observable(o => {
|
||||
const l = o.next.bind(o);
|
||||
if (mql.onchange) mql.addEventListener('change', l); else mql.addListener(l);
|
||||
return () => {
|
||||
if (mql.onchange) mql.removeEventListener('change', l); else mql.removeListener(l);
|
||||
}
|
||||
});
|
||||
export function fromMediaQuery(
|
||||
mql: MediaQueryList,
|
||||
): Observable<MediaQueryListEvent> {
|
||||
return new Observable((o) => {
|
||||
const l = o.next.bind(o);
|
||||
if (mql.onchange) mql.addEventListener("change", l);
|
||||
else mql.addListener(l);
|
||||
return () => {
|
||||
if (mql.onchange) mql.removeEventListener("change", l);
|
||||
else mql.removeListener(l);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function tween(easingFn: (t: number, b: number, c: number, d: number, s?: number) => number, b: number, c: number, d: number, s?: number): Observable<number> {
|
||||
return animationFrames().pipe(
|
||||
map(({ elapsed }) => elapsed),
|
||||
takeWhile(t => t < d),
|
||||
endWith(d),
|
||||
map(t => easingFn(t, b, c, d, s)),
|
||||
)
|
||||
export function tween(
|
||||
easingFn: (t: number, b: number, c: number, d: number, s?: number) => number,
|
||||
b: number,
|
||||
c: number,
|
||||
d: number,
|
||||
s?: number,
|
||||
): Observable<number> {
|
||||
return animationFrames().pipe(
|
||||
map(({ elapsed }) => elapsed),
|
||||
takeWhile((t) => t < d),
|
||||
endWith(d),
|
||||
map((t) => easingFn(t, b, c, d, s)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,46 +1,51 @@
|
||||
import { LitElement } from 'lit';
|
||||
import { Subject } from 'rxjs';
|
||||
import { LitElement } from "lit";
|
||||
import { Subject } from "rxjs";
|
||||
|
||||
export class RxLitElement extends LitElement {
|
||||
$connected = new Subject<boolean>();
|
||||
$connected = new Subject<boolean>();
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.$connected.next(true);
|
||||
}
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.$connected.next(true);
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.$connected.next(false);
|
||||
}
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this.$connected.next(false);
|
||||
}
|
||||
|
||||
#firstUpdate!: boolean;
|
||||
#firstUpdate!: boolean;
|
||||
|
||||
$: any = {};
|
||||
$: any = {};
|
||||
|
||||
firstUpdated() {
|
||||
this.#firstUpdate = true;
|
||||
}
|
||||
firstUpdated() {
|
||||
this.#firstUpdate = true;
|
||||
}
|
||||
|
||||
updated(changedProperties: Map<string, any>) {
|
||||
if (!this.#firstUpdate)
|
||||
for (const prop of changedProperties.keys()) {
|
||||
if (prop in this.$) this.$[prop].next((<any>this)[prop]);
|
||||
}
|
||||
this.#firstUpdate = false;
|
||||
}
|
||||
updated(changedProperties: Map<string, any>) {
|
||||
if (!this.#firstUpdate)
|
||||
for (const prop of changedProperties.keys()) {
|
||||
if (prop in this.$) this.$[prop].next((<any>this)[prop]);
|
||||
}
|
||||
this.#firstUpdate = false;
|
||||
}
|
||||
|
||||
fireEvent<T>(name: string, eventInitDict?: CustomEventInit<T>) {
|
||||
this.dispatchEvent(new CustomEvent(name, eventInitDict));
|
||||
this.dispatchEvent(new CustomEvent(`${this.tagName.toLowerCase()}-${name}`, eventInitDict));
|
||||
}
|
||||
fireEvent<T>(name: string, eventInitDict?: CustomEventInit<T>) {
|
||||
this.dispatchEvent(new CustomEvent(name, eventInitDict));
|
||||
this.dispatchEvent(
|
||||
new CustomEvent(`${this.tagName.toLowerCase()}-${name}`, eventInitDict),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function applyMixins<T>(derivedCtor: Constructor<T>, baseCtors: Constructor<any>[]) {
|
||||
baseCtors.forEach((baseCtor) => {
|
||||
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
|
||||
derivedCtor.prototype[name] = baseCtor.prototype[name];
|
||||
});
|
||||
});
|
||||
return derivedCtor;
|
||||
export function applyMixins<T>(
|
||||
derivedCtor: Constructor<T>,
|
||||
baseCtors: Constructor<any>[],
|
||||
) {
|
||||
baseCtors.forEach((baseCtor) => {
|
||||
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
|
||||
derivedCtor.prototype[name] = baseCtor.prototype[name];
|
||||
});
|
||||
});
|
||||
return derivedCtor;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './creators';
|
||||
export * from './element';
|
||||
export * from './observers';
|
||||
export * from './operators';
|
||||
export * from './util';
|
||||
export * from "./creators";
|
||||
export * from "./element";
|
||||
export * from "./observers";
|
||||
export * from "./operators";
|
||||
export * from "./util";
|
||||
|
||||
@@ -1,31 +1,45 @@
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
export function createResizeObservable(el: HTMLElement): Observable<ResizeObserverEntry> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new ResizeObserver(xs => xs.forEach(x => obs.next(x)));
|
||||
observer.observe(el);
|
||||
return () => { observer.unobserve(el); };
|
||||
});
|
||||
export function createResizeObservable(
|
||||
el: HTMLElement,
|
||||
): Observable<ResizeObserverEntry> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new ResizeObserver((xs) => xs.forEach((x) => obs.next(x)));
|
||||
observer.observe(el);
|
||||
return () => {
|
||||
observer.unobserve(el);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function createMutationObservable(el: HTMLElement, options?: MutationObserverInit): Observable<MutationRecord> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new MutationObserver(xs => xs.forEach(x => obs.next(x)));
|
||||
observer.observe(el, options);
|
||||
return () => { observer.disconnect(); };
|
||||
});
|
||||
export function createMutationObservable(
|
||||
el: HTMLElement,
|
||||
options?: MutationObserverInit,
|
||||
): Observable<MutationRecord> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new MutationObserver((xs) =>
|
||||
xs.forEach((x) => obs.next(x)),
|
||||
);
|
||||
observer.observe(el, options);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function createIntersectionObservable(els: HTMLElement|HTMLElement[], options?: IntersectionObserverInit): Observable<IntersectionObserverEntry[]> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new IntersectionObserver(xs => obs.next(xs), options);
|
||||
export function createIntersectionObservable(
|
||||
els: HTMLElement | HTMLElement[],
|
||||
options?: IntersectionObserverInit,
|
||||
): Observable<IntersectionObserverEntry[]> {
|
||||
return new Observable((obs) => {
|
||||
const observer = new IntersectionObserver((xs) => obs.next(xs), options);
|
||||
|
||||
if (Array.isArray(els)) els.forEach(el => observer.observe(el));
|
||||
else observer.observe(els);
|
||||
if (Array.isArray(els)) els.forEach((el) => observer.observe(el));
|
||||
else observer.observe(els);
|
||||
|
||||
return () => {
|
||||
if (Array.isArray(els)) els.forEach(el => observer.unobserve(el));
|
||||
else observer.unobserve(els);
|
||||
};
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
if (Array.isArray(els)) els.forEach((el) => observer.unobserve(el));
|
||||
else observer.unobserve(els);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import { Observable, NEVER, OperatorFunction } from "rxjs";
|
||||
import { filter, map, switchMap, withLatestFrom, tap, debounceTime } from "rxjs/operators";
|
||||
import {
|
||||
filter,
|
||||
map,
|
||||
switchMap,
|
||||
withLatestFrom,
|
||||
tap,
|
||||
debounceTime,
|
||||
} from "rxjs/operators";
|
||||
|
||||
export function subscribeWhen<T>(p$: Observable<boolean>) {
|
||||
return (source: Observable<T>) => {
|
||||
return p$.pipe(switchMap(p => (p ? source : NEVER)));
|
||||
};
|
||||
return (source: Observable<T>) => {
|
||||
return p$.pipe(switchMap((p) => (p ? source : NEVER)));
|
||||
};
|
||||
}
|
||||
|
||||
export function unsubscribeWhen<T>(p$: Observable<boolean>) {
|
||||
return (source: Observable<T>) => {
|
||||
return p$.pipe(switchMap(p => (p ? NEVER : source)));
|
||||
};
|
||||
return (source: Observable<T>) => {
|
||||
return p$.pipe(switchMap((p) => (p ? NEVER : source)));
|
||||
};
|
||||
}
|
||||
|
||||
// export function filterWhen<T>(p$: Observable<boolean>) {
|
||||
@@ -23,33 +30,38 @@ export function unsubscribeWhen<T>(p$: Observable<boolean>) {
|
||||
// };
|
||||
// };
|
||||
|
||||
export function filterWhen<T>(p$: Observable<boolean>, ...others: Observable<boolean>[]) {
|
||||
return (source: Observable<T>) => {
|
||||
if (others.length === 0) {
|
||||
return source.pipe(
|
||||
withLatestFrom(p$),
|
||||
filter(([, p]) => p),
|
||||
map(([x]) => x)
|
||||
);
|
||||
}
|
||||
export function filterWhen<T>(
|
||||
p$: Observable<boolean>,
|
||||
...others: Observable<boolean>[]
|
||||
) {
|
||||
return (source: Observable<T>) => {
|
||||
if (others.length === 0) {
|
||||
return source.pipe(
|
||||
withLatestFrom(p$),
|
||||
filter(([, p]) => p),
|
||||
map(([x]) => x),
|
||||
);
|
||||
}
|
||||
|
||||
return source.pipe(
|
||||
withLatestFrom(p$, ...others),
|
||||
filter(([, ...ps]) => ps.every(p => p)),
|
||||
map(([x]) => x as T)
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
export function bufferDebounceTime<T>(time: number = 0): OperatorFunction<T, T[]> {
|
||||
return (source: Observable<T>) => {
|
||||
let bufferedValues: T[] = [];
|
||||
|
||||
return source.pipe(
|
||||
tap(value => bufferedValues.push(value)),
|
||||
debounceTime(time),
|
||||
map(() => bufferedValues),
|
||||
tap(() => bufferedValues = []),
|
||||
);
|
||||
};
|
||||
return source.pipe(
|
||||
withLatestFrom(p$, ...others),
|
||||
filter(([, ...ps]) => ps.every((p) => p)),
|
||||
map(([x]) => x as T),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export function bufferDebounceTime<T>(
|
||||
time: number = 0,
|
||||
): OperatorFunction<T, T[]> {
|
||||
return (source: Observable<T>) => {
|
||||
let bufferedValues: T[] = [];
|
||||
|
||||
return source.pipe(
|
||||
tap((value) => bufferedValues.push(value)),
|
||||
debounceTime(time),
|
||||
map(() => bufferedValues),
|
||||
tap(() => (bufferedValues = [])),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,42 +1,51 @@
|
||||
export function getScrollHeight() {
|
||||
const h = document.documentElement;
|
||||
const b = document.body;
|
||||
const sh = "scrollHeight";
|
||||
return h[sh] || b[sh];
|
||||
const h = document.documentElement;
|
||||
const b = document.body;
|
||||
const sh = "scrollHeight";
|
||||
return h[sh] || b[sh];
|
||||
}
|
||||
|
||||
export function getScrollLeft() {
|
||||
return window.pageXOffset || document.body.scrollLeft;
|
||||
return window.pageXOffset || document.body.scrollLeft;
|
||||
}
|
||||
|
||||
export function getScrollTop() {
|
||||
return window.pageYOffset || document.body.scrollTop;
|
||||
return window.pageYOffset || document.body.scrollTop;
|
||||
}
|
||||
|
||||
export const matches = (el: Element, selector: string) => (el.matches || (<any>el)['msMatchesSelector']).call(el, selector);
|
||||
export const matches = (el: Element, selector: string) =>
|
||||
(el.matches || (<any>el)["msMatchesSelector"]).call(el, selector);
|
||||
|
||||
// Checks if this element or any of its parents matches a given `selector`.
|
||||
export function matchesAncestors(el: Element | null, selector: string): Element | null {
|
||||
let curr = el;
|
||||
while (curr != null) {
|
||||
if (matches(curr, selector)) return curr;
|
||||
curr = curr.parentNode instanceof Element ? curr.parentNode : null;
|
||||
}
|
||||
return null;
|
||||
export function matchesAncestors(
|
||||
el: Element | null,
|
||||
selector: string,
|
||||
): Element | null {
|
||||
let curr = el;
|
||||
while (curr != null) {
|
||||
if (matches(curr, selector)) return curr;
|
||||
curr = curr.parentNode instanceof Element ? curr.parentNode : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function fragmentFromString(strHTML: string): DocumentFragment {
|
||||
return document.createRange().createContextualFragment(strHTML);
|
||||
return document.createRange().createContextualFragment(strHTML);
|
||||
}
|
||||
|
||||
type Resolver<T> = (value: T | PromiseLike<T>) => void;
|
||||
type Rejector = (reason?: any) => void;
|
||||
type ResolvablePromise<T> = Promise<T> & { resolve: Resolver<T>, reject: Rejector }
|
||||
type ResolvablePromise<T> = Promise<T> & {
|
||||
resolve: Resolver<T>;
|
||||
reject: Rejector;
|
||||
};
|
||||
export function createResolvablePromise<T>(): ResolvablePromise<T> {
|
||||
let res!: Resolver<T>;
|
||||
let rej!: Rejector;
|
||||
const promise = new Promise((r, s) => (res = r, rej = s)) as ResolvablePromise<T>;
|
||||
promise.resolve = res;
|
||||
promise.reject = rej;
|
||||
return promise;
|
||||
let res!: Resolver<T>;
|
||||
let rej!: Rejector;
|
||||
const promise = new Promise(
|
||||
(r, s) => ((res = r), (rej = s)),
|
||||
) as ResolvablePromise<T>;
|
||||
promise.resolve = res;
|
||||
promise.reject = rej;
|
||||
return promise;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
},
|
||||
"include": [
|
||||
"typings/**/*.ts",
|
||||
"src/**/*.ts",
|
||||
],
|
||||
}
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true
|
||||
},
|
||||
"include": ["typings/**/*.ts", "src/**/*.ts"]
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
type Constructor<T> = {
|
||||
new (...args: unknown[]): T
|
||||
new (...args: unknown[]): T;
|
||||
};
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassDescriptor {
|
||||
kind: 'class';
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
kind: "class";
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
}
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassElement {
|
||||
kind: 'field'|'method';
|
||||
key: PropertyKey;
|
||||
placement: 'static'|'prototype'|'own';
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
kind: "field" | "method";
|
||||
key: PropertyKey;
|
||||
placement: "static" | "prototype" | "own";
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
{
|
||||
"name": "@hydecorp/drawer",
|
||||
"version": "1.0.0",
|
||||
"description": "A touch-enabled drawer component for the modern web",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hy-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hy-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hy-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/resize-observer-browser": "^0.1.7",
|
||||
"@types/w3c-css-typed-object-model-level-1": "20180410.0.4"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/hydecorp/drawer.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/hydecorp/drawer/issues"
|
||||
},
|
||||
"homepage": "https://hydecorp.github.io/drawer/",
|
||||
"tags": [
|
||||
"drawer",
|
||||
"touch-events",
|
||||
"swipe-gestures",
|
||||
"webcomponent",
|
||||
"jquery",
|
||||
"rxjs",
|
||||
"pivoine",
|
||||
"jquery-plugin",
|
||||
"vanilla-js",
|
||||
"drawer-layout",
|
||||
"custom-element",
|
||||
"vanilla",
|
||||
"web-components",
|
||||
"ui-component",
|
||||
"reactive",
|
||||
"menu",
|
||||
"menu-navigation"
|
||||
],
|
||||
"devDependencies": {
|
||||
"rollup": "^4.40.1"
|
||||
}
|
||||
"name": "@hydecorp/drawer",
|
||||
"version": "1.0.0",
|
||||
"description": "A touch-enabled drawer component for the modern web",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hy-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hy-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hy-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/resize-observer-browser": "^0.1.7",
|
||||
"@types/w3c-css-typed-object-model-level-1": "20180410.0.4"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/hydecorp/drawer.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/hydecorp/drawer/issues"
|
||||
},
|
||||
"homepage": "https://hydecorp.github.io/drawer/",
|
||||
"tags": [
|
||||
"drawer",
|
||||
"touch-events",
|
||||
"swipe-gestures",
|
||||
"webcomponent",
|
||||
"jquery",
|
||||
"rxjs",
|
||||
"pivoine",
|
||||
"jquery-plugin",
|
||||
"vanilla-js",
|
||||
"drawer-layout",
|
||||
"custom-element",
|
||||
"vanilla",
|
||||
"web-components",
|
||||
"ui-component",
|
||||
"reactive",
|
||||
"menu",
|
||||
"menu-navigation"
|
||||
],
|
||||
"devDependencies": {
|
||||
"rollup": "^4.40.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import terser from '@rollup/plugin-terser';
|
||||
import resolve from "@rollup/plugin-node-resolve";
|
||||
import commonjs from "@rollup/plugin-commonjs";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
|
||||
export default [
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hy-drawer.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
{
|
||||
input: "src/index.ts",
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hy-drawer.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,69 +1,86 @@
|
||||
import { VELOCITY_THRESHOLD } from "./constants";
|
||||
|
||||
import { Coord } from './observables';
|
||||
import { Coord } from "./observables";
|
||||
|
||||
// Using shorthands for common functions
|
||||
const min = Math.min.bind(Math);
|
||||
const max = Math.max.bind(Math);
|
||||
|
||||
export class CalcMixin {
|
||||
side!: 'left' | 'right';
|
||||
range!: [number, number];
|
||||
side!: "left" | "right";
|
||||
range!: [number, number];
|
||||
|
||||
calcIsInRange({ clientX }: Coord, opened: boolean) {
|
||||
// console.log(this.range, this.align);
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
const [lower, upper] = this.range;
|
||||
return clientX > lower && (opened || clientX < upper);
|
||||
}
|
||||
case "right": {
|
||||
const upper = window.innerWidth - this.range[0];
|
||||
const lower = window.innerWidth - this.range[1];
|
||||
return clientX < upper && (opened || clientX > lower);
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
calcIsInRange({ clientX }: Coord, opened: boolean) {
|
||||
// console.log(this.range, this.align);
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
const [lower, upper] = this.range;
|
||||
return clientX > lower && (opened || clientX < upper);
|
||||
}
|
||||
case "right": {
|
||||
const upper = window.innerWidth - this.range[0];
|
||||
const lower = window.innerWidth - this.range[1];
|
||||
return clientX < upper && (opened || clientX > lower);
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
|
||||
calcIsSwipe({ clientX: startX }: Coord, { clientX: endX }: Coord, translateX: number, drawerWidth: number, _: number): boolean {
|
||||
return endX !== startX || (translateX > 0 && translateX < drawerWidth);
|
||||
}
|
||||
calcIsSwipe(
|
||||
{ clientX: startX }: Coord,
|
||||
{ clientX: endX }: Coord,
|
||||
translateX: number,
|
||||
drawerWidth: number,
|
||||
_: number,
|
||||
): boolean {
|
||||
return endX !== startX || (translateX > 0 && translateX < drawerWidth);
|
||||
}
|
||||
|
||||
calcWillOpen(_: {}, __: {}, translateX: number, drawerWidth: number, velocity: number): boolean {
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
if (velocity > VELOCITY_THRESHOLD) return true;
|
||||
else if (velocity < -VELOCITY_THRESHOLD) return false;
|
||||
else if (translateX >= drawerWidth / 2) return true;
|
||||
else return false;
|
||||
}
|
||||
case "right": {
|
||||
if (-velocity > VELOCITY_THRESHOLD) return true;
|
||||
else if (-velocity < -VELOCITY_THRESHOLD) return false;
|
||||
else if (translateX <= -drawerWidth / 2) return true;
|
||||
else return false;
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
calcWillOpen(
|
||||
_: {},
|
||||
__: {},
|
||||
translateX: number,
|
||||
drawerWidth: number,
|
||||
velocity: number,
|
||||
): boolean {
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
if (velocity > VELOCITY_THRESHOLD) return true;
|
||||
else if (velocity < -VELOCITY_THRESHOLD) return false;
|
||||
else if (translateX >= drawerWidth / 2) return true;
|
||||
else return false;
|
||||
}
|
||||
case "right": {
|
||||
if (-velocity > VELOCITY_THRESHOLD) return true;
|
||||
else if (-velocity < -VELOCITY_THRESHOLD) return false;
|
||||
else if (translateX <= -drawerWidth / 2) return true;
|
||||
else return false;
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
|
||||
calcTranslateX({ clientX: moveX }: Coord, { clientX: startX }: Coord, startTranslateX: number, drawerWidth: number): number {
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
const deltaX = moveX - startX;
|
||||
const translateX = startTranslateX + deltaX;
|
||||
return max(0, min(drawerWidth, translateX));
|
||||
}
|
||||
case "right": {
|
||||
const deltaX = moveX - startX;
|
||||
const translateX = startTranslateX + deltaX;
|
||||
return min(0, max(-drawerWidth, translateX));
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
};
|
||||
calcTranslateX(
|
||||
{ clientX: moveX }: Coord,
|
||||
{ clientX: startX }: Coord,
|
||||
startTranslateX: number,
|
||||
drawerWidth: number,
|
||||
): number {
|
||||
switch (this.side) {
|
||||
case "left": {
|
||||
const deltaX = moveX - startX;
|
||||
const translateX = startTranslateX + deltaX;
|
||||
return max(0, min(drawerWidth, translateX));
|
||||
}
|
||||
case "right": {
|
||||
const deltaX = moveX - startX;
|
||||
const translateX = startTranslateX + deltaX;
|
||||
return min(0, max(-drawerWidth, translateX));
|
||||
}
|
||||
default:
|
||||
throw Error();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +1,42 @@
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { createResizeObservable } from '@hydecorp/component';
|
||||
import { ComplexAttributeConverter } from 'lit';
|
||||
import { Observable, of } from "rxjs";
|
||||
import { map } from "rxjs/operators";
|
||||
import { createResizeObservable } from "@hydecorp/component";
|
||||
import { ComplexAttributeConverter } from "lit";
|
||||
|
||||
export { applyMixins, subscribeWhen, filterWhen, tween } from '@hydecorp/component';
|
||||
export {
|
||||
applyMixins,
|
||||
subscribeWhen,
|
||||
filterWhen,
|
||||
tween,
|
||||
} from "@hydecorp/component";
|
||||
|
||||
export function easeOutSine(t: number, b: number, c: number, d: number) {
|
||||
return c * Math.sin((t / d) * (Math.PI / 2)) + b;
|
||||
return c * Math.sin((t / d) * (Math.PI / 2)) + b;
|
||||
}
|
||||
|
||||
export function observeWidth(el: HTMLElement) {
|
||||
// This component should have at least basic support without `ResizeObserver` support,
|
||||
// so we pass a one-time measurement when it's missing. Obviously this won't update, so BYO polyfill.
|
||||
const resize$: Observable<{ contentRect: { width: number } }> =
|
||||
'ResizeObserver' in window ? createResizeObservable(el) : of({ contentRect: { width: el.clientWidth } });
|
||||
return resize$.pipe(map((rect) => rect.contentRect.width));
|
||||
// This component should have at least basic support without `ResizeObserver` support,
|
||||
// so we pass a one-time measurement when it's missing. Obviously this won't update, so BYO polyfill.
|
||||
const resize$: Observable<{ contentRect: { width: number } }> =
|
||||
"ResizeObserver" in window
|
||||
? createResizeObservable(el)
|
||||
: of({ contentRect: { width: el.clientWidth } });
|
||||
return resize$.pipe(map((rect) => rect.contentRect.width));
|
||||
}
|
||||
|
||||
export const rangeConverter: ComplexAttributeConverter<number[]> = {
|
||||
fromAttribute(attr) {
|
||||
return (attr ?? '')
|
||||
.replace(/[\[\]]/g, '')
|
||||
.split(',')
|
||||
.map(Number);
|
||||
},
|
||||
fromAttribute(attr) {
|
||||
return (attr ?? "")
|
||||
.replace(/[\[\]]/g, "")
|
||||
.split(",")
|
||||
.map(Number);
|
||||
},
|
||||
|
||||
toAttribute(range) {
|
||||
return range.join(',');
|
||||
},
|
||||
toAttribute(range) {
|
||||
return range.join(",");
|
||||
},
|
||||
};
|
||||
|
||||
export function rangeHasChanged(curr: number[], prev: number[] = []) {
|
||||
return curr.length !== prev.length || curr.some((v, i) => v !== prev[i]);
|
||||
return curr.length !== prev.length || curr.some((v, i) => v !== prev[i]);
|
||||
}
|
||||
|
||||
@@ -17,406 +17,469 @@
|
||||
* @license
|
||||
* @nocompile
|
||||
*/
|
||||
import { html, ReactiveElement } from 'lit';
|
||||
import { property, customElement, query } from 'lit/decorators.js';
|
||||
import { classMap } from 'lit/directives/class-map.js';
|
||||
import { styleMap } from 'lit/directives/style-map.js';
|
||||
import { html, ReactiveElement } from "lit";
|
||||
import { property, customElement, query } from "lit/decorators.js";
|
||||
import { classMap } from "lit/directives/class-map.js";
|
||||
import { styleMap } from "lit/directives/style-map.js";
|
||||
|
||||
import { Observable, Subject, BehaviorSubject, combineLatest, merge, NEVER, defer, fromEvent } from 'rxjs';
|
||||
import {
|
||||
startWith,
|
||||
takeUntil,
|
||||
map,
|
||||
share,
|
||||
withLatestFrom,
|
||||
tap,
|
||||
sample,
|
||||
timestamp,
|
||||
pairwise,
|
||||
filter,
|
||||
switchMap,
|
||||
skip,
|
||||
finalize,
|
||||
} from 'rxjs/operators';
|
||||
Observable,
|
||||
Subject,
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
merge,
|
||||
NEVER,
|
||||
defer,
|
||||
fromEvent,
|
||||
} from "rxjs";
|
||||
import {
|
||||
startWith,
|
||||
takeUntil,
|
||||
map,
|
||||
share,
|
||||
withLatestFrom,
|
||||
tap,
|
||||
sample,
|
||||
timestamp,
|
||||
pairwise,
|
||||
filter,
|
||||
switchMap,
|
||||
skip,
|
||||
finalize,
|
||||
} from "rxjs/operators";
|
||||
|
||||
import { RxLitElement, createResolvablePromise } from '@hydecorp/component';
|
||||
import { RxLitElement, createResolvablePromise } from "@hydecorp/component";
|
||||
|
||||
import { BASE_DURATION, WIDTH_CONTRIBUTION } from './constants';
|
||||
import { applyMixins, filterWhen, easeOutSine, observeWidth, rangeConverter, rangeHasChanged, tween } from './common';
|
||||
import { ObservablesMixin, Coord } from './observables';
|
||||
import { CalcMixin } from './calc';
|
||||
import { UpdateMixin, DOMUpdater } from './update';
|
||||
import { styles } from './styles';
|
||||
import { BASE_DURATION, WIDTH_CONTRIBUTION } from "./constants";
|
||||
import {
|
||||
applyMixins,
|
||||
filterWhen,
|
||||
easeOutSine,
|
||||
observeWidth,
|
||||
rangeConverter,
|
||||
rangeHasChanged,
|
||||
tween,
|
||||
} from "./common";
|
||||
import { ObservablesMixin, Coord } from "./observables";
|
||||
import { CalcMixin } from "./calc";
|
||||
import { UpdateMixin, DOMUpdater } from "./update";
|
||||
import { styles } from "./styles";
|
||||
|
||||
@customElement('hy-drawer')
|
||||
@customElement("hy-drawer")
|
||||
export class HyDrawer
|
||||
extends applyMixins(RxLitElement, [ObservablesMixin, UpdateMixin, CalcMixin])
|
||||
implements ObservablesMixin, UpdateMixin, CalcMixin
|
||||
extends applyMixins(RxLitElement, [ObservablesMixin, UpdateMixin, CalcMixin])
|
||||
implements ObservablesMixin, UpdateMixin, CalcMixin
|
||||
{
|
||||
static styles = styles;
|
||||
static styles = styles;
|
||||
|
||||
@query('.scrim') scrimEl!: HTMLElement;
|
||||
@query('.wrapper') contentEl!: HTMLElement;
|
||||
@query('.peek') peekEl!: HTMLElement;
|
||||
@query(".scrim") scrimEl!: HTMLElement;
|
||||
@query(".wrapper") contentEl!: HTMLElement;
|
||||
@query(".peek") peekEl!: HTMLElement;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) opened: boolean = false;
|
||||
@property({ type: String, reflect: true }) side: 'left' | 'right' = 'left';
|
||||
@property({ type: Boolean, reflect: true }) persistent: boolean = false;
|
||||
@property({ type: Number, reflect: true }) threshold: number = 10;
|
||||
@property({ type: Boolean, reflect: true }) noScroll: boolean = false;
|
||||
@property({ type: Boolean, reflect: true }) mouseEvents: boolean = false;
|
||||
// @property({ type: Boolean, reflect: true }) hashChange: boolean = false;
|
||||
@property({ reflect: true, converter: rangeConverter, hasChanged: rangeHasChanged }) range: [number, number] = [
|
||||
0, 100,
|
||||
];
|
||||
@property({ type: Boolean, reflect: true }) opened: boolean = false;
|
||||
@property({ type: String, reflect: true }) side: "left" | "right" = "left";
|
||||
@property({ type: Boolean, reflect: true }) persistent: boolean = false;
|
||||
@property({ type: Number, reflect: true }) threshold: number = 10;
|
||||
@property({ type: Boolean, reflect: true }) noScroll: boolean = false;
|
||||
@property({ type: Boolean, reflect: true }) mouseEvents: boolean = false;
|
||||
// @property({ type: Boolean, reflect: true }) hashChange: boolean = false;
|
||||
@property({
|
||||
reflect: true,
|
||||
converter: rangeConverter,
|
||||
hasChanged: rangeHasChanged,
|
||||
})
|
||||
range: [number, number] = [0, 100];
|
||||
|
||||
// State
|
||||
@property() scrimClickable!: boolean;
|
||||
@property() grabbing!: boolean;
|
||||
@property() willChange: boolean = false;
|
||||
// State
|
||||
@property() scrimClickable!: boolean;
|
||||
@property() grabbing!: boolean;
|
||||
@property() willChange: boolean = false;
|
||||
|
||||
#initialized = createResolvablePromise();
|
||||
get initialized() {
|
||||
return this.#initialized;
|
||||
}
|
||||
#initialized = createResolvablePromise();
|
||||
get initialized() {
|
||||
return this.#initialized;
|
||||
}
|
||||
|
||||
// get histId() { return this.id || this.tagName; }
|
||||
// get hashId() { return `#${this.histId}--opened`; }
|
||||
// get histId() { return this.id || this.tagName; }
|
||||
// get hashId() { return `#${this.histId}--opened`; }
|
||||
|
||||
translateX!: number;
|
||||
opacity!: number;
|
||||
isSliding!: boolean;
|
||||
translateX!: number;
|
||||
opacity!: number;
|
||||
isSliding!: boolean;
|
||||
|
||||
$!: {
|
||||
opened: Subject<boolean>;
|
||||
side: Subject<'left' | 'right'>;
|
||||
persistent: Subject<boolean>;
|
||||
preventDefault: Subject<boolean>;
|
||||
mouseEvents: Subject<boolean>;
|
||||
// hashChange: Subject<boolean>;
|
||||
};
|
||||
$!: {
|
||||
opened: Subject<boolean>;
|
||||
side: Subject<"left" | "right">;
|
||||
persistent: Subject<boolean>;
|
||||
preventDefault: Subject<boolean>;
|
||||
mouseEvents: Subject<boolean>;
|
||||
// hashChange: Subject<boolean>;
|
||||
};
|
||||
|
||||
animateTo$!: Subject<boolean>;
|
||||
animateTo$!: Subject<boolean>;
|
||||
|
||||
// TODO: Prefer composition to mixins...
|
||||
// ObservablesMixin
|
||||
getStartObservable!: () => Observable<Coord>;
|
||||
getMoveObservable!: (start: Observable<Coord>, end: Observable<Coord>) => Observable<Coord>;
|
||||
getEndObservable!: () => Observable<Coord>;
|
||||
getIsSlidingObservable!: (
|
||||
move: Observable<Coord>,
|
||||
start: Observable<Coord>,
|
||||
end: Observable<Coord>,
|
||||
) => Observable<boolean>;
|
||||
getIsSlidingObservableInner!: (move: Observable<Coord>, start: Observable<Coord>) => Observable<boolean>;
|
||||
// TODO: Prefer composition to mixins...
|
||||
// ObservablesMixin
|
||||
getStartObservable!: () => Observable<Coord>;
|
||||
getMoveObservable!: (
|
||||
start: Observable<Coord>,
|
||||
end: Observable<Coord>,
|
||||
) => Observable<Coord>;
|
||||
getEndObservable!: () => Observable<Coord>;
|
||||
getIsSlidingObservable!: (
|
||||
move: Observable<Coord>,
|
||||
start: Observable<Coord>,
|
||||
end: Observable<Coord>,
|
||||
) => Observable<boolean>;
|
||||
getIsSlidingObservableInner!: (
|
||||
move: Observable<Coord>,
|
||||
start: Observable<Coord>,
|
||||
) => Observable<boolean>;
|
||||
|
||||
// CalcMixin
|
||||
calcIsInRange!: (start: Coord, opened: boolean) => boolean;
|
||||
calcIsSwipe!: (start: Coord, end: Coord, translateX: number, drawerWidth: number, _: number) => boolean;
|
||||
calcWillOpen!: (start: {}, end: {}, translateX: number, drawerWidth: number, velocity: number) => boolean;
|
||||
calcTranslateX!: (move: Coord, start: Coord, startTranslateX: number, drawerWidth: number) => number;
|
||||
// CalcMixin
|
||||
calcIsInRange!: (start: Coord, opened: boolean) => boolean;
|
||||
calcIsSwipe!: (
|
||||
start: Coord,
|
||||
end: Coord,
|
||||
translateX: number,
|
||||
drawerWidth: number,
|
||||
_: number,
|
||||
) => boolean;
|
||||
calcWillOpen!: (
|
||||
start: {},
|
||||
end: {},
|
||||
translateX: number,
|
||||
drawerWidth: number,
|
||||
velocity: number,
|
||||
) => boolean;
|
||||
calcTranslateX!: (
|
||||
move: Coord,
|
||||
start: Coord,
|
||||
startTranslateX: number,
|
||||
drawerWidth: number,
|
||||
) => number;
|
||||
|
||||
// UpdateMixin
|
||||
updateDOM!: (translateX: number, drawerWidth: number) => void;
|
||||
updater!: DOMUpdater;
|
||||
// UpdateMixin
|
||||
updateDOM!: (translateX: number, drawerWidth: number) => void;
|
||||
updater!: DOMUpdater;
|
||||
|
||||
// HyDrawer
|
||||
getDrawerWidth(): Observable<number> {
|
||||
const content$ = observeWidth(this.contentEl).pipe(
|
||||
tap((px) => this.fireEvent('content-width-change', { detail: px })),
|
||||
);
|
||||
const peek$ = observeWidth(this.peekEl).pipe(tap((px) => this.fireEvent('peek-width-change', { detail: px })));
|
||||
// HyDrawer
|
||||
getDrawerWidth(): Observable<number> {
|
||||
const content$ = observeWidth(this.contentEl).pipe(
|
||||
tap((px) => this.fireEvent("content-width-change", { detail: px })),
|
||||
);
|
||||
const peek$ = observeWidth(this.peekEl).pipe(
|
||||
tap((px) => this.fireEvent("peek-width-change", { detail: px })),
|
||||
);
|
||||
|
||||
return combineLatest([content$, peek$]).pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
map(([contentWidth, peekWidth]) => contentWidth - peekWidth),
|
||||
share(),
|
||||
);
|
||||
}
|
||||
return combineLatest([content$, peek$]).pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
map(([contentWidth, peekWidth]) => contentWidth - peekWidth),
|
||||
share(),
|
||||
);
|
||||
}
|
||||
|
||||
// private consolidateState() {
|
||||
// const hashOpened = location.hash === this.hashId;
|
||||
// const isReload = history.state && history.state[this.histId];
|
||||
// if (isReload) {
|
||||
// if (hashOpened !== this.opened) {
|
||||
// this.opened = hashOpened;
|
||||
// }
|
||||
// } else {
|
||||
// const url = new URL(location.href);
|
||||
// const newState = { ...history.state, [this.histId]: { backable: false } };
|
||||
// if (hashOpened && !this.opened) {
|
||||
// url.hash = '';
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
// private consolidateState() {
|
||||
// const hashOpened = location.hash === this.hashId;
|
||||
// const isReload = history.state && history.state[this.histId];
|
||||
// if (isReload) {
|
||||
// if (hashOpened !== this.opened) {
|
||||
// this.opened = hashOpened;
|
||||
// }
|
||||
// } else {
|
||||
// const url = new URL(location.href);
|
||||
// const newState = { ...history.state, [this.histId]: { backable: false } };
|
||||
// if (hashOpened && !this.opened) {
|
||||
// url.hash = '';
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
|
||||
// url.hash = this.hashId;
|
||||
// history.pushState({ [this.histId]: { backable: true } }, document.title, url.href);
|
||||
// url.hash = this.hashId;
|
||||
// history.pushState({ [this.histId]: { backable: true } }, document.title, url.href);
|
||||
|
||||
// this.opened = true;
|
||||
// }
|
||||
// else if (!hashOpened && this.opened) {
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
// this.opened = true;
|
||||
// }
|
||||
// else if (!hashOpened && this.opened) {
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
|
||||
// url.hash = this.hashId;
|
||||
// history.pushState({ [this.histId]: { backable: true } }, document.title, url.href);
|
||||
// }
|
||||
// else {
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// url.hash = this.hashId;
|
||||
// history.pushState({ [this.histId]: { backable: true } }, document.title, url.href);
|
||||
// }
|
||||
// else {
|
||||
// history.replaceState(newState, document.title, url.href);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
|
||||
// if (this.hashChange) this.consolidateState()
|
||||
// if (this.hashChange) this.consolidateState()
|
||||
|
||||
this.$ = {
|
||||
opened: new BehaviorSubject(this.opened),
|
||||
side: new BehaviorSubject(this.side),
|
||||
persistent: new BehaviorSubject(this.persistent),
|
||||
preventDefault: new BehaviorSubject(this.noScroll),
|
||||
mouseEvents: new BehaviorSubject(this.mouseEvents),
|
||||
// hashChange: new BehaviorSubject(this.hashChange),
|
||||
};
|
||||
this.$ = {
|
||||
opened: new BehaviorSubject(this.opened),
|
||||
side: new BehaviorSubject(this.side),
|
||||
persistent: new BehaviorSubject(this.persistent),
|
||||
preventDefault: new BehaviorSubject(this.noScroll),
|
||||
mouseEvents: new BehaviorSubject(this.mouseEvents),
|
||||
// hashChange: new BehaviorSubject(this.hashChange),
|
||||
};
|
||||
|
||||
this.scrimClickable = this.opened;
|
||||
this.animateTo$ = new Subject<boolean>();
|
||||
this.updater = DOMUpdater.getUpdaterForPlatform(this);
|
||||
this.updateComplete.then(this.upgrade);
|
||||
}
|
||||
this.scrimClickable = this.opened;
|
||||
this.animateTo$ = new Subject<boolean>();
|
||||
this.updater = DOMUpdater.getUpdaterForPlatform(this);
|
||||
this.updateComplete.then(this.upgrade);
|
||||
}
|
||||
|
||||
#translateX$!: Observable<number>;
|
||||
#startTranslateX$!: Observable<number>;
|
||||
#tweenTranslateX$!: Observable<number>;
|
||||
#translateX$!: Observable<number>;
|
||||
#startTranslateX$!: Observable<number>;
|
||||
#tweenTranslateX$!: Observable<number>;
|
||||
|
||||
upgrade = () => {
|
||||
const drawerWidth$ = this.getDrawerWidth();
|
||||
const active$ = this.$.persistent.pipe(map((_) => !_));
|
||||
upgrade = () => {
|
||||
const drawerWidth$ = this.getDrawerWidth();
|
||||
const active$ = this.$.persistent.pipe(map((_) => !_));
|
||||
|
||||
const start$ = this.getStartObservable().pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$),
|
||||
share(),
|
||||
);
|
||||
const start$ = this.getStartObservable().pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$),
|
||||
share(),
|
||||
);
|
||||
|
||||
const isScrimVisible$ = defer(() => {
|
||||
return this.#translateX$.pipe(map((translateX) => translateX !== 0));
|
||||
});
|
||||
const isScrimVisible$ = defer(() => {
|
||||
return this.#translateX$.pipe(map((translateX) => translateX !== 0));
|
||||
});
|
||||
|
||||
const isInRange$ = start$.pipe(
|
||||
withLatestFrom(isScrimVisible$),
|
||||
map((args) => this.calcIsInRange(...args)),
|
||||
tap((inRange) => {
|
||||
if (inRange) {
|
||||
this.willChange = true;
|
||||
this.fireEvent('prepare');
|
||||
}
|
||||
}),
|
||||
share(),
|
||||
);
|
||||
const isInRange$ = start$.pipe(
|
||||
withLatestFrom(isScrimVisible$),
|
||||
map((args) => this.calcIsInRange(...args)),
|
||||
tap((inRange) => {
|
||||
if (inRange) {
|
||||
this.willChange = true;
|
||||
this.fireEvent("prepare");
|
||||
}
|
||||
}),
|
||||
share(),
|
||||
);
|
||||
|
||||
const end$ = this.getEndObservable().pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$, isInRange$),
|
||||
tap(() => {
|
||||
if (this.mouseEvents) this.grabbing = false;
|
||||
}),
|
||||
share(),
|
||||
);
|
||||
const end$ = this.getEndObservable().pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$, isInRange$),
|
||||
tap(() => {
|
||||
if (this.mouseEvents) this.grabbing = false;
|
||||
}),
|
||||
share(),
|
||||
);
|
||||
|
||||
const move$ = this.getMoveObservable(start$, end$).pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$, isInRange$),
|
||||
share(),
|
||||
);
|
||||
const move$ = this.getMoveObservable(start$, end$).pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
filterWhen(active$, isInRange$),
|
||||
share(),
|
||||
);
|
||||
|
||||
const isSliding$ = this.getIsSlidingObservable(move$, start$, end$).pipe(
|
||||
tap((isSliding) => {
|
||||
this.isSliding = isSliding;
|
||||
if (isSliding && this.mouseEvents) this.grabbing = true;
|
||||
// if (isSliding) this.fireEvent('slidestart', { detail: this.opened });
|
||||
}),
|
||||
);
|
||||
const isSliding$ = this.getIsSlidingObservable(move$, start$, end$).pipe(
|
||||
tap((isSliding) => {
|
||||
this.isSliding = isSliding;
|
||||
if (isSliding && this.mouseEvents) this.grabbing = true;
|
||||
// if (isSliding) this.fireEvent('slidestart', { detail: this.opened });
|
||||
}),
|
||||
);
|
||||
|
||||
const translateX$ = (this.#translateX$ = defer(() => {
|
||||
const jumpTranslateX$ = combineLatest([this.$.opened, this.$.side, drawerWidth$]).pipe(
|
||||
map(([opened, side, drawerWidth]) => {
|
||||
return !opened ? 0 : drawerWidth * (side === 'left' ? 1 : -1);
|
||||
}),
|
||||
);
|
||||
const translateX$ = (this.#translateX$ = defer(() => {
|
||||
const jumpTranslateX$ = combineLatest([
|
||||
this.$.opened,
|
||||
this.$.side,
|
||||
drawerWidth$,
|
||||
]).pipe(
|
||||
map(([opened, side, drawerWidth]) => {
|
||||
return !opened ? 0 : drawerWidth * (side === "left" ? 1 : -1);
|
||||
}),
|
||||
);
|
||||
|
||||
const moveTranslateX$ = move$.pipe(
|
||||
filterWhen(isSliding$),
|
||||
tap(() => (this.scrimClickable = false)),
|
||||
tap(({ event }) => event && this.noScroll && event.preventDefault()),
|
||||
withLatestFrom(start$, this.#startTranslateX$, drawerWidth$),
|
||||
map((args) => this.calcTranslateX(...args)),
|
||||
);
|
||||
const moveTranslateX$ = move$.pipe(
|
||||
filterWhen(isSliding$),
|
||||
tap(() => (this.scrimClickable = false)),
|
||||
tap(({ event }) => event && this.noScroll && event.preventDefault()),
|
||||
withLatestFrom(start$, this.#startTranslateX$, drawerWidth$),
|
||||
map((args) => this.calcTranslateX(...args)),
|
||||
);
|
||||
|
||||
return merge(this.#tweenTranslateX$, jumpTranslateX$, moveTranslateX$);
|
||||
}).pipe(share()));
|
||||
return merge(this.#tweenTranslateX$, jumpTranslateX$, moveTranslateX$);
|
||||
}).pipe(share()));
|
||||
|
||||
this.#startTranslateX$ = translateX$.pipe(sample(start$));
|
||||
this.#startTranslateX$ = translateX$.pipe(sample(start$));
|
||||
|
||||
const velocity$ = translateX$.pipe(
|
||||
timestamp(),
|
||||
pairwise(),
|
||||
filter(([{ timestamp: prevTime }, { timestamp: time }]) => time - prevTime > 0),
|
||||
map(([{ value: prevX, timestamp: prevTime }, { value: x, timestamp: time }]) => (x - prevX) / (time - prevTime)),
|
||||
startWith(0),
|
||||
);
|
||||
const velocity$ = translateX$.pipe(
|
||||
timestamp(),
|
||||
pairwise(),
|
||||
filter(
|
||||
([{ timestamp: prevTime }, { timestamp: time }]) => time - prevTime > 0,
|
||||
),
|
||||
map(
|
||||
([
|
||||
{ value: prevX, timestamp: prevTime },
|
||||
{ value: x, timestamp: time },
|
||||
]) => (x - prevX) / (time - prevTime),
|
||||
),
|
||||
startWith(0),
|
||||
);
|
||||
|
||||
const willOpen$ = end$.pipe(
|
||||
withLatestFrom(start$, translateX$, drawerWidth$, velocity$),
|
||||
filter((args) => this.calcIsSwipe(...args)),
|
||||
map((args) => this.calcWillOpen(...args)),
|
||||
// TODO: only fire `slideend` event when slidestart fired as well?
|
||||
// tap(willOpen => this.fireEvent('slideend', { detail: willOpen })),
|
||||
);
|
||||
const willOpen$ = end$.pipe(
|
||||
withLatestFrom(start$, translateX$, drawerWidth$, velocity$),
|
||||
filter((args) => this.calcIsSwipe(...args)),
|
||||
map((args) => this.calcWillOpen(...args)),
|
||||
// TODO: only fire `slideend` event when slidestart fired as well?
|
||||
// tap(willOpen => this.fireEvent('slideend', { detail: willOpen })),
|
||||
);
|
||||
|
||||
const animateTo$ = this.animateTo$.pipe(
|
||||
tap(() => {
|
||||
this.willChange = true;
|
||||
this.fireEvent('prepare');
|
||||
}),
|
||||
);
|
||||
const animateTo$ = this.animateTo$.pipe(
|
||||
tap(() => {
|
||||
this.willChange = true;
|
||||
this.fireEvent("prepare");
|
||||
}),
|
||||
);
|
||||
|
||||
this.#tweenTranslateX$ = merge(willOpen$, animateTo$).pipe(
|
||||
withLatestFrom(translateX$, drawerWidth$),
|
||||
switchMap(([willOpen, translateX, drawerWidth]) => {
|
||||
const inv = this.side === 'left' ? 1 : -1;
|
||||
const endTranslateX = willOpen ? drawerWidth * inv : 0;
|
||||
const diffTranslateX = endTranslateX - translateX;
|
||||
const duration = Math.ceil(BASE_DURATION + drawerWidth * WIDTH_CONTRIBUTION);
|
||||
this.#tweenTranslateX$ = merge(willOpen$, animateTo$).pipe(
|
||||
withLatestFrom(translateX$, drawerWidth$),
|
||||
switchMap(([willOpen, translateX, drawerWidth]) => {
|
||||
const inv = this.side === "left" ? 1 : -1;
|
||||
const endTranslateX = willOpen ? drawerWidth * inv : 0;
|
||||
const diffTranslateX = endTranslateX - translateX;
|
||||
const duration = Math.ceil(
|
||||
BASE_DURATION + drawerWidth * WIDTH_CONTRIBUTION,
|
||||
);
|
||||
|
||||
return tween(easeOutSine, translateX, diffTranslateX, duration).pipe(
|
||||
finalize(() => {
|
||||
this.transitioned(willOpen);
|
||||
}),
|
||||
takeUntil(start$),
|
||||
takeUntil(this.$.side.pipe(skip(1))),
|
||||
share(),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return tween(easeOutSine, translateX, diffTranslateX, duration).pipe(
|
||||
finalize(() => {
|
||||
this.transitioned(willOpen);
|
||||
}),
|
||||
takeUntil(start$),
|
||||
takeUntil(this.$.side.pipe(skip(1))),
|
||||
share(),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
translateX$
|
||||
.pipe(
|
||||
withLatestFrom(drawerWidth$),
|
||||
tap((args) => {
|
||||
this.updateDOM(...args);
|
||||
const { translateX, opacity } = this;
|
||||
this.fireEvent('move', { detail: { translateX, opacity }, bubbles: false });
|
||||
}),
|
||||
)
|
||||
.subscribe();
|
||||
translateX$
|
||||
.pipe(
|
||||
withLatestFrom(drawerWidth$),
|
||||
tap((args) => {
|
||||
this.updateDOM(...args);
|
||||
const { translateX, opacity } = this;
|
||||
this.fireEvent("move", {
|
||||
detail: { translateX, opacity },
|
||||
bubbles: false,
|
||||
});
|
||||
}),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
fromEvent(this.scrimEl, 'click')
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
tap(() => this.close()),
|
||||
)
|
||||
.subscribe();
|
||||
fromEvent(this.scrimEl, "click")
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
tap(() => this.close()),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
active$
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
tap((active) => {
|
||||
this.scrimEl.style.display = active ? 'block' : 'none';
|
||||
}),
|
||||
)
|
||||
.subscribe();
|
||||
active$
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
tap((active) => {
|
||||
this.scrimEl.style.display = active ? "block" : "none";
|
||||
}),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
this.$.mouseEvents
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
switchMap((mouseEvents) => {
|
||||
return mouseEvents ? start$.pipe(withLatestFrom(isInRange$)) : NEVER;
|
||||
}),
|
||||
filter(([coord, isInRange]) => isInRange && coord.event != null),
|
||||
tap(([{ event }]) => event && event.preventDefault()),
|
||||
)
|
||||
.subscribe();
|
||||
this.$.mouseEvents
|
||||
.pipe(
|
||||
// takeUntil(this.subjects.disconnect),
|
||||
switchMap((mouseEvents) => {
|
||||
return mouseEvents ? start$.pipe(withLatestFrom(isInRange$)) : NEVER;
|
||||
}),
|
||||
filter(([coord, isInRange]) => isInRange && coord.event != null),
|
||||
tap(([{ event }]) => event && event.preventDefault()),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
// fromEvent(window, 'hashchange').pipe(
|
||||
// // takeUntil(this.subjects.disconnect),
|
||||
// subscribeWhen(this.$.hashChange),
|
||||
// tap(() => {
|
||||
// const opened = location.hash === this.hashId;
|
||||
// if (!history.state && opened) {
|
||||
// history.replaceState({ [this.histId]: { backable: true } }, document.title)
|
||||
// }
|
||||
// fromEvent(window, 'hashchange').pipe(
|
||||
// // takeUntil(this.subjects.disconnect),
|
||||
// subscribeWhen(this.$.hashChange),
|
||||
// tap(() => {
|
||||
// const opened = location.hash === this.hashId;
|
||||
// if (!history.state && opened) {
|
||||
// history.replaceState({ [this.histId]: { backable: true } }, document.title)
|
||||
// }
|
||||
|
||||
// // If the state doesn't match open/close the drawer
|
||||
// if (opened !== this.opened) this.animateTo$.next(opened);
|
||||
// }),
|
||||
// ).subscribe();
|
||||
// // If the state doesn't match open/close the drawer
|
||||
// if (opened !== this.opened) this.animateTo$.next(opened);
|
||||
// }),
|
||||
// ).subscribe();
|
||||
|
||||
this.fireEvent('init', { detail: this.opened });
|
||||
this.#initialized.resolve(this);
|
||||
};
|
||||
this.fireEvent("init", { detail: this.opened });
|
||||
this.#initialized.resolve(this);
|
||||
};
|
||||
|
||||
private transitioned = (hasOpened: boolean) => {
|
||||
this.opened = this.scrimClickable = hasOpened;
|
||||
this.willChange = false;
|
||||
private transitioned = (hasOpened: boolean) => {
|
||||
this.opened = this.scrimClickable = hasOpened;
|
||||
this.willChange = false;
|
||||
|
||||
// if (this.hashChange) this.transitionedHash(hasOpened)
|
||||
// if (this.hashChange) this.transitionedHash(hasOpened)
|
||||
|
||||
this.fireEvent('transitioned', { detail: hasOpened });
|
||||
};
|
||||
this.fireEvent("transitioned", { detail: hasOpened });
|
||||
};
|
||||
|
||||
// private transitionedHash(hasOpened: boolean) {
|
||||
// const hasClosed = !hasOpened;
|
||||
// const { backable } = history.state && history.state[this.histId] || { backable: false }
|
||||
// if (hasClosed && backable) {
|
||||
// history.back()
|
||||
// }
|
||||
// if (hasOpened && location.hash !== this.hashId) {
|
||||
// location.hash = this.hashId;
|
||||
// }
|
||||
// }
|
||||
// private transitionedHash(hasOpened: boolean) {
|
||||
// const hasClosed = !hasOpened;
|
||||
// const { backable } = history.state && history.state[this.histId] || { backable: false }
|
||||
// if (hasClosed && backable) {
|
||||
// history.back()
|
||||
// }
|
||||
// if (hasOpened && location.hash !== this.hashId) {
|
||||
// location.hash = this.hashId;
|
||||
// }
|
||||
// }
|
||||
|
||||
render() {
|
||||
return html`
|
||||
render() {
|
||||
return html`
|
||||
<div class="peek full-height"></div>
|
||||
<div
|
||||
class="scrim"
|
||||
style=${styleMap({
|
||||
willChange: this.willChange ? 'opacity' : '',
|
||||
pointerEvents: this.scrimClickable ? 'all' : '',
|
||||
})}
|
||||
willChange: this.willChange ? "opacity" : "",
|
||||
pointerEvents: this.scrimClickable ? "all" : "",
|
||||
})}
|
||||
></div>
|
||||
${this.mouseEvents && this.grabbing && !this.scrimClickable
|
||||
? html`<div class="grabbing-screen full-screen"></div>`
|
||||
: null}
|
||||
${
|
||||
this.mouseEvents && this.grabbing && !this.scrimClickable
|
||||
? html`<div class="grabbing-screen full-screen"></div>`
|
||||
: null
|
||||
}
|
||||
<div
|
||||
class=${classMap({
|
||||
wrapper: true,
|
||||
'full-height': true,
|
||||
[this.side]: true,
|
||||
grab: this.mouseEvents,
|
||||
grabbing: this.mouseEvents && this.grabbing,
|
||||
})}
|
||||
wrapper: true,
|
||||
"full-height": true,
|
||||
[this.side]: true,
|
||||
grab: this.mouseEvents,
|
||||
grabbing: this.mouseEvents && this.grabbing,
|
||||
})}
|
||||
style=${styleMap({
|
||||
willChange: this.willChange ? 'transform' : '',
|
||||
})}
|
||||
willChange: this.willChange ? "transform" : "",
|
||||
})}
|
||||
>
|
||||
<div class="overflow">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
open() {
|
||||
this.animateTo$.next(true);
|
||||
}
|
||||
open() {
|
||||
this.animateTo$.next(true);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.animateTo$.next(false);
|
||||
}
|
||||
close() {
|
||||
this.animateTo$.next(false);
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.animateTo$.next(!this.opened);
|
||||
}
|
||||
toggle() {
|
||||
this.animateTo$.next(!this.opened);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import { Observable, combineLatest, fromEvent, merge, NEVER, ObservedValueOf } from "rxjs";
|
||||
import {
|
||||
Observable,
|
||||
combineLatest,
|
||||
fromEvent,
|
||||
merge,
|
||||
NEVER,
|
||||
ObservedValueOf,
|
||||
} from "rxjs";
|
||||
|
||||
import {
|
||||
// tap,
|
||||
filter,
|
||||
map,
|
||||
mapTo,
|
||||
repeatWhen,
|
||||
skipWhile,
|
||||
startWith,
|
||||
switchMap,
|
||||
take,
|
||||
withLatestFrom,
|
||||
// tap,
|
||||
filter,
|
||||
map,
|
||||
mapTo,
|
||||
repeatWhen,
|
||||
skipWhile,
|
||||
startWith,
|
||||
switchMap,
|
||||
take,
|
||||
withLatestFrom,
|
||||
} from "rxjs/operators";
|
||||
|
||||
import { subscribeWhen } from "./common";
|
||||
@@ -18,112 +25,137 @@ import { subscribeWhen } from "./common";
|
||||
const abs = Math.abs.bind(Math);
|
||||
|
||||
export type Coord = {
|
||||
readonly target: EventTarget;
|
||||
readonly clientX: number;
|
||||
readonly clientY: number;
|
||||
readonly pageX: number;
|
||||
readonly pageY: number;
|
||||
readonly screenX: number;
|
||||
readonly screenY: number;
|
||||
event?: Event;
|
||||
}
|
||||
readonly target: EventTarget;
|
||||
readonly clientX: number;
|
||||
readonly clientY: number;
|
||||
readonly pageX: number;
|
||||
readonly pageY: number;
|
||||
readonly screenX: number;
|
||||
readonly screenY: number;
|
||||
event?: Event;
|
||||
};
|
||||
|
||||
export class ObservablesMixin {
|
||||
$!: {
|
||||
mouseEvents: Observable<boolean>;
|
||||
preventDefault: Observable<boolean>;
|
||||
}
|
||||
$!: {
|
||||
mouseEvents: Observable<boolean>;
|
||||
preventDefault: Observable<boolean>;
|
||||
};
|
||||
|
||||
threshold!: number;
|
||||
noScroll!: boolean;
|
||||
threshold!: number;
|
||||
noScroll!: boolean;
|
||||
|
||||
getStartObservable() {
|
||||
return combineLatest([this.$.mouseEvents]).pipe(
|
||||
switchMap(([mouseEvents]) => {
|
||||
const touchstart$ = (<Observable<TouchEvent>>fromEvent(document, "touchstart", { passive: true })).pipe(
|
||||
filter(({ touches }) => touches.length === 1),
|
||||
map(({ touches }) => touches[0] as Coord)
|
||||
);
|
||||
getStartObservable() {
|
||||
return combineLatest([this.$.mouseEvents]).pipe(
|
||||
switchMap(([mouseEvents]) => {
|
||||
const touchstart$ = (<Observable<TouchEvent>>(
|
||||
fromEvent(document, "touchstart", { passive: true })
|
||||
)).pipe(
|
||||
filter(({ touches }) => touches.length === 1),
|
||||
map(({ touches }) => touches[0] as Coord),
|
||||
);
|
||||
|
||||
const mousedown$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>fromEvent(document, "mousedown")).pipe(
|
||||
map((e) => (((e as Coord).event = e), e as Coord)),
|
||||
);
|
||||
const mousedown$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>fromEvent(document, "mousedown")).pipe(
|
||||
map((e) => (((e as Coord).event = e), e as Coord)),
|
||||
);
|
||||
|
||||
return merge(touchstart$, mousedown$);
|
||||
})
|
||||
);
|
||||
}
|
||||
return merge(touchstart$, mousedown$);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getMoveObservable(start$: Observable<Coord>, end$: Observable<Coord>) {
|
||||
return combineLatest([this.$.mouseEvents, this.$.preventDefault]).pipe(
|
||||
switchMap(([mouseEvents, preventDefault]) => {
|
||||
const touchmove$ = (<Observable<TouchEvent>>fromEvent(document, "touchmove", { passive: !preventDefault })).pipe(
|
||||
map(e => (((e.touches[0] as Coord).event = e), e.touches[0] as Coord))
|
||||
);
|
||||
getMoveObservable(start$: Observable<Coord>, end$: Observable<Coord>) {
|
||||
return combineLatest([this.$.mouseEvents, this.$.preventDefault]).pipe(
|
||||
switchMap(([mouseEvents, preventDefault]) => {
|
||||
const touchmove$ = (<Observable<TouchEvent>>(
|
||||
fromEvent(document, "touchmove", { passive: !preventDefault })
|
||||
)).pipe(
|
||||
map(
|
||||
(e) => (((e.touches[0] as Coord).event = e), e.touches[0] as Coord),
|
||||
),
|
||||
);
|
||||
|
||||
const mousemove$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>fromEvent(document, "mousemove", { passive: !preventDefault })).pipe(
|
||||
subscribeWhen(merge(start$.pipe(mapTo(true)), end$.pipe(mapTo(false)))),
|
||||
map(e => (((e as Coord).event = e), e as Coord))
|
||||
);
|
||||
const mousemove$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>(
|
||||
fromEvent(document, "mousemove", { passive: !preventDefault })
|
||||
)).pipe(
|
||||
subscribeWhen(
|
||||
merge(start$.pipe(mapTo(true)), end$.pipe(mapTo(false))),
|
||||
),
|
||||
map((e) => (((e as Coord).event = e), e as Coord)),
|
||||
);
|
||||
|
||||
return merge(touchmove$, mousemove$);
|
||||
})
|
||||
);
|
||||
}
|
||||
return merge(touchmove$, mousemove$);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getEndObservable() {
|
||||
return combineLatest([this.$.mouseEvents]).pipe(
|
||||
switchMap(([mouseEvents]) => {
|
||||
const touchend$ = (<Observable<TouchEvent>>fromEvent(document, "touchend", { passive: true })).pipe(
|
||||
filter(({ touches }) => touches.length === 0),
|
||||
map(event => event.changedTouches[0] as Coord)
|
||||
);
|
||||
getEndObservable() {
|
||||
return combineLatest([this.$.mouseEvents]).pipe(
|
||||
switchMap(([mouseEvents]) => {
|
||||
const touchend$ = (<Observable<TouchEvent>>(
|
||||
fromEvent(document, "touchend", { passive: true })
|
||||
)).pipe(
|
||||
filter(({ touches }) => touches.length === 0),
|
||||
map((event) => event.changedTouches[0] as Coord),
|
||||
);
|
||||
|
||||
const mouseup$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>fromEvent(document, "mouseup", { passive: true })).pipe(
|
||||
map(e => (((e as Coord).event = e), e as Coord)),
|
||||
);
|
||||
const mouseup$ = !mouseEvents
|
||||
? NEVER
|
||||
: (<Observable<MouseEvent>>(
|
||||
fromEvent(document, "mouseup", { passive: true })
|
||||
)).pipe(map((e) => (((e as Coord).event = e), e as Coord)));
|
||||
|
||||
return merge(touchend$, mouseup$);
|
||||
})
|
||||
);
|
||||
}
|
||||
return merge(touchend$, mouseup$);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
getIsSlidingObservable(move$: Observable<Coord>, start$: Observable<Coord>, end$: Observable<Coord>) {
|
||||
return this.getIsSlidingObservableInner(move$, start$).pipe(
|
||||
take(1),
|
||||
startWith(undefined),
|
||||
repeatWhen(() => end$)
|
||||
);
|
||||
}
|
||||
getIsSlidingObservable(
|
||||
move$: Observable<Coord>,
|
||||
start$: Observable<Coord>,
|
||||
end$: Observable<Coord>,
|
||||
) {
|
||||
return this.getIsSlidingObservableInner(move$, start$).pipe(
|
||||
take(1),
|
||||
startWith(undefined),
|
||||
repeatWhen(() => end$),
|
||||
);
|
||||
}
|
||||
|
||||
getIsSlidingObservableInner(move$: Observable<Coord>, start$: Observable<Coord>) {
|
||||
if (this.threshold) {
|
||||
return move$.pipe(
|
||||
withLatestFrom(start$),
|
||||
skipWhile(
|
||||
([{ clientX, clientY }, { clientX: startX, clientY: startY }]) =>
|
||||
abs(startY - clientY) < this.threshold && abs(startX - clientX) < this.threshold
|
||||
),
|
||||
map(
|
||||
([{ clientX, clientY }, { clientX: startX, clientY: startY }]) =>
|
||||
abs(startX - clientX) >= abs(startY - clientY)
|
||||
)
|
||||
);
|
||||
} else {
|
||||
return move$.pipe(
|
||||
withLatestFrom(start$),
|
||||
map(([{ clientX, clientY, event }, { clientX: startX, clientY: startY }]) => {
|
||||
const isSliding = abs(startX - clientX) >= abs(startY - clientY);
|
||||
if (this.noScroll && isSliding && event) event.preventDefault();
|
||||
return isSliding;
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
getIsSlidingObservableInner(
|
||||
move$: Observable<Coord>,
|
||||
start$: Observable<Coord>,
|
||||
) {
|
||||
if (this.threshold) {
|
||||
return move$.pipe(
|
||||
withLatestFrom(start$),
|
||||
skipWhile(
|
||||
([{ clientX, clientY }, { clientX: startX, clientY: startY }]) =>
|
||||
abs(startY - clientY) < this.threshold &&
|
||||
abs(startX - clientX) < this.threshold,
|
||||
),
|
||||
map(
|
||||
([{ clientX, clientY }, { clientX: startX, clientY: startY }]) =>
|
||||
abs(startX - clientX) >= abs(startY - clientY),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return move$.pipe(
|
||||
withLatestFrom(start$),
|
||||
map(
|
||||
([
|
||||
{ clientX, clientY, event },
|
||||
{ clientX: startX, clientY: startY },
|
||||
]) => {
|
||||
const isSliding = abs(startX - clientX) >= abs(startY - clientY);
|
||||
if (this.noScroll && isSliding && event) event.preventDefault();
|
||||
return isSliding;
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { css } from 'lit';
|
||||
import { css } from "lit";
|
||||
|
||||
export const styles = css`
|
||||
@media screen {
|
||||
|
||||
@@ -1,68 +1,79 @@
|
||||
export type CallbackValue = { translateX: number, opacity: number };
|
||||
export type CallbackValue = { translateX: number; opacity: number };
|
||||
|
||||
export class UpdateMixin {
|
||||
contentEl!: HTMLElement;
|
||||
scrimEl!: HTMLElement;
|
||||
contentEl!: HTMLElement;
|
||||
scrimEl!: HTMLElement;
|
||||
|
||||
translateX!: number;
|
||||
side!: string;
|
||||
opacity!: number;
|
||||
translateX!: number;
|
||||
side!: string;
|
||||
opacity!: number;
|
||||
|
||||
updater!: DOMUpdater;
|
||||
updater!: DOMUpdater;
|
||||
|
||||
updateDOM(translateX: number, drawerWidth: number) {
|
||||
const inv = this.side === "left" ? 1 : -1;
|
||||
const opacity = (translateX / drawerWidth) * inv || 0;
|
||||
updateDOM(translateX: number, drawerWidth: number) {
|
||||
const inv = this.side === "left" ? 1 : -1;
|
||||
const opacity = (translateX / drawerWidth) * inv || 0;
|
||||
|
||||
this.translateX = translateX;
|
||||
this.opacity = opacity;
|
||||
this.translateX = translateX;
|
||||
this.opacity = opacity;
|
||||
|
||||
this.updater.updateDOM(translateX, opacity);
|
||||
}
|
||||
this.updater.updateDOM(translateX, opacity);
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class DOMUpdater {
|
||||
static getUpdaterForPlatform(parent: UpdateMixin) {
|
||||
const hasCSSOM = "attributeStyleMap" in Element.prototype && "CSS" in window && "number" in CSS;
|
||||
return hasCSSOM
|
||||
? new AttributeStyleMapUpdater(parent)
|
||||
: new StyleUpdater(parent);
|
||||
}
|
||||
static getUpdaterForPlatform(parent: UpdateMixin) {
|
||||
const hasCSSOM =
|
||||
"attributeStyleMap" in Element.prototype &&
|
||||
"CSS" in window &&
|
||||
"number" in CSS;
|
||||
return hasCSSOM
|
||||
? new AttributeStyleMapUpdater(parent)
|
||||
: new StyleUpdater(parent);
|
||||
}
|
||||
|
||||
private parent: UpdateMixin;
|
||||
constructor(parent: UpdateMixin) {
|
||||
this.parent = parent;
|
||||
}
|
||||
get contentEl() { return this.parent.contentEl }
|
||||
get scrimEl() { return this.parent.scrimEl }
|
||||
private parent: UpdateMixin;
|
||||
constructor(parent: UpdateMixin) {
|
||||
this.parent = parent;
|
||||
}
|
||||
get contentEl() {
|
||||
return this.parent.contentEl;
|
||||
}
|
||||
get scrimEl() {
|
||||
return this.parent.scrimEl;
|
||||
}
|
||||
|
||||
abstract updateDOM(translateX: number, opacity: number): void;
|
||||
abstract updateDOM(translateX: number, opacity: number): void;
|
||||
}
|
||||
|
||||
export class StyleUpdater extends DOMUpdater {
|
||||
constructor(parent: UpdateMixin) { super(parent); }
|
||||
constructor(parent: UpdateMixin) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
updateDOM(translateX: number, opacity: number) {
|
||||
this.contentEl.style.transform = `translate(${translateX}px, 0px)`;
|
||||
this.scrimEl.style.opacity = `${opacity}`;
|
||||
}
|
||||
updateDOM(translateX: number, opacity: number) {
|
||||
this.contentEl.style.transform = `translate(${translateX}px, 0px)`;
|
||||
this.scrimEl.style.opacity = `${opacity}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class AttributeStyleMapUpdater extends DOMUpdater {
|
||||
private tvalue: CSSTransformValue;
|
||||
private ovalue: CSSUnitValue;
|
||||
private tvalue: CSSTransformValue;
|
||||
private ovalue: CSSUnitValue;
|
||||
|
||||
constructor(parent: UpdateMixin) {
|
||||
super(parent);
|
||||
this.tvalue = new CSSTransformValue([new CSSTranslate(CSS.px(0), CSS.px(0))]);
|
||||
this.ovalue = CSS.number(1);
|
||||
}
|
||||
constructor(parent: UpdateMixin) {
|
||||
super(parent);
|
||||
this.tvalue = new CSSTransformValue([
|
||||
new CSSTranslate(CSS.px(0), CSS.px(0)),
|
||||
]);
|
||||
this.ovalue = CSS.number(1);
|
||||
}
|
||||
|
||||
updateDOM(translateX: number, opacity: number) {
|
||||
((this.tvalue[0] as CSSTranslate).x as CSSUnitValue).value = translateX;
|
||||
this.ovalue.value = opacity;
|
||||
updateDOM(translateX: number, opacity: number) {
|
||||
((this.tvalue[0] as CSSTranslate).x as CSSUnitValue).value = translateX;
|
||||
this.ovalue.value = opacity;
|
||||
|
||||
this.contentEl.attributeStyleMap.set("transform", this.tvalue);
|
||||
this.scrimEl.attributeStyleMap.set("opacity", this.ovalue);
|
||||
}
|
||||
}
|
||||
this.contentEl.attributeStyleMap.set("transform", this.tvalue);
|
||||
this.scrimEl.attributeStyleMap.set("opacity", this.ovalue);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
},
|
||||
"include": [
|
||||
"typings/**/*.ts",
|
||||
"src/**/*.ts",
|
||||
],
|
||||
}
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true
|
||||
},
|
||||
"include": ["typings/**/*.ts", "src/**/*.ts"]
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
type Constructor<T> = {
|
||||
new (...args: unknown[]): T
|
||||
new (...args: unknown[]): T;
|
||||
};
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassDescriptor {
|
||||
kind: 'class';
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
kind: "class";
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
}
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassElement {
|
||||
kind: 'field'|'method';
|
||||
key: PropertyKey;
|
||||
placement: 'static'|'prototype'|'own';
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
kind: "field" | "method";
|
||||
key: PropertyKey;
|
||||
placement: "static" | "prototype" | "own";
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
|
||||
@@ -1,69 +1,69 @@
|
||||
{
|
||||
"name": "@hydecorp/push-state",
|
||||
"version": "1.0.0",
|
||||
"description": "Turn static web sites into dynamic web apps",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hy-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hy-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hy-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/resize-observer-browser": "^0.1.7"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/hydecorp/push-state.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/hydecorp/push-state/issues"
|
||||
},
|
||||
"homepage": "https://hydecorp.github.io/push-state/",
|
||||
"keywords": [
|
||||
"page-transitions",
|
||||
"ajax",
|
||||
"pjax",
|
||||
"smoothstate",
|
||||
"pivoine",
|
||||
"vanilla",
|
||||
"jquery",
|
||||
"animations",
|
||||
"rxjs",
|
||||
"vanilla-js",
|
||||
"custom-element",
|
||||
"jquery-plugin",
|
||||
"history-api",
|
||||
"web-components",
|
||||
"webcomponent",
|
||||
"history-management",
|
||||
"prefetch",
|
||||
"page-loader",
|
||||
"prefetcher",
|
||||
"reactive"
|
||||
]
|
||||
"name": "@hydecorp/push-state",
|
||||
"version": "1.0.0",
|
||||
"description": "Turn static web sites into dynamic web apps",
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"module": "lib/index.js",
|
||||
"files": [
|
||||
"src",
|
||||
"lib",
|
||||
"module",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rm -rf lib module",
|
||||
"test": "exit 0",
|
||||
"build:tsc": "tsc -d",
|
||||
"watch:tsc": "tsc -d -w",
|
||||
"build:rollup": "rollup -c",
|
||||
"watch:rollup": "rollup -c -w",
|
||||
"build": "pnpm run build:tsc & pnpm run build:rollup & wait",
|
||||
"watch": "pnpm run watch:tsc & pnpm run watch:rollup",
|
||||
"serve": "serve -l 3337",
|
||||
"dev": "pnpm run watch & pnpm run serve",
|
||||
"preversion": "sed -i '' -E 's:^(lib|docs/assets/hy-\\*)$:#<removed temporarily>\\1:' .gitignore",
|
||||
"version": "pnpm run build && git add .",
|
||||
"postversion": "sed -i '' -E 's:^#<removed temporarily>(lib|docs/assets/hy-\\*)$:\\1:' .gitignore && git rm --cached -r lib docs/assets/hy-* && git add . && git commit -m 'Restore preversion .gitignore'",
|
||||
"prepack": "pnpm run clean && pnpm run build"
|
||||
},
|
||||
"author": "Florian Klampfer <mail@qwtel.com> (https://qwtel.com/)",
|
||||
"license": "GPL-3.0",
|
||||
"dependencies": {
|
||||
"@hydecorp/component": "^1.0.0",
|
||||
"@types/resize-observer-browser": "^0.1.7"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/hydecorp/push-state.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/hydecorp/push-state/issues"
|
||||
},
|
||||
"homepage": "https://hydecorp.github.io/push-state/",
|
||||
"keywords": [
|
||||
"page-transitions",
|
||||
"ajax",
|
||||
"pjax",
|
||||
"smoothstate",
|
||||
"pivoine",
|
||||
"vanilla",
|
||||
"jquery",
|
||||
"animations",
|
||||
"rxjs",
|
||||
"vanilla-js",
|
||||
"custom-element",
|
||||
"jquery-plugin",
|
||||
"history-api",
|
||||
"web-components",
|
||||
"webcomponent",
|
||||
"history-management",
|
||||
"prefetch",
|
||||
"page-loader",
|
||||
"prefetcher",
|
||||
"reactive"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import terser from '@rollup/plugin-terser';
|
||||
import resolve from "@rollup/plugin-node-resolve";
|
||||
import commonjs from "@rollup/plugin-commonjs";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
|
||||
export default [
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hy-push-state.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: 'es',
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
{
|
||||
input: "src/index.ts",
|
||||
output: [
|
||||
{
|
||||
file: `docs/assets/hy-push-state.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
{
|
||||
file: `module/index.js`,
|
||||
format: "es",
|
||||
sourcemap: true,
|
||||
},
|
||||
],
|
||||
plugins: [typescript(), resolve(), commonjs(), terser()],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true,
|
||||
},
|
||||
"include": [
|
||||
"typings/**/*.ts",
|
||||
"src/**/*.ts",
|
||||
],
|
||||
}
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"moduleResolution": "Node",
|
||||
"module": "ES2020",
|
||||
"target": "ES2018",
|
||||
"outDir": "lib",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"inlineSources": true,
|
||||
"strict": true,
|
||||
"importHelpers": true
|
||||
},
|
||||
"include": ["typings/**/*.ts", "src/**/*.ts"]
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
type Constructor<T> = {
|
||||
new (...args: unknown[]): T
|
||||
new (...args: unknown[]): T;
|
||||
};
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassDescriptor {
|
||||
kind: 'class';
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
kind: "class";
|
||||
elements: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
}
|
||||
|
||||
// From the TC39 Decorators proposal
|
||||
interface ClassElement {
|
||||
kind: 'field'|'method';
|
||||
key: PropertyKey;
|
||||
placement: 'static'|'prototype'|'own';
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
kind: "field" | "method";
|
||||
key: PropertyKey;
|
||||
placement: "static" | "prototype" | "own";
|
||||
initializer?: Function;
|
||||
extras?: ClassElement[];
|
||||
finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
|
||||
descriptor?: PropertyDescriptor;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user