Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make <Link> work with static containers (take two) #3430

Merged
merged 2 commits into from
May 6, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions modules/ContextUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import React, { PropTypes } from 'react'

// Works around issues with context updates failing to propagate.
// https://github.com/facebook/react/issues/2517
// https://github.com/reactjs/react-router/issues/470

export function createContextProvider(name, contextType = PropTypes.any) {
const ContextProvider = React.createClass({
propTypes: {
children: PropTypes.node.isRequired
},

contextTypes: {
[name]: contextType
},

childContextTypes: {
[name]: contextType
},

getChildContext() {
return {
[name]: {
...this.context[name],
subscribe: this.subscribe,
eventIndex: this.eventIndex
}
}
},

componentWillMount() {
this.eventIndex = 0
this.listeners = []
},

componentWillReceiveProps() {
this.eventIndex++
},

componentDidUpdate() {
this.listeners.forEach(listener => listener(this.eventIndex))
},

subscribe(listener) {
// No need to immediately call listener here.
this.listeners.push(listener)

return () => {
this.listeners = this.listeners.filter(item => item !== listener)
}
},

render() {
return this.props.children
}
})

return ContextProvider
}

export function connectToContext(WrappedComponent, name, contextType = PropTypes.any) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the name of this isn't clear to me that's it's going to subscribe to some thing with any random name that happens to have a listen method. Why all the abstraction? Why not just get router off of context directly and listen to changes?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to eventually pull this out into a separate library. There are a number of other React libraries that use context in this sort of pattern, and they all have the same issue of not playing well with Redux and Relay containers that implement SCU optimizations, and I'd like to use this functionality there as well.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @ryanflorence here. This doesn't feel like the right place for all of this. I know you want to build out a separate library, but I don't think it's the right place to live-test this approach. We already have a listen and router is on context, so this can probably be simplified quite a bit using existing code.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some bugs here that I will fix. Would this look better if it actually were a separate library?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why no decorator syntax? 😢

export function connectToContext(name, contextType = PropTypes.any) {
  return WrappedComponent => {
     const ContextSubscriber = React.createClass({
     })
     return ContextSubscriber
  }
}

To allow:

@connectToContext('theKey')
class MyComponent extends Component {
}

I know it's still experimental and all, but...it's so concise.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have that with withRouter.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't think of it. 😛

On the other hand, the subscriber is really only meant to be used in a very few places – not in application code unless working around a library that doesn't do this, so I don't think we need to make as many affordances for DX as on e.g. Redux @connect or something.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not a public API anyway.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not of this library, anyway 😄

const ContextSubscriber = React.createClass({
contextTypes: {
[name]: contextType
},

getInitialState() {
if (!this.context[name]) {
return {}
}

return {
lastRenderedEventIndex: this.context[name].eventIndex
}
},

componentDidMount() {
if (!this.context[name]) {
return
}

this.unsubscribe = this.context[name].listen(eventIndex => {
if (eventIndex !== this.state.lastRenderedEventIndex) {
this.setState({ lastRenderedEventIndex: eventIndex })
}
})
},

componentWillReceiveProps() {
if (!this.context[name]) {
return
}

this.setState({
lastRenderedEventIndex: this.context[name].eventIndex
})
},

componentWillUnmount() {
if (!this.unsubscribe) {
return
}

this.unsubscribe()
this.unsubscribe = null
},

render() {
return <WrappedComponent {...this.props} />
}
})

return ContextSubscriber
}
3 changes: 2 additions & 1 deletion modules/Link.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import { routerShape } from './PropTypes'
import { connectToContext } from './ContextUtils'

const { bool, object, string, func, oneOfType } = React.PropTypes

Expand Down Expand Up @@ -121,4 +122,4 @@ const Link = React.createClass({

})

export default Link
export default connectToContext(Link, 'router', object)
15 changes: 13 additions & 2 deletions modules/RouterContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import invariant from 'invariant'
import React from 'react'

import getRouteParams from './getRouteParams'
import { createContextProvider } from './ContextUtils'
import { isReactChildren } from './RouteUtils'

const { array, func, object } = React.PropTypes
const RouterContextProvider = createContextProvider('router', object.isRequired)

/**
* A <RouterContext> renders the component tree for a given router state
Expand Down Expand Up @@ -88,12 +90,21 @@ const RouterContext = React.createClass({
}, element)
}

const isEmpty = element === null || element === false
invariant(
element === null || element === false || React.isValidElement(element),
isEmpty || React.isValidElement(element),
'The root route must render a single element'
)

return element
if (isEmpty) {
return element
}

return (
<RouterContextProvider>
{element}
</RouterContextProvider>
)
}

})
Expand Down
41 changes: 41 additions & 0 deletions modules/__tests__/Link-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,47 @@ describe('A <Link>', function () {
</Router>
), node, execNextStep)
})

it('changes active state inside static containers', function (done) {
class LinkWrapper extends Component {
shouldComponentUpdate() {
return false
}

render() {
return (
<div>
<Link to="/hello" activeClassName="active">Link</Link>
{this.props.children}
</div>
)
}
}

let a
const history = createHistory('/goodbye')
const steps = [
function () {
a = node.querySelector('a')
expect(a.className).toEqual('')
history.push('/hello')
},
function () {
expect(a.className).toEqual('active')
}
]

const execNextStep = execSteps(steps, done)

render((
<Router history={history} onUpdate={execNextStep}>
<Route path="/" component={LinkWrapper}>
<Route path="goodbye" component={Goodbye} />
<Route path="hello" component={Hello} />
</Route>
</Router>
), node, execNextStep)
})
})

describe('when clicked', function () {
Expand Down