UNPKG

3.16 kBJavaScriptView Raw
1/**
2 * Copyright 2014, Yahoo! Inc.
3 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
4 */
5/*global window */
6'use strict';
7
8var React = require('react');
9var NavLink;
10var navigateAction = require('../actions/navigate');
11var debug = require('debug')('NavLink');
12var objectAssign = require('object-assign');
13
14function isLeftClickEvent (e) {
15 return e.button === 0;
16}
17
18function isModifiedEvent (e) {
19 return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
20}
21
22NavLink = 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 // this is a click with a modifier or not a left-click
36 // let browser handle it natively
37 return;
38 }
39
40 var href = this.props.href;
41
42 if (href[0] === '#') {
43 // this is a hash link url for page's internal links.
44 // Do not trigger navigate action. Let browser handle it natively.
45 return;
46 }
47
48 if (href[0] !== '/') {
49 // this is not a relative url. check for external urls.
50 var location = window.location;
51 var origin = location.origin || (location.protocol + '//' + location.host);
52
53 if (href.indexOf(origin) !== 0) {
54 // this is an external url, do not trigger navigate action.
55 // let browser handle it natively.
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
103module.exports = NavLink;