[d565449] | 1 | import { useEffect, useState } from 'react';
|
---|
| 2 | import { isBrowser, off, on } from './misc/util';
|
---|
| 3 | var patchHistoryMethod = function (method) {
|
---|
| 4 | var history = window.history;
|
---|
| 5 | var original = history[method];
|
---|
| 6 | history[method] = function (state) {
|
---|
| 7 | var result = original.apply(this, arguments);
|
---|
| 8 | var event = new Event(method.toLowerCase());
|
---|
| 9 | event.state = state;
|
---|
| 10 | window.dispatchEvent(event);
|
---|
| 11 | return result;
|
---|
| 12 | };
|
---|
| 13 | };
|
---|
| 14 | if (isBrowser) {
|
---|
| 15 | patchHistoryMethod('pushState');
|
---|
| 16 | patchHistoryMethod('replaceState');
|
---|
| 17 | }
|
---|
| 18 | var useLocationServer = function () { return ({
|
---|
| 19 | trigger: 'load',
|
---|
| 20 | length: 1,
|
---|
| 21 | }); };
|
---|
| 22 | var buildState = function (trigger) {
|
---|
| 23 | var _a = window.history, state = _a.state, length = _a.length;
|
---|
| 24 | 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;
|
---|
| 25 | return {
|
---|
| 26 | trigger: trigger,
|
---|
| 27 | state: state,
|
---|
| 28 | length: length,
|
---|
| 29 | hash: hash,
|
---|
| 30 | host: host,
|
---|
| 31 | hostname: hostname,
|
---|
| 32 | href: href,
|
---|
| 33 | origin: origin,
|
---|
| 34 | pathname: pathname,
|
---|
| 35 | port: port,
|
---|
| 36 | protocol: protocol,
|
---|
| 37 | search: search,
|
---|
| 38 | };
|
---|
| 39 | };
|
---|
| 40 | var useLocationBrowser = function () {
|
---|
| 41 | var _a = useState(buildState('load')), state = _a[0], setState = _a[1];
|
---|
| 42 | useEffect(function () {
|
---|
| 43 | var onPopstate = function () { return setState(buildState('popstate')); };
|
---|
| 44 | var onPushstate = function () { return setState(buildState('pushstate')); };
|
---|
| 45 | var onReplacestate = function () { return setState(buildState('replacestate')); };
|
---|
| 46 | on(window, 'popstate', onPopstate);
|
---|
| 47 | on(window, 'pushstate', onPushstate);
|
---|
| 48 | on(window, 'replacestate', onReplacestate);
|
---|
| 49 | return function () {
|
---|
| 50 | off(window, 'popstate', onPopstate);
|
---|
| 51 | off(window, 'pushstate', onPushstate);
|
---|
| 52 | off(window, 'replacestate', onReplacestate);
|
---|
| 53 | };
|
---|
| 54 | }, []);
|
---|
| 55 | return state;
|
---|
| 56 | };
|
---|
| 57 | var hasEventConstructor = typeof Event === 'function';
|
---|
| 58 | export default isBrowser && hasEventConstructor ? useLocationBrowser : useLocationServer;
|
---|