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

New context API #11818

Merged
merged 17 commits into from
Jan 25, 2018
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"platform": "^1.1.0",
"prettier": "1.8.1",
"prop-types": "^15.6.0",
"random-seed": "^0.3.0",
"rimraf": "^2.6.1",
"rollup": "^0.52.1",
"rollup-plugin-babel": "^3.0.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ let React;
let ReactCallReturn;
let ReactDOMServer;
let PropTypes;
let ReactFeatureFlags;

function normalizeCodeLocInfo(str) {
return str && str.replace(/\(at .+?:\d+\)/g, '(at **)');
Expand All @@ -22,6 +23,8 @@ function normalizeCodeLocInfo(str) {
describe('ReactDOMServer', () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableNewContextAPI = true;
React = require('react');
ReactCallReturn = require('react-call-return');
PropTypes = require('prop-types');
Expand Down Expand Up @@ -384,6 +387,99 @@ describe('ReactDOMServer', () => {
expect(markup).toContain('hello, world');
});

it('renders with new context API', () => {
const Context = React.unstable_createContext(0);

function Provider(props) {
return Context.provide(props.value, props.children);
}

function Consumer(props) {
return Context.consume(value => {
return 'Result: ' + value;
});
}

const Indirection = React.Fragment;

function App(props) {
return (
<Provider value={props.value}>
<Provider value={2}>
<Consumer />
</Provider>
<Indirection>
<Indirection>
<Consumer />
<Provider value={3}>
<Consumer />
</Provider>
</Indirection>
</Indirection>
<Consumer />
</Provider>
);
}

const markup = ReactDOMServer.renderToString(<App value={1} />);
// Extract the numbers rendered by the consumers
const results = markup.match(/\d+/g).map(Number);
expect(results).toEqual([2, 1, 3, 1]);
});

it('renders context API, reentrancy', () => {
const Context = React.unstable_createContext(0);

function Provider(props) {
return Context.provide(props.value, props.children);
}

function Consumer(props) {
return Context.consume(value => {
return 'Result: ' + value;
});
}

let reentrantMarkup;
function Reentrant() {
reentrantMarkup = ReactDOMServer.renderToString(
<App value={1} reentrant={false} />,
);
return null;
}

const Indirection = React.Fragment;

function App(props) {
return (
<Provider value={props.value}>
{props.reentrant && <Reentrant />}
<Provider value={2}>
<Consumer />
</Provider>
<Indirection>
<Indirection>
<Consumer />
<Provider value={3}>
<Consumer />
</Provider>
</Indirection>
</Indirection>
<Consumer />
</Provider>
);
}

const markup = ReactDOMServer.renderToString(
<App value={1} reentrant={true} />,
);
// Extract the numbers rendered by the consumers
const results = markup.match(/\d+/g).map(Number);
const reentrantResults = reentrantMarkup.match(/\d+/g).map(Number);
expect(results).toEqual([2, 1, 3, 1]);
expect(reentrantResults).toEqual([2, 1, 3, 1]);
});

it('renders components with different batching strategies', () => {
class StaticComponent extends React.Component {
render() {
Expand Down
124 changes: 119 additions & 5 deletions packages/react-dom/src/server/ReactPartialRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
*/

import type {ReactElement} from 'shared/ReactElementType';
import type {
ReactProvider,
ReactConsumer,
ReactContext,
} from 'shared/ReactTypes';

import React from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
Expand All @@ -25,6 +30,8 @@ import {
REACT_CALL_TYPE,
REACT_RETURN_TYPE,
REACT_PORTAL_TYPE,
REACT_PROVIDER_TYPE,
REACT_CONTEXT_TYPE,
} from 'shared/ReactSymbols';

import {
Expand Down Expand Up @@ -192,7 +199,7 @@ function warnNoop(
const constructor = publicInstance.constructor;
const componentName =
(constructor && getComponentName(constructor)) || 'ReactClass';
const warningKey = `${componentName}.${callerName}`;
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This change is because the previous version was screwing up my editor's syntax highlighting 😆

Copy link

Choose a reason for hiding this comment

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

Sounds like the worst possible reason for a change in a project with more than one developer.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I can think of worse ones

const warningKey = componentName + '.' + callerName;
if (didWarnAboutNoopUpdateForComponent[warningKey]) {
return;
}
Expand Down Expand Up @@ -603,6 +610,7 @@ function resolve(
}

type Frame = {
type: mixed,
domNamespace: string,
children: FlatReactChildren,
childIndex: number,
Expand All @@ -622,12 +630,16 @@ class ReactDOMServerRenderer {
previousWasTextNode: boolean;
makeStaticMarkup: boolean;

providerStack: Array<?ReactProvider<any>>;
providerIndex: number;

constructor(children: mixed, makeStaticMarkup: boolean) {
const flatChildren = flattenTopLevelChildren(children);

const topFrame: Frame = {
// Assume all trees start in the HTML namespace (not totally true, but
// this is what we did historically)
type: null,
domNamespace: Namespaces.html,
children: flatChildren,
childIndex: 0,
Expand All @@ -642,6 +654,39 @@ class ReactDOMServerRenderer {
this.currentSelectValue = null;
this.previousWasTextNode = false;
this.makeStaticMarkup = makeStaticMarkup;

// Context (new API)
this.providerStack = []; // Stack of provider objects
this.providerIndex = -1;
}

pushProvider<T>(provider: ReactProvider<T>): void {
this.providerIndex += 1;
this.providerStack[this.providerIndex] = provider;
const context: ReactContext<any> = provider.type.context;
context.currentValue = provider.props.value;
}

popProvider<T>(provider: ReactProvider<T>): void {
if (__DEV__) {
warning(
this.providerIndex > -1 &&
provider === this.providerStack[this.providerIndex],
'Unexpected pop.',
);
}
this.providerStack[this.providerIndex] = null;
this.providerIndex -= 1;
const context: ReactContext<any> = provider.type.context;
if (this.providerIndex < 0) {
context.currentValue = context.defaultValue;
} else {
// We assume this type is correct because of the index check above.
const previousProvider: ReactProvider<any> = (this.providerStack[
this.providerIndex
]: any);
context.currentValue = previousProvider.props.value;
}
}

Choose a reason for hiding this comment

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

Maybe there is a way to refactor this so you don't have almost the same implementation as in https://github.com/acdlite/react/blob/0276eb5c5b27ea6ac251c42bd83211c7d486ab16/packages/react-reconciler/src/ReactFiberNewContext.js


read(bytes: number): string | null {
Expand All @@ -663,8 +708,15 @@ class ReactDOMServerRenderer {
this.previousWasTextNode = false;
}
this.stack.pop();
if (frame.tag === 'select') {
if (frame.type === 'select') {
this.currentSelectValue = null;
} else if (
frame.type != null &&
frame.type.type != null &&
frame.type.type.$$typeof === REACT_PROVIDER_TYPE
) {
const provider: ReactProvider<any> = (frame.type: any);
this.popProvider(provider);
}
continue;
}
Expand Down Expand Up @@ -723,6 +775,7 @@ class ReactDOMServerRenderer {
}
const nextChildren = toArray(nextChild);
const frame: Frame = {
type: null,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
Expand All @@ -738,12 +791,18 @@ class ReactDOMServerRenderer {
// Safe because we just checked it's an element.
const nextElement = ((nextChild: any): ReactElement);
const elementType = nextElement.type;

if (typeof elementType === 'string') {
return this.renderDOM(nextElement, context, parentNamespace);
}

switch (elementType) {
case REACT_FRAGMENT_TYPE:
case REACT_FRAGMENT_TYPE: {
const nextChildren = toArray(
((nextChild: any): ReactElement).props.children,
);
const frame: Frame = {
type: null,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
Expand All @@ -755,6 +814,7 @@ class ReactDOMServerRenderer {
}
this.stack.push(frame);
return '';
}
case REACT_CALL_TYPE:
case REACT_RETURN_TYPE:
invariant(
Expand All @@ -764,8 +824,62 @@ class ReactDOMServerRenderer {
);
// eslint-disable-next-line-no-fallthrough
default:
return this.renderDOM(nextElement, context, parentNamespace);
break;
}
if (typeof elementType === 'object' && elementType !== null) {
switch (elementType.$$typeof) {
case REACT_PROVIDER_TYPE: {
const provider: ReactProvider<any> = (nextChild: any);
const nextProps = provider.props;
const nextChildren = toArray(nextProps.children);
const frame: Frame = {
type: provider,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
artzhookov marked this conversation as resolved.
Show resolved Hide resolved
}

this.pushProvider(provider);

this.stack.push(frame);
return '';
}
case REACT_CONTEXT_TYPE: {
const consumer: ReactConsumer<any> = (nextChild: any);
const nextProps = consumer.props;
const nextValue = consumer.type.currentValue;

const nextChildren = toArray(nextProps.render(nextValue));
const frame: Frame = {
type: nextChild,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
}
default:
break;
}
}
invariant(
false,
'Element type is invalid: expected a string (for built-in ' +
'components) or a class/function (for composite components) ' +
'but got: %s.',
elementType == null ? elementType : typeof elementType,
);
}
}

Expand Down Expand Up @@ -1052,7 +1166,7 @@ class ReactDOMServerRenderer {
}
const frame = {
domNamespace: getChildNamespace(parentNamespace, element.type),
tag,
type: tag,
children,
childIndex: 0,
context: context,
Expand Down