-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathmatch.js
More file actions
59 lines (56 loc) · 1.64 KB
/
Copy pathmatch.js
File metadata and controls
59 lines (56 loc) · 1.64 KB
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
import { h, Component, cloneElement } from 'preact';
import { subscribers, getCurrentUrl, Link as StaticLink } from 'preact-router';
import { exec, segmentize } from './util';
export class Match extends Component {
constructor(props, context) {
super(props);
this.baseUrl = this.props.base || '';
if (props.path) {
let segments = segmentize(props.path);
segments.forEach(segment => {
if (segment.indexOf(':') == -1) {
this.baseUrl = this.baseUrl + '/' + segment;
}
});
}
if (context && context['preact-router-base']) {
this.baseUrl = context['preact-router-base'] + this.baseUrl;
}
}
update = url => {
this.nextUrl = url;
this.setState({});
};
componentDidMount() {
subscribers.push(this.update);
}
componentWillUnmount() {
subscribers.splice(subscribers.indexOf(this.update)>>>0, 1);
}
getChildContext() {
let result = {['preact-router-base']: this.baseUrl};
return result;
}
render(props, state, context) {
let url = this.nextUrl || getCurrentUrl(),
path = url.replace(/\?.+$/,'');
this.nextUrl = null;
const newProps = {
url,
path,
matches: path===props.path || exec(path, context['preact-router-base'] + props.path, {})
};
return props.children[0] &&
(typeof props.children[0] === 'function' ?
props.children[0](newProps) : cloneElement(props.children[0], newProps));
}
}
export const Link = ({ activeClassName, path, ...props }) => (
<Match path={path || props.href}>
{ ({ matches }) => (
<StaticLink {...props} class={[props.class || props.className, matches && activeClassName].filter(Boolean).join(' ')} />
) }
</Match>
);
export default Match;
Match.Link = Link;