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

[styles] Improve ref forwarding #13676

Merged
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
6 changes: 3 additions & 3 deletions docs/src/modules/components/AppDrawerNavItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ class AppDrawerNavItem extends React.Component {
return (
<ListItem className={classes.itemLeaf} disableGutters {...other}>
<Button
component={props => (
<Link naked activeClassName={classes.active} href={href} {...props} />
)}
component={React.forwardRef((props, ref) => (
<Link naked activeClassName={classes.active} href={href} ref={ref} {...props} />
))}
className={clsx(classes.buttonLeaf, `depth-${depth}`)}
disableRipple
onClick={onClick}
Expand Down
24 changes: 10 additions & 14 deletions docs/src/modules/components/HomeSteps.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ import NoSsr from '@material-ui/core/NoSsr';
import Link from 'docs/src/modules/components/Link';
import compose from 'docs/src/modules/utils/compose';

const InstallationLink = React.forwardRef((buttonProps, ref) => (
<Link naked prefetch href="/getting-started/installation" ref={ref} {...buttonProps} />
));

const UsageLink = React.forwardRef((buttonProps, ref) => (
<Link naked prefetch href="/getting-started/usage" ref={ref} {...buttonProps} />
));

const styles = theme => ({
step: {
border: `12px solid ${theme.palette.background.paper}`,
Expand Down Expand Up @@ -124,13 +132,7 @@ function HomeSteps(props) {
/>
</div>
<Divider className={classes.divider} />
<Button
component={buttonProps => (
<Link naked prefetch href="/getting-started/installation" {...buttonProps} />
)}
>
{t('installButton')}
</Button>
<Button component={InstallationLink}>{t('installButton')}</Button>
</Grid>
<Grid item xs={12} md={4} className={classes.step}>
<div className={classes.stepTitle}>
Expand Down Expand Up @@ -158,13 +160,7 @@ function HomeSteps(props) {
/>
</div>
<Divider className={classes.divider} />
<Button
component={buttonProps => (
<Link naked prefetch href="/getting-started/usage" {...buttonProps} />
)}
>
{t('usageButton')}
</Button>
<Button component={UsageLink}>{t('usageButton')}</Button>
</Grid>
<Grid item xs={12} md={4} className={clsx(classes.step, classes.rightStep)}>
<div className={classes.stepTitle}>
Expand Down
19 changes: 8 additions & 11 deletions docs/src/modules/components/PageTitle.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,15 @@ import PageContext from 'docs/src/modules/components/PageContext';

// TODO: it really wants to be named useTitle but we're not quite there yet.
function PageTitle(props) {
return (
<PageContext.Consumer>
{({ activePage }) => {
if (!activePage) {
throw new Error('Missing activePage.');
}
const { activePage } = React.useContext(PageContext);

const title = activePage.title !== false ? pageToTitle(activePage) : null;
return props.children(title);
}}
</PageContext.Consumer>
);
if (!activePage) {
throw new Error('Missing activePage.');
}

const title = activePage.title !== false ? pageToTitle(activePage) : null;

return props.children(title);
}

PageTitle.propTypes = {
Expand Down
7 changes: 4 additions & 3 deletions docs/src/pages/css-in-js/api/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,9 @@ This `classes` object contains the name of the class names injected in the DOM.

Some implementation details that might be interesting to being aware of:
- It adds a `classes` property so you can override the injected class names from the outside.
- It adds an `innerRef` property so you can get a reference to the wrapped component. The usage of `innerRef` is identical to `ref`.
- It forwards *non React static* properties so this HOC is more "transparent".
- It forwards refs to the inner component.
- The `innerRef` prop is deprecated. Use `ref` instead.
- It does **not** copy over statics.
Copy link
Member Author

Choose a reason for hiding this comment

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

Forgotten in #13698

For instance, it can be used to defined a `getInitialProps()` static method (next.js).

#### Arguments
Expand Down Expand Up @@ -296,7 +297,7 @@ in the render method.

#### Returns

`Component`: The new component created.
`Component`: The new component created. Does forward refs to the inner component.

#### Examples

Expand Down
16 changes: 0 additions & 16 deletions packages/material-ui-styles/src/RefHolder.js

This file was deleted.

1 change: 0 additions & 1 deletion packages/material-ui-styles/src/install.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/* istanbul ignore file */
Copy link
Member

Choose a reason for hiding this comment

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

I'm removing all the istanbul ignore, @eps1lon is right, let's leave the 100% utopia.

Copy link
Member Author

Choose a reason for hiding this comment

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

To be fair that broken window analogy you linked made total sense to me. I just think that these comments won't help in that regard. At least this way we have the actual number to look at. Previously it was 100% (kind of; who knows how good it is actually). Now we know how good/bad we are and have tools helping us analyze it. Codesearch is not really that helpful IMO. It's like prefering // TODO over creating issues.

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.

/* eslint-disable no-underscore-dangle */

import { ponyfillGlobal } from '@material-ui/utils';
Expand Down
22 changes: 14 additions & 8 deletions packages/material-ui-styles/src/withStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { getDisplayName } from '@material-ui/utils';
import { chainPropTypes, getDisplayName } from '@material-ui/utils';
import makeStyles from './makeStyles';
import RefHolder from './RefHolder';
import getThemeProps from './getThemeProps';
import useTheme from './useTheme';

Expand Down Expand Up @@ -67,11 +66,7 @@ const withStyles = (stylesOrCreator, options = {}) => Component => {
}
}

return (
<RefHolder ref={ref}>
<Component ref={innerRef} classes={classes} {...more} />
</RefHolder>
);
return <Component ref={innerRef || ref} classes={classes} {...more} />;
});

WithStyles.propTypes = {
Expand All @@ -80,9 +75,20 @@ const withStyles = (stylesOrCreator, options = {}) => Component => {
*/
classes: PropTypes.object,
/**
* @deprecated
* Use that property to pass a ref callback to the decorated component.
*/
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
innerRef: chainPropTypes(PropTypes.oneOfType([PropTypes.func, PropTypes.object]), props => {
if (props.innerRef == null) {
return null;
}

return null;
// return new Error(
Copy link
Member

@oliviertassinari oliviertassinari Mar 5, 2019

Choose a reason for hiding this comment

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

It's raising a warning as the ButtonBase is still using this API.

Copy link
Member Author

Choose a reason for hiding this comment

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

Right. I think I annotated it with @deprecated somewhere to indicate a "soft deprecation". In a perfect world the eslint rule would detect these. I don't like runtime deprecation warnings that have the same level as any other warning (hello ReactDOM.findDOMNode). A lint rule makes more sense to me.

// 'Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' +
// 'Refs are now automatically forwarded to the inner component.',
// );
}),
};

if (process.env.NODE_ENV !== 'production') {
Expand Down
63 changes: 63 additions & 0 deletions packages/material-ui-styles/src/withStyles.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Input } from '@material-ui/core';
import { createMount } from '@material-ui/core/test-utils';
import { isMuiElement } from '@material-ui/core/utils/reactHelpers';
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
// import consoleErrorMock from 'test/utils/consoleErrorMock';
import StylesProvider from './StylesProvider';
import ThemeProvider from './ThemeProvider';
import withStyles from './withStyles';
Expand Down Expand Up @@ -38,6 +39,68 @@ describe('withStyles', () => {
assert.strictEqual(isMuiElement(<StyledInput />, ['Input']), true);
});

describe('refs', () => {
it('forwards ref to class components', () => {
// eslint-disable-next-line react/prefer-stateless-function
class TargetComponent extends React.Component {
render() {
return null;
}
}
const StyledTarget = withStyles({})(TargetComponent);

const ref = React.createRef();
mount(
<React.Fragment>
Copy link
Member

@oliviertassinari oliviertassinari Mar 5, 2019

Choose a reason for hiding this comment

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

What should we do with the Fragment. Should we embrace <> everywhere, should only use React.Fragment or it doesn't matter 🤔. I'm reducing entropy until we decide.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think React.Fragment is required if fragment refs land. So maybe enforce that?

<StyledTarget ref={ref} />
</React.Fragment>,
);
assert.instanceOf(ref.current, TargetComponent);
});

it('forwards refs to React.forwardRef types', () => {
const StyledTarget = withStyles({})(
// eslint-disable-next-line react/no-multi-comp
React.forwardRef((props, ref) => <div {...props} ref={ref} />),
);

const ref = React.createRef();
mount(
<React.Fragment>
<StyledTarget ref={ref} />
</React.Fragment>,
);
assert.strictEqual(ref.current.nodeName, 'DIV');
});

// describe('innerRef', () => {
// beforeEach(() => {
// consoleErrorMock.spy();
// });

// afterEach(() => {
// consoleErrorMock.reset();
// PropTypes.resetWarningCache();
// });

// it('is deprecated', () => {
// const ThemedDiv = withStyles({})('div');

// mount(
// <React.Fragment>
// <ThemedDiv innerRef={React.createRef()} />
// </React.Fragment>,
// );

// assert.strictEqual(consoleErrorMock.callCount(), 1);
// assert.include(
// consoleErrorMock.args()[0][0],
// 'Warning: Failed prop type: Material-UI: The `innerRef` prop is deprecated',
// );
// });
// });
});

it('should forward the properties', () => {
const Test = props => <div>{props.foo}</div>;
Test.propTypes = {
Expand Down
21 changes: 13 additions & 8 deletions packages/material-ui-styles/src/withTheme.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React from 'react';
import PropTypes from 'prop-types';
import hoistNonReactStatics from 'hoist-non-react-statics';
import { getDisplayName } from '@material-ui/utils';
import { chainPropTypes, getDisplayName } from '@material-ui/utils';
import useTheme from './useTheme';
import RefHolder from './RefHolder';

// Provide the theme object as a property to the input component.
// It's an alternative API to useTheme().
Expand All @@ -21,18 +20,24 @@ const withTheme = Component => {
const WithTheme = React.forwardRef(function WithTheme(props, ref) {
const { innerRef, ...other } = props;
const theme = useTheme();
return (
<RefHolder ref={ref}>
<Component theme={theme} ref={innerRef} {...other} />
</RefHolder>
);
return <Component theme={theme} ref={innerRef || ref} {...other} />;
});

WithTheme.propTypes = {
/**
* @deprecated
* Use that property to pass a ref callback to the decorated component.
*/
innerRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
innerRef: chainPropTypes(PropTypes.oneOfType([PropTypes.func, PropTypes.object]), props => {
if (props.innerRef == null) {
return null;
}

return new Error(
'Material-UI: The `innerRef` prop is deprecated and will be removed in v5. ' +
'Refs are now automatically forwarded to the inner component.',
);
}),
};

if (process.env.NODE_ENV !== 'production') {
Expand Down
65 changes: 65 additions & 0 deletions packages/material-ui-styles/src/withTheme.test.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
/* eslint-disable react/no-multi-comp */
import React from 'react';
import { assert } from 'chai';
import { createMount } from '@material-ui/core/test-utils';
import { Input } from '@material-ui/core';
import { isMuiElement } from '@material-ui/core/utils/reactHelpers';
import PropTypes from 'prop-types';
import consoleErrorMock from 'test/utils/consoleErrorMock';
import withTheme from './withTheme';
import ThemeProvider from './ThemeProvider';

Expand Down Expand Up @@ -52,6 +54,69 @@ describe('withTheme', () => {
assert.strictEqual(isMuiElement(<ThemedInput />, ['Input']), true);
});

describe('refs', () => {
it('forwards ref to class components', () => {
// eslint-disable-next-line react/prefer-stateless-function
class TargetComponent extends React.Component {
render() {
return null;
}
}
const ThemedTarget = withTheme(TargetComponent);

const ref = React.createRef();
mount(
<React.Fragment>
<ThemedTarget ref={ref} />
</React.Fragment>,
);

assert.instanceOf(ref.current, TargetComponent);
});

it('forwards refs to React.forwardRef types', () => {
const ThemedTarget = withTheme(
React.forwardRef((props, ref) => <div {...props} ref={ref} />),
);

const ref = React.createRef();
mount(
<React.Fragment>
<ThemedTarget ref={ref} />
</React.Fragment>,
);

assert.strictEqual(ref.current.nodeName, 'DIV');
});

describe('innerRef', () => {
beforeEach(() => {
consoleErrorMock.spy();
});

afterEach(() => {
consoleErrorMock.reset();
PropTypes.resetWarningCache();
});

it('is deprecated', () => {
const ThemedDiv = withTheme('div');

mount(
<React.Fragment>
<ThemedDiv innerRef={React.createRef()} />
</React.Fragment>,
);

assert.strictEqual(consoleErrorMock.callCount(), 1);
assert.include(
consoleErrorMock.args()[0][0],
'Warning: Failed prop type: Material-UI: The `innerRef` prop is deprecated',
);
});
});
});

it('should throw is the import is invalid', () => {
assert.throw(
() => withTheme(undefined),
Expand Down
1 change: 0 additions & 1 deletion packages/material-ui-utils/src/chainPropTypes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
function chainPropTypes(propType1, propType2) {
/* istanbul ignore if */
if (process.env.NODE_ENV === 'production') {
return () => null;
}
Expand Down
1 change: 0 additions & 1 deletion packages/material-ui-utils/src/exactProp.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
export const specialProperty = 'exact-prop: \u200b';

function exactProp(propTypes) {
/* istanbul ignore if */
if (process.env.NODE_ENV === 'production') {
return propTypes;
}
Expand Down
1 change: 0 additions & 1 deletion packages/material-ui/src/ButtonBase/createRippleHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ let createRippleHandler = (instance, eventName, action, cb) => event => {
return true;
};

/* istanbul ignore if */
if (typeof window === 'undefined') {
createRippleHandler = () => () => {};
}
Expand Down
Loading