@bye_past/vue-keep
Version:
缓存你的页面组件, 使得可以比手机APP更好的体验效果
1,296 lines (1,263 loc) • 50.4 kB
JavaScript
import * as Vue from 'vue';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var asyncToGenerator = {exports: {}};
(function (module) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(asyncToGenerator));
var _asyncToGenerator = getDefaultExportFromCjs(asyncToGenerator.exports);
var regeneratorRuntime$1 = {exports: {}};
var _typeof$1 = {exports: {}};
(function (module) {
function _typeof(obj) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(_typeof$1));
var _typeof = getDefaultExportFromCjs(_typeof$1.exports);
(function (module) {
var _typeof = _typeof$1.exports["default"];
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
return exports;
}, module.exports.__esModule = true, module.exports["default"] = module.exports;
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function define(obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) {
if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
}
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function reset(skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) {
"t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
}
},
stop: function stop() {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function dispatchException(exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function abrupt(type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function complete(record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function finish(finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
"catch": function _catch(tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function delegateYield(iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(regeneratorRuntime$1));
getDefaultExportFromCjs(regeneratorRuntime$1.exports);
var runtime = regeneratorRuntime$1.exports();
var regenerator = runtime;
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
if (typeof globalThis === "object") {
globalThis.regeneratorRuntime = runtime;
} else {
Function("r", "regeneratorRuntime = r")(runtime);
}
}
var KEEP_BEFORE_ROUTE_CHANGE = 'KEEP_BEFORE_ROUTE_CHANGE';
var KEEP_ROUTE_CHANGE = 'KEEP_ROUTE_CHANGE';
var KEEP_COMPONENT_DESTROY = 'KEEP_COMPONENT_DESTROY';
var KEEP_SUBSCRIBE_COMPLETE = 'KEEP_SUBSCRIBE_COMPLETE';
var DESTROY_ALL = 'ALL';
function useCallbacks() {
var handlers = [];
function add(name, handler) {
var obj = typeof name === 'function' ? name : {
name: name,
handler: handler
};
handlers.push(obj);
return function () {
var i = handlers.indexOf(obj);
if (i > -1) {
handlers.splice(i, 1);
}
};
}
function reset() {
handlers = [];
}
return {
add: add,
list: function list() {
return handlers;
},
reset: reset
};
}
function stripBase(pathname, base) {
if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) return pathname;
return pathname.slice(base.length) || '/';
}
function createCurrentLocation(base) {
var _location = location,
pathname = _location.pathname,
search = _location.search,
hash = _location.hash;
var hashPos = base.indexOf('#');
if (hashPos > -1) {
var slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1;
var pathFromHash = hash.slice(slicePos);
if (pathFromHash[0] !== '/') {
pathFromHash = '/' + pathFromHash;
}
return stripBase(pathFromHash, '');
}
var path = stripBase(pathname, base);
return (path + search + hash).replace(/^\/#/, '');
}
function getAbsolutePath() {
var _window$location = window.location,
protocol = _window$location.protocol,
host = _window$location.host,
href = _window$location.href;
var protocolAndPath = protocol + '//' + host;
return href.replace(protocolAndPath, '');
}
function getBase(router) {
var _router$options$histo;
var base;
if (router.mode) {
base = router.options.base;
return base;
}
base = (_router$options$histo = router.options.history) === null || _router$options$histo === void 0 ? void 0 : _router$options$histo.base;
if (!base && location.hash) {
base = location.pathname;
}
return base || '/';
}
function toLocationResolve(router, to) {
typeof to === 'string' && (to = {
path: to
});
if (to.path && !/^\//.test(to.path)) {
to.path = '/' + to.path;
}
var toLocation = router.resolve(to);
if (toLocation.resolved) {
toLocation = toLocation.resolved;
}
return toLocation;
}
function getToLocation(router) {
var base = getBase(router);
var path = createCurrentLocation(base);
var toLocation = toLocationResolve(router, path);
return toLocation;
}
function decode(text) {
try {
return decodeURIComponent('' + text);
} catch (err) {
console.warn("Error decoding \"".concat(text, "\". Using original value"));
}
return '' + text;
}
function parseQuery(search) {
var query = {};
if (search === '' || search === '?') return query;
var hasLeadingIM = search[0] === '?';
var searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
for (var i = 0; i < searchParams.length; ++i) {
var searchParam = searchParams[i].replace(/\+/g, ' ');
var eqPos = searchParam.indexOf('=');
var key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
var value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
if (key in query) {
var currentValue = query[key];
if (!Array.isArray(currentValue)) {
currentValue = query[key] = [currentValue];
}
currentValue.push(value);
} else {
query[key] = value;
}
}
return query;
}
var assign = Object.assign;
var toConsumableArray = {exports: {}};
var arrayWithoutHoles = {exports: {}};
var arrayLikeToArray = {exports: {}};
(function (module) {
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;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(arrayLikeToArray));
getDefaultExportFromCjs(arrayLikeToArray.exports);
(function (module) {
var arrayLikeToArray$1 = arrayLikeToArray.exports;
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray$1(arr);
}
module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(arrayWithoutHoles));
getDefaultExportFromCjs(arrayWithoutHoles.exports);
var iterableToArray = {exports: {}};
(function (module) {
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(iterableToArray));
getDefaultExportFromCjs(iterableToArray.exports);
var unsupportedIterableToArray = {exports: {}};
(function (module) {
var arrayLikeToArray$1 = arrayLikeToArray.exports;
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return arrayLikeToArray$1(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$1(o, minLen);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(unsupportedIterableToArray));
getDefaultExportFromCjs(unsupportedIterableToArray.exports);
var nonIterableSpread = {exports: {}};
(function (module) {
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(nonIterableSpread));
getDefaultExportFromCjs(nonIterableSpread.exports);
(function (module) {
var arrayWithoutHoles$1 = arrayWithoutHoles.exports;
var iterableToArray$1 = iterableToArray.exports;
var unsupportedIterableToArray$1 = unsupportedIterableToArray.exports;
var nonIterableSpread$1 = nonIterableSpread.exports;
function _toConsumableArray(arr) {
return arrayWithoutHoles$1(arr) || iterableToArray$1(arr) || unsupportedIterableToArray$1(arr) || nonIterableSpread$1();
}
module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
}(toConsumableArray));
var _toConsumableArray = getDefaultExportFromCjs(toConsumableArray.exports);
function resetComponentsName(router, isChildren) {
var _router$constructor$v;
var routerVersion = (_router$constructor$v = router.constructor.version) === null || _router$constructor$v === void 0 ? void 0 : _router$constructor$v.replace(/\.(\d+)$/, '$1');
if (routerVersion < 3.5) {
console.error('vue-keep: vue-router version is lower than 3.5.0, please upgrade vue-router');
return;
}
var routes = isChildren ? router : router.getRoutes();
routes.forEach(function (route) {
var _route$components, _route$children;
if (!(route !== null && route !== void 0 && (_route$components = route.components) !== null && _route$components !== void 0 && _route$components.default)) return;
if (((_route$children = route.children) === null || _route$children === void 0 ? void 0 : _route$children.length) > 0) {
resetComponentsName(route.children, true);
}
if (typeof route.components.default === 'function') {
var oldComponent = route.components.default;
return route.components.default = _asyncToGenerator( regenerator.mark(function _callee() {
var newComponent, _ref2, isOnly;
return regenerator.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return oldComponent();
case 2:
newComponent = _context.sent;
_ref2 = Object.getOwnPropertyDescriptor(newComponent.default, 'name') || {
writable: true
}, isOnly = _ref2.writable;
newComponent.default._canCoveredName = isOnly;
isOnly && (newComponent.default.name = route.name);
if (isOnly && !route.name) {
console.error('vue-keep: this component is not cached, did you forget to set the name in the route?');
}
return _context.abrupt("return", newComponent);
case 8:
case "end":
return _context.stop();
}
}
}, _callee);
}));
}
route.components.default.name = route.name;
});
}
function getBaseOptions() {
var extendList = ['push', 'replace', 'go', 'back', 'forward'];
var obj = Object.create(null);
return {
extendList: extendList,
obj: obj
};
}
function addRoute(router) {
var routerPrototype = router.constructor.prototype;
var oldAddRoute = router.addRoute;
if (routerPrototype.addRoute) {
oldAddRoute = routerPrototype.addRoute;
return routerPrototype.addRoute = newAddRoute;
}
router.addRoute = newAddRoute;
var waiting = false;
function newAddRoute() {
var _oldAddRoute;
(_oldAddRoute = oldAddRoute).call.apply(_oldAddRoute, [this].concat(Array.prototype.slice.call(arguments)));
if (!waiting) {
waiting = true;
Promise.resolve().then(function () {
resetComponentsName(router);
});
}
}
}
var isJump;
function jump(router, callback) {
return function () {
var _router$type;
var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref3$type = _ref3.type,
type = _ref3$type === void 0 ? 'push' : _ref3$type;
isJump = true;
if (typeof arguments[0] === 'number') {
var params = arguments[1];
if (_typeof(params) !== 'object') return;
type = params.type || 'go';
callback(type, assign({
delta: arguments[0] || 0
}, params));
router[params.type || 'go'].call(this, arguments[0] || 0);
return isJump = false;
}
callback(type, arguments[0]);
(_router$type = router[type]).call.apply(_router$type, [this].concat(Array.prototype.slice.call(arguments)));
isJump = false;
};
}
function router3x(router, callback) {
var _getBaseOptions = getBaseOptions(),
extendList = _getBaseOptions.extendList,
obj = _getBaseOptions.obj;
var historyPrototype = router.history.constructor.prototype;
var routerPrototype = router.constructor.prototype;
addRoute(router);
routerPrototype.jump = jump(router, callback);
extendList.forEach(function (key) {
obj[key] = historyPrototype[key] || function () {
return historyPrototype.go(1);
};
historyPrototype[key] = function () {
var _arguments = arguments,
_this = this;
isJump || callback.apply(void 0, [key].concat(Array.prototype.slice.call(arguments)));
new Promise(function (resolve) {
return resolve();
}).then(function () {
var _obj$key;
return (_obj$key = obj[key]).call.apply(_obj$key, [_this].concat(_toConsumableArray(_arguments)));
});
};
});
return router;
}
function router4x(router, callback) {
var _getBaseOptions2 = getBaseOptions(),
extendList = _getBaseOptions2.extendList,
obj = _getBaseOptions2.obj;
addRoute(router);
router.jump = jump(router, callback);
extendList.forEach(function (key) {
obj[key] = router[key];
router[key] = function (to) {
isJump || callback.apply(void 0, [key].concat(Array.prototype.slice.call(arguments)));
return obj[key](to);
};
});
}
var replaceState = 'replaceState';
var pushState = 'pushState';
var push = 'push';
var replace = 'replace';
var forward = 'forward';
var go = 'go';
var back = 'back';
var POPSTATE = 'popstate';
var RouterJumpMethods = {
push: push,
replace: replace,
go: go,
forward: forward,
back: back
};
var HistoryJumpMethods = {
replaceState: replaceState,
pushState: pushState,
go: go,
forward: forward,
back: back
};
var NavigationDirection = {
back: back,
forward: forward
};
var historyRecord = JSON.parse(sessionStorage.getItem('keep_history_record') || '[]');
function handleHistoryRecord(toLocation, method) {
var keepPosition = history.state.keepPosition;
var path = toLocation.fullPath || toLocation.path;
historyRecord[keepPosition] = path;
if (method === HistoryJumpMethods.pushState) {
historyRecord.push(path);
historyRecord = historyRecord.slice(0, keepPosition + 1);
}
sessionStorage.setItem('keep_history_record', JSON.stringify(historyRecord));
}
var _history$state;
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
var beforeGuards = useCallbacks();
var $router;
var keepPosition = ((_history$state = history.state) === null || _history$state === void 0 ? void 0 : _history$state.keepPosition) || history.length - 1;
var prevPosition = keepPosition;
var isEmptyJump;
var to;
var from = Object.create(null);
var isRouter4xPush;
var isPopstateBack;
var isBeforeRouterChange;
var beforeState = Object.create(null);
var init = true;
window.addEventListener(POPSTATE, function (ev) {
keepPosition = ev.state.keepPosition;
var direction = keepPosition <= prevPosition ? NavigationDirection.back : NavigationDirection.forward;
var absolutePath = getAbsolutePath();
direction === NavigationDirection.back && (isPopstateBack = true);
history.replaceState(history.state, absolutePath);
prevPosition = keepPosition;
});
function historyJumpExtend(router) {
$router = router;
var _history$constructor$ = history.constructor.prototype,
back = _history$constructor$.back,
forward = _history$constructor$.forward,
go = _history$constructor$.go,
pushState = _history$constructor$.pushState,
replaceState = _history$constructor$.replaceState;
var historyJumpMethods = {
back: back,
forward: forward,
go: go,
pushState: pushState,
replaceState: replaceState
};
var hijackList = Object.keys(historyJumpMethods);
var absolutePath = getAbsolutePath();
history.replaceState(buildState(keepPosition, HistoryJumpMethods.replaceState), absolutePath);
routerChange(NavigationDirection.forward, POPSTATE);
isBeforeRouterChange = true;
if (router.constructor.version) {
Promise.resolve().then(function () {
return routerChange(NavigationDirection.forward, POPSTATE);
});
}
function getToLocation(position, method) {
var _to2, _to3;
var toLocation;
if ([RouterJumpMethods.go, RouterJumpMethods.forward, RouterJumpMethods.back].includes(method)) {
to = assign({}, to);
to.path = historyRecord[position];
return toLocation = to;
}
if ((_to2 = to) !== null && _to2 !== void 0 && _to2.name || (_to3 = to) !== null && _to3 !== void 0 && _to3.path) {
toLocation = toLocationResolve($router, to);
}
if (!toLocation) {
var base = getBase($router);
toLocation = {
path: createCurrentLocation(base)
};
}
return toLocation;
}
function buildState(position, method, isBack) {
var _beforeState;
var toLocation = getToLocation(position, method);
var path = toLocation.fullPath || toLocation.path;
var temporaryHistoryStack = Array.from(historyRecord);
if ([HistoryJumpMethods.pushState, RouterJumpMethods.push].includes(method)) {
temporaryHistoryStack[position] = path;
temporaryHistoryStack = historyRecord.slice(0, position);
}
var current = ([RouterJumpMethods.forward, HistoryJumpMethods.pushState, RouterJumpMethods.push].includes(method) ? historyRecord[position - 1] : historyRecord[position]) || path;
var keepBack = historyRecord[position - 1];
if (isPopstateBack && historyRecord.length > history.length) {
if (method === RouterJumpMethods.replace) {
var maxBrowserHistory = historyRecord.map(function (path, index) {
return index < keepPosition ? null : path;
});
keepBack = maxBrowserHistory[position - 1];
}
var positionOffset = Math.abs(historyRecord.length - history.length - keepPosition);
!historyRecord[positionOffset - 1] && (keepBack = null);
}
return {
keepPosition: position,
keepBack: keepBack,
keepCurrent: current,
keepNext: path,
keepForward: temporaryHistoryStack[position + 1],
keepReplace: !!((_beforeState = beforeState) !== null && _beforeState !== void 0 && _beforeState.keepReplace),
keepDirection: isBack ? NavigationDirection.back : NavigationDirection.forward
};
}
hijackList.forEach(function (key) {
return hijackHistoryMethod(key);
});
function hijackHistoryMethod(key) {
history.constructor.prototype[key] = function () {
var _historyJumpMethods$k2;
prevPosition = keepPosition;
if (isEmptyJump) return;
switch (key) {
case HistoryJumpMethods.pushState:
case RouterJumpMethods.forward:
keepPosition = keepPosition + 1;
break;
case RouterJumpMethods.go:
keepPosition = keepPosition + arguments[0];
break;
case RouterJumpMethods.back:
keepPosition = keepPosition - 1;
}
if ([RouterJumpMethods.go, RouterJumpMethods.forward, RouterJumpMethods.back].includes(key)) {
var _historyJumpMethods$k;
(_historyJumpMethods$k = historyJumpMethods[key]).call.apply(_historyJumpMethods$k, [this].concat(Array.prototype.slice.call(arguments)));
return;
}
var state = buildState(keepPosition, key, isPopstateBack);
arguments[0] = assign(arguments[0], state);
(_historyJumpMethods$k2 = historyJumpMethods[key]).call.apply(_historyJumpMethods$k2, [this].concat(Array.prototype.slice.call(arguments)));
if ([HistoryJumpMethods.pushState, HistoryJumpMethods.replaceState].includes(key)) {
if (isRouter4xPush && key === HistoryJumpMethods.replaceState) return;
routerChange(isPopstateBack ? NavigationDirection.back : NavigationDirection.forward, key);
isBeforeRouterChange = false;
beforeState = null;
}
isPopstateBack = false;
isRouter4xPush = false;
};
}
function routerBeforeCallback(method, toLocation) {
var _from;
if (typeof toLocation === 'string') {
toLocation = {
path: toLocation
};
} else if (typeof toLocation === 'number') {
toLocation = {
delta: toLocation
};
}
to = assign({
method: method
}, toLocation);
if (to.path === ((_from = from) === null || _from === void 0 ? void 0 : _from.path)) return;
isBeforeRouterChange = true;
var isBack = method === RouterJumpMethods.back || to.delta < 0;
var direction = isBack ? NavigationDirection.back : NavigationDirection.forward;
var nextPosition;
isPopstateBack = !!isBack;
switch (method) {
case RouterJumpMethods.go:
nextPosition = keepPosition + to.delta;
break;
case RouterJumpMethods.replace:
nextPosition = keepPosition;
break;
default:
nextPosition = keepPosition + (isBack ? -1 : 1);
}
beforeState = buildState(nextPosition, method, isBack);
method === RouterJumpMethods.push && (isRouter4xPush = true);
method === RouterJumpMethods.replace && (beforeState.keepReplace = true);
beforeRouterChange(direction, method);
}
if (Object.prototype.hasOwnProperty.call(router, RouterJumpMethods.push)) {
return router4x(router, routerBeforeCallback);
}
return router3x(router, routerBeforeCallback);
}
function triggerBeforeEach(mergeToLocation) {
var _iterator = _createForOfIteratorHelper(beforeGuards.list()),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var guard = _step.value;
if (mergeToLocation.name === guard.name) {
guard.handler(mergeToLocation, from);
} else if (typeof guard === 'function') {
guard(mergeToLocation, from);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
function dispatch(_x, _x2, _x3) {
return _dispatch.apply(this, arguments);
}
function _dispatch() {
_dispatch = _asyncToGenerator( regenerator.mark(function _callee(eventName, direction, toLocation) {
var _to4;
var triggerType, state, existSearchReg, _beforeState$keepNext, query, mergeToLocation, options, componentName, _matcheds, matcheds, component, name, newComponent, event, listener;
return regenerator.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
toLocation = assign({}, toLocation);
if (eventName === KEEP_BEFORE_ROUTE_CHANGE) {
triggerType = 'beforeChange';
state = beforeState;
existSearchReg = /^.+\?/;
if (beforeState.keepNext && existSearchReg.test(beforeState.keepNext)) {
query = parseQuery((_beforeState$keepNext = beforeState.keepNext) === null || _beforeState$keepNext === void 0 ? void 0 : _beforeState$keepNext.replace(existSearchReg, ''));
toLocation.query = assign(query, toLocation.query);
}
} else {
triggerType = 'change';
state = history.state;
}
mergeToLocation = assign({
direction: direction,
triggerType: triggerType,
state: state
}, to, toLocation);
if (eventName === KEEP_BEFORE_ROUTE_CHANGE) {
triggerBeforeEach(mergeToLocation);
}
if (!isBeforeRouterChange) {
triggerBeforeEach(mergeToLocation);
}
options = Object.create(null);
if (init) {
_context.next = 17;
break;
}
matcheds = toLocation.matched;
component = (_matcheds = matcheds[matcheds.length - 1]) === null || _matcheds === void 0 ? void 0 : _matcheds.components.default;
if (!(component !== null && component !== void 0 && component.prototype)) {
_context.next = 17;
break;
}
name = component.name;
if (!(!component.name && eventName !== KEEP_BEFORE_ROUTE_CHANGE)) {
_context.next = 16;
break;
}
_context.next = 14;
return component();
case 14:
newComponent = _context.sent;
name = newComponent._canCoveredName ? null : newComponent.default.name;
case 16:
componentName = {
name: name
};
case 17:
options.detail = {
direction: direction,
destroy: mergeToLocation === null || mergeToLocation === void 0 ? void 0 : mergeToLocation.destroy,
cache: mergeToLocation === null || mergeToLocation === void 0 ? void 0 : mergeToLocation.cache,
constCache: (_to4 = to) === null || _to4 === void 0 ? void 0 : _to4.constCache,
toLocation: assign({}, toLocation, componentName)
};
event = new CustomEvent(eventName, options);
listener = function listener() {
return window.dispatchEvent(event);
};
listener();
window.addEventListener(KEEP_SUBSCRIBE_COMPLETE, listener);
setTimeout(function () {
window.removeEventListener(KEEP_SUBSCRIBE_COMPLETE, listener);
}, 300);
return _context.abrupt("return", mergeToLocation);
case 24:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _dispatch.apply(this, arguments);
}
function beforeRouterChange(direction, method) {
var _to = to;
if (!to.path && !to.name) {
var _keepPosition = history.state.keepPosition;
var index;
switch (method) {
case 'go':
index = _keepPosition + to.delta;
break;
case 'forward':
index = _keepPosition + 1;
break;
case 'back':
index = _keepPosition - 1;
break;
default:
index = _keepPosition;
}
_to = historyRecord[index];
if (!_to) {
console.warn('vue-keep:', 'empty jump');
isEmptyJump = true;
new Promise(function (resolve) {
return resolve();
}).then(function () {
return isEmptyJump = false;
});
return;
}
}
var toLocation = toLocationResolve($router, _to);
dispatch(KEEP_BEFORE_ROUTE_CHANGE, direction, toLocation);
}
function routerChange(_x4, _x5) {
return _routerChange.apply(this, arguments);
}
function _routerChange() {
_routerChange = _asyncToGenerator( regenerator.mark(function _callee2(direction, method) {
var toLocation, mergeToLocation;
return regenerator.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
toLocation = getToLocation($router);
_context2.next = 3;
return dispatch(KEEP_ROUTE_CHANGE, direction, toLocation);
case 3:
mergeToLocation = _context2.sent;
handleHistoryRecord(mergeToLocation, method);
from = mergeToLocation;
to = null;
init = false;
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return _routerChange.apply(this, arguments);
}
var extendRouter = (function (router) {
resetComponentsName(router);
historyJumpExtend(router);
});
function render2x() {
var vm = this;
var h = vm.$createElement;
var c = vm._self.c || h;
return c('keep-alive', {
attrs: {
include: [].concat(vm.includeList),
max: vm.max,
exclude: vm.exclude
}
}, [c('router-view')], 1);
}
function render3x(ctx, cache, props, setup, data) {
var _Vue = Vue;
var componentRouterView = _Vue.resolveComponent('router-view');
var openBlock = _Vue.openBlock;
var createBlock = _Vue.createBlock;
var withCtx = _Vue.withCtx;
var KeepAlive = _Vue.KeepAlive;
var resolveDynamicComponent = _Vue.resolveDynamicComponent;
return openBlock(), createBlock(componentRouterView, {
key: 0
}, {
default: withCtx(function (ref) {
var Component = ref.Component;
return [(openBlock(), createBlock(KeepAlive, {
include: data.includeList,
max: props.max,
exclude: props.exclude
}, [(openBlock(), createBlock(resolveDynamicComponent(Component)))], 1032, ['include', 'max', 'exclude']))];
}),
_: 1
});
}
var KeepRouterView = {
name: 'KeepRouteView',
render: function render() {
if (!this.vueNext) {
return render2x.call(this);
} else {
return render3x.apply(void 0, arguments);
}
},
props: {
max: {
type: Number,
default: 5
},
exclude: {
type: [Array, RegExp, String],
default: function _default() {
return [];
}
}
},
data: function data() {
return {
vueNext: Number(vueApp.version.slice(0, 3)) >= 3,
includeList: []
};
},
created: function created() {
this.isForward = false;
this.addEvents();
},
activated: function activated() {
this.addEvents();
},
deactivated: function deactivated() {
this.removeEvents();
},
beforeDestroy: function beforeDestroy() {
this.removeEvents();
},
beforeUnmount: function beforeUnmount() {
this.removeEvents();
},
methods: {
addEvents: function addEvents() {
window.addEventListener(KEEP_BEFORE_ROUTE_CHANGE, this.beforeRouteChangeEvent);
window.addEventListener(KEEP_ROUTE_CHANGE, this.routerChangeEvent);
window.addEventListener(KEEP_COMPONENT_DESTROY, this.componentDestroyEvent);
var event = new CustomEvent(KEEP_SUBSCRIBE_COMPLETE);
window.dispatchEvent(event);
},
removeEvents: function removeEvents() {
window.removeEventListener(KEEP_BEFORE_ROUTE_CHANGE, this.beforeRouteChangeEvent);
window.removeEventListener(KEEP_ROUTE_CHANGE, this.routerChangeEvent);
window.removeEventListener(KEEP_COMPONENT_DESTROY, this.componentDestroyEvent);
},
beforeRouteChangeEvent: function beforeRouteChangeEvent(params) {
var _this = this;
return _asyncToGenerator( regenerator.mark(function _callee() {
var _params$detail, direction, destroy, cache, constCache, toLocation;
return regenerator.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_params$detail = params.detail, direction = _params$detail.direction, destroy = _params$detail.destroy, cache = _params$detail.cache, constCache = _params$detail.constCache, toLocation = _params$detail.toLocation;
if (!(direction !== 'forward')) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
cache || constCache || _this.destroyTraverse(toLocation.name);
if (!(typeof destroy === 'string' && destroy === DESTROY_ALL)) {
_context.next = 6;
break;
}
return _context.abrupt("return", _this.includeList = []);
case 6:
_this.handelDestroy(destroy);
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}))();
},
routerChangeEvent: function routerChangeEvent(params) {
var _this2 = this;
var toLocation = params.detail.toLocation;
var matched = toLocation.matched;
matched.forEach(function (item) {
var _item$components;
var name = ((_item$components = item.components) === null || _item$components === void 0 ? void 0 : _item$components.default.name) || toLocation.name;
if (_this2.includeList.includes(name)) return;
name && _this2.forward(name);
});
if (!toLocation.name) {
console.warn('keep-router-view: Please pay attention to whether the router base path you configured is correct!');
}
},
componentDestroyEvent: function componentDestroyEvent(params) {
var destroy = params.detail;
if (destroy === DESTROY_ALL) {
return this.includeList = [];
}
this.handelDestroy(destroy);
},
forward: function forward(name) {
var includeList = this.includeList,
exclude = this.exclude;
if (exclude.includes(name)) return;
if (includeList.includes(name)) {
var index = includeList.indexOf(name);
includeList.splice(index, 1);
}
if (includeList.length === this.max) {
includeList.splice(0, 1);
}
includeList.push(name);
},
handelDestroy: function handelDestroy(destroy) {
var destroyTraverse = this.destroyTraverse;
if (typeof destroy === 'string' && destroy) {
destroyTraverse(destroy);
} else if (Array.isArray(destroy)) {
destroy.forEach(function (name) {
return destroyTraverse(name);
});
}
},
destroyTraverse: function destroyTraverse(name) {
var includeList = this.includeList;
for (var i = 0; i < includeList.length; i++) {
if (name === includeList[i]) {
includeList.splice(i, 1);
break;
}
}
}
}
};
function destroy(value) {
var destroyEvent = new CustomEvent(KEEP_COMPONENT_DESTROY, {
detail: value
});
window.dispatchEvent(destroyEvent);
}
var vueApp;
var beforeEach = beforeGuards.add;
var index = {
beforeEach: beforeEach,
install: function install(app, router) {
vueApp = app;
extendRouter(router);
app.component('KeepRouterVi