61 lines
2.3 KiB
JavaScript
61 lines
2.3 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var react_1 = require("react");
|
|
var util_1 = require("./misc/util");
|
|
var patchHistoryMethod = function (method) {
|
|
var history = window.history;
|
|
var original = history[method];
|
|
history[method] = function (state) {
|
|
var result = original.apply(this, arguments);
|
|
var event = new Event(method.toLowerCase());
|
|
event.state = state;
|
|
window.dispatchEvent(event);
|
|
return result;
|
|
};
|
|
};
|
|
if (util_1.isBrowser) {
|
|
patchHistoryMethod('pushState');
|
|
patchHistoryMethod('replaceState');
|
|
}
|
|
var useLocationServer = function () { return ({
|
|
trigger: 'load',
|
|
length: 1,
|
|
}); };
|
|
var buildState = function (trigger) {
|
|
var _a = window.history, state = _a.state, length = _a.length;
|
|
var _b = window.location, hash = _b.hash, host = _b.host, hostname = _b.hostname, href = _b.href, origin = _b.origin, pathname = _b.pathname, port = _b.port, protocol = _b.protocol, search = _b.search;
|
|
return {
|
|
trigger: trigger,
|
|
state: state,
|
|
length: length,
|
|
hash: hash,
|
|
host: host,
|
|
hostname: hostname,
|
|
href: href,
|
|
origin: origin,
|
|
pathname: pathname,
|
|
port: port,
|
|
protocol: protocol,
|
|
search: search,
|
|
};
|
|
};
|
|
var useLocationBrowser = function () {
|
|
var _a = react_1.useState(buildState('load')), state = _a[0], setState = _a[1];
|
|
react_1.useEffect(function () {
|
|
var onPopstate = function () { return setState(buildState('popstate')); };
|
|
var onPushstate = function () { return setState(buildState('pushstate')); };
|
|
var onReplacestate = function () { return setState(buildState('replacestate')); };
|
|
util_1.on(window, 'popstate', onPopstate);
|
|
util_1.on(window, 'pushstate', onPushstate);
|
|
util_1.on(window, 'replacestate', onReplacestate);
|
|
return function () {
|
|
util_1.off(window, 'popstate', onPopstate);
|
|
util_1.off(window, 'pushstate', onPushstate);
|
|
util_1.off(window, 'replacestate', onReplacestate);
|
|
};
|
|
}, []);
|
|
return state;
|
|
};
|
|
var hasEventConstructor = typeof Event === 'function';
|
|
exports.default = util_1.isBrowser && hasEventConstructor ? useLocationBrowser : useLocationServer;
|