/
index.ts
132 lines (109 loc) · 2.61 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import {Component} from 'react';
import {on, off, isClient, noop} from '../util';
import faccToHoc from '../util/faccToHoc';
import renderProp from '../util/renderProp';
import {IUniversalInterfaceProps} from '../typing';
const patchHistoryMethod = (method) => {
const original = history[method];
history[method] = function (state) {
const result = original.apply(this, arguments);
const event = new Event(method.toLowerCase());
(event as any).state = state;
window.dispatchEvent(event);
return result;
};
};
if (isClient) {
patchHistoryMethod('pushState');
patchHistoryMethod('replaceState');
}
export interface ILocationSensorProps extends IUniversalInterfaceProps<ILocationSensorState> {
onChange?: (state: ILocationSensorState) => void;
}
export interface ILocationSensorState {
trigger: string;
state?: any;
length?: number;
hash?: string;
host?: string;
hostname?: string;
href?: string;
origin?: string;
pathname?: string;
port?: string;
protocol?: string;
search?: string;
}
export class LocationSensor extends Component<ILocationSensorProps, ILocationSensorState> {
state: ILocationSensorState;
constructor (props, context) {
super(props, context);
if (isClient) {
this.state = this.buildState('load');
} else {
this.state = {
trigger: 'load',
length: 1
};
}
}
componentDidMount () {
on(window, 'popstate', this.onPopstate);
on(window, 'pushstate', this.onPushstate);
on(window, 'replacestate', this.onReplacestate);
}
componentWillUnmount () {
off(window, 'popstate', this.onPopstate);
off(window, 'pushstate', this.onPushstate);
off(window, 'replacestate', this.onReplacestate);
}
onPopstate = () => {
this.onChange('popstate');
};
onPushstate = () => {
this.onChange('pushstate');
};
onReplacestate = () => {
this.onChange('replacestate');
};
onChange = (trigger: string) => {
const newState = this.buildState(trigger);
this.setState(newState);
(this.props.onChange || noop)(newState);
};
buildState (trigger: string) {
const {
state,
length
} = history;
const {
hash,
host,
hostname,
href,
origin,
pathname,
port,
protocol,
search
} = location;
return {
trigger,
state,
length,
hash,
host,
hostname,
href,
origin,
pathname,
port,
protocol,
search
};
}
render () {
return renderProp(this.props, this.state);
}
}
export const withLocation = faccToHoc(LocationSensor, 'location');