hy-push-state
Version:
Turn static web sites into dynamic web apps
241 lines (179 loc) • 13.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setupObservablesMixin = void 0;
var _esm = require("rxjs/_esm5");
var _operators = require("rxjs/_esm5/operators");
var _url = require("../url");
var _constants = require("./constants");
var _operators2 = require("./operators");
var _methods = require("./methods");
var _history = require("./history");
var _fetching = require("./fetching");
var _update = require("./update");
var _events = require("./events");
var _eventListeners = require("./event-listeners");
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var setupObservablesMixin = function setupObservablesMixin(C) {
return /*#__PURE__*/function (_eventListenersMixin) {
_inherits(_class, _eventListenersMixin);
var _super = _createSuper(_class);
function _class() {
_classCallCheck(this, _class);
return _super.apply(this, arguments);
}
_createClass(_class, [{
key: "compareContext",
// A compare function for contexts, used in combination with `distinctUntilChanged`.
// We use `cacheNr` as it is a convenient (hacky) way of circumventing
// `distinctUntilChanged` when retrying requests.
value: function compareContext(p, q) {
return p.url.href === q.url.href && p.error === q.error && p.cacheNr === q.cacheNr;
} // ### Setup observable
// This functions sets up the core observable pipeline of this component.
}, {
key: "setupObservables",
value: function setupObservables() {
var _this = this;
this.cacheNr = 1; // For now, we take for granted that we have a stream of all `PUSH` events (loading a new page by
// clicking on a link) and `HINT` events (probable click on a link) which are `pushSubject` and
// `hintSubject` respectively.
this.pushSubject = new _esm.Subject();
this.hintSubject = new _esm.Subject(); // TODO: doc
var push$ = this.pushSubject.pipe((0, _operators.takeUntil)(this.subjects.disconnect), (0, _operators.map)(function (event) {
return {
type: _constants.PUSH,
url: new _url.URL(event.currentTarget.href, _this.href),
anchor: event.currentTarget,
event: event,
cacheNr: _this.cacheNr
};
}), (0, _operators.filter)(this.isPushEvent.bind(this)), (0, _operators.tap)(function (_ref) {
var event = _ref.event;
event.preventDefault();
_this.saveScrollPosition();
})); // In additon to `HINT` and `PUSH` events, there's also `POP` events, which are caused by
// modifying the browser history, e.g. clicking the back button, etc.
var pop$ = (0, _esm.fromEvent)(window, "popstate").pipe((0, _operators.takeUntil)(this.subjects.disconnect), (0, _operators.filter)(function () {
return window.history.state && window.history.state[_this.histId()];
}), (0, _operators.map)(function (event) {
return {
type: _constants.POP,
url: new _url.URL(window.location, _this.href),
event: event,
cacheNr: _this.cacheNr
};
}));
var reload$ = this.reload$.pipe((0, _operators.takeUntil)(this.subjects.disconnect)); // TODO: doc
var _merge$pipe$map = (0, _esm.merge)(push$, pop$, reload$).pipe((0, _operators.startWith)({
url: new _url.URL(this.initialHref)
}), // HACK: make hy-push-state mimic window.location?
(0, _operators.tap)(function (_ref2) {
var url = _ref2.url;
return _this._url = url;
}), (0, _operators.pairwise)(), (0, _operators.share)(), (0, _operators.partition)(this.isHashChange)).map(function (obs$) {
return obs$.pipe((0, _operators.map)(function (_ref3) {
var _ref4 = _slicedToArray(_ref3, 2),
x = _ref4[1];
return x;
}), (0, _operators.share)());
}),
_merge$pipe$map2 = _slicedToArray(_merge$pipe$map, 2),
hash$ = _merge$pipe$map2[0],
page$ = _merge$pipe$map2[1]; // TODO: doc
var hint$ = this.subjects.prefetch.pipe((0, _operators.switchMap)(function (prefetch) {
if (!prefetch) return _esm.NEVER; // We don't want to prefetch (i.e. use bandwidth) for a _possible_ page load,
// while a _certain_ page load is going on.
// The `pauser$` observable let's us achieve this.
// Needs to be deferred b/c of "cyclical" dependency.
var pauser$ = (0, _esm.defer)(function () {
return (// A page change event means we want to pause prefetching, while
// a response event means we want to resume prefetching.
(0, _esm.merge)(page$.pipe((0, _operators.mapTo)(true)), _this.fetch$.pipe((0, _operators.mapTo)(false)))
);
}) // Start with `false`, i.e. we want the prefetch pipelien to be active
.pipe((0, _operators.startWith)(false), (0, _operators.share)());
return _this.hintSubject.pipe((0, _operators.takeUntil)(_this.subjects.disconnect), (0, _operators2.unsubscribeWhen)(pauser$), (0, _operators.map)(function (event) {
return {
type: _constants.HINT,
url: new _url.URL(event.currentTarget.href, _this.href),
anchor: event.currentTarget,
event: event,
cacheNr: _this.cacheNr
};
}), (0, _operators.filter)(_this.isHintEvent.bind(_this)));
})); // The stream of (pre-)fetch events.
// Includes definitive page change events do deal with unexpected page changes.
var prefetch$ = (0, _esm.merge)(hint$, page$).pipe( // Don't abort a request if the user "jiggles" over a link
(0, _operators.distinctUntilChanged)(this.compareContext.bind(this)), (0, _operators.switchMap)(this.makeRequest.bind(this)), // Start with some value so `withLatestFrom` below doesn't "block"
(0, _operators.startWith)({
url: {}
}), (0, _operators.share)()); // TODO: doc
this.fetch$ = page$.pipe((0, _operators.tap)(function (context) {
_this.updateHistoryState(context);
_this.onStart(context);
}), (0, _operators.withLatestFrom)(prefetch$), (0, _operators.switchMap)(this.getResponse.bind(this, prefetch$)), (0, _operators.share)()); // TODO: doc
var _this$fetch$$pipe = this.fetch$.pipe((0, _operators.partition)(function (_ref5) {
var error = _ref5.error;
return !error;
})),
_this$fetch$$pipe2 = _slicedToArray(_this$fetch$$pipe, 2),
fetchOk$ = _this$fetch$$pipe2[0],
fetchError$ = _this$fetch$$pipe2[1]; // TODO: doc
var main$ = fetchOk$.pipe((0, _operators.map)(this.responseToContent.bind(this)), (0, _operators.tap)(function (context) {
_this.onReady(context);
_this.updateDOM(context);
_this.onAfter(context);
_this.manageScrollPostion(context);
}), (0, _operators.tap)({
error: function error(e) {
return _this.onDOMError(e);
}
}), (0, _operators.catchError)(function (e, c) {
return c;
}), // If the experimental script feature is enabled,
// scripts tags have been stripped from the content,
// and this is where we insert them again.
(0, _operators.switchMap)(this.reinsertScriptTags.bind(this)), (0, _operators.tap)({
error: function error(e) {
return _this.onError(e);
}
}), (0, _operators.catchError)(function (e, c) {
return c;
})); // #### Subscriptions
// Subscribe to main observables.
main$.subscribe(this.onLoad.bind(this)); // Subscribe to hash observables.
hash$.subscribe(function (context) {
_this.updateHistoryStateHash(context);
_this.manageScrollPostion(context);
}); // Subscribe to the fetch error branch.
fetchError$.subscribe(this.onNetworkError.bind(this)); // Fire `progress` event when fetching takes longer than expected.
page$.pipe((0, _operators.switchMap)(function (context) {
return (0, _esm.defer)(function () {
return _this.animPromise;
}).pipe((0, _operators.takeUntil)(_this.fetch$), (0, _operators.mapTo)(context));
})).subscribe(this.onProgress.bind(this)); // TODO: doc
this.setupEventListeners();
}
}]);
return _class;
}((0, _eventListeners.eventListenersMixin)((0, _events.eventMixin)((0, _update.updateMixin)((0, _fetching.fetchMixin)((0, _history.historyMixin)((0, _methods.helperMixin)(C)))))));
};
exports.setupObservablesMixin = setupObservablesMixin;