1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | 'use strict';
|
7 |
|
8 | var React = require('react');
|
9 | var NavLink;
|
10 | var navigateAction = require('../actions/navigate');
|
11 | var debug = require('debug')('NavLink');
|
12 | var objectAssign = require('object-assign');
|
13 |
|
14 | function isLeftClickEvent (e) {
|
15 | return e.button === 0;
|
16 | }
|
17 |
|
18 | function isModifiedEvent (e) {
|
19 | return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
|
20 | }
|
21 |
|
22 | NavLink = React.createClass({
|
23 | displayName: 'NavLink',
|
24 | contextTypes: {
|
25 | executeAction: React.PropTypes.func,
|
26 | makePath: React.PropTypes.func
|
27 | },
|
28 | propTypes: {
|
29 | context: React.PropTypes.object
|
30 | },
|
31 | dispatchNavAction: function (e) {
|
32 | debug('dispatchNavAction: action=NAVIGATE', this.props.href, this.props.navParams);
|
33 |
|
34 | if (isModifiedEvent(e) || !isLeftClickEvent(e)) {
|
35 |
|
36 |
|
37 | return;
|
38 | }
|
39 |
|
40 | var href = this.props.href;
|
41 |
|
42 | if (href[0] === '#') {
|
43 |
|
44 |
|
45 | return;
|
46 | }
|
47 |
|
48 | if (href[0] !== '/') {
|
49 |
|
50 | var location = window.location;
|
51 | var origin = location.origin || (location.protocol + '//' + location.host);
|
52 |
|
53 | if (href.indexOf(origin) !== 0) {
|
54 |
|
55 |
|
56 | return;
|
57 | }
|
58 |
|
59 | href = href.substring(origin.length) || '/';
|
60 | }
|
61 |
|
62 | var context;
|
63 | if (this.context && this.context.executeAction) {
|
64 | context = this.context;
|
65 | } else if (this.props.context && this.props.context.executeAction) {
|
66 | context = this.props.context;
|
67 | }
|
68 |
|
69 | if (context) {
|
70 | e.preventDefault();
|
71 | e.stopPropagation();
|
72 | context.executeAction(navigateAction, {
|
73 | type: 'click',
|
74 | url: href,
|
75 | params: this.props.navParams
|
76 | });
|
77 | } else {
|
78 | console.warn('NavLink.dispatchNavAction: missing dispatcher, will load from server');
|
79 | }
|
80 | },
|
81 | render: function() {
|
82 | var context;
|
83 | if (this.context && this.context.makePath) {
|
84 | context = this.context;
|
85 | } else if (this.props.context && this.props.context.makePath) {
|
86 | context = this.props.context;
|
87 | }
|
88 |
|
89 | var routeName = this.props.routeName;
|
90 | if (!this.props.href && routeName && context) {
|
91 | this.props.href = context.makePath(routeName, this.props.navParams);
|
92 | }
|
93 | return React.createElement(
|
94 | 'a',
|
95 | objectAssign({}, {
|
96 | onClick: this.dispatchNavAction
|
97 | }, this.props),
|
98 | this.props.children
|
99 | );
|
100 | }
|
101 | });
|
102 |
|
103 | module.exports = NavLink;
|