1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/lib/link.js

73 lines
1.7 KiB
JavaScript
Raw Normal View History

import React, { Component, Children } from 'react'
import Router from './router'
2016-10-06 07:07:41 +00:00
export default class Link extends Component {
constructor (props) {
super(props)
this.linkClicked = this.linkClicked.bind(this)
}
linkClicked (e) {
if (e.target.nodeName === 'A' &&
(e.metaKey || e.ctrlKey || e.shiftKey || (e.nativeEvent && e.nativeEvent.which === 2))) {
2016-10-06 07:07:41 +00:00
// ignore click for new tab / new window behavior
return
}
2016-12-28 05:27:52 +00:00
const { href, as = href } = this.props
2016-10-06 07:07:41 +00:00
if (!isLocal(href)) {
// ignore click if it's outside our scope
return
}
e.preventDefault()
// avoid scroll for urls with anchor refs
let { scroll } = this.props
if (scroll == null) {
2016-12-28 05:27:52 +00:00
scroll = as.indexOf('#') < 0
}
2016-10-06 07:07:41 +00:00
// straight up redirect
2016-12-28 05:27:52 +00:00
Router.push(href, as)
.then((success) => {
if (!success) return
2016-12-22 08:17:50 +00:00
if (scroll) window.scrollTo(0, 0)
})
.catch((err) => {
if (this.props.onError) this.props.onError(err)
})
2016-10-06 07:07:41 +00:00
}
render () {
const children = Children.map(this.props.children, (child) => {
const props = {
onClick: this.linkClicked
}
const isAnchor = child && child.type === 'a'
2016-10-06 07:07:41 +00:00
// if child does not specify a href, specify it
// so that repetition is not needed by the user
2016-10-08 05:12:51 +00:00
if (!isAnchor || !('href' in child.props)) {
props.href = this.props.as || this.props.href
2016-10-06 07:07:41 +00:00
}
2016-10-08 05:12:51 +00:00
if (isAnchor) {
2016-10-06 07:07:41 +00:00
return React.cloneElement(child, props)
} else {
return <a {...props}>{child}</a>
}
})
return children[0]
}
}
export function isLocal (href) {
const origin = window.location.origin
2016-10-06 07:07:41 +00:00
return !/^https?:\/\//.test(href) ||
origin === href.substr(0, origin.length)
}