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

Add withSafeTimeout higher-order component #4839

Merged
merged 2 commits into from
Feb 9, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions blocks/rich-text/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import 'element-closest';
*/
import { createElement, Component, renderToString } from '@wordpress/element';
import { keycodes, createBlobURL } from '@wordpress/utils';
import { Slot, Fill } from '@wordpress/components';
import { withSafeTimeout, Slot, Fill } from '@wordpress/components';

/**
* Internal dependencies
Expand Down Expand Up @@ -72,7 +72,7 @@ export function getFormatProperties( formatName, parents ) {

const DEFAULT_FORMATS = [ 'bold', 'italic', 'strikethrough', 'link' ];

export default class RichText extends Component {
export class RichText extends Component {
constructor( props ) {
super( ...arguments );

Expand Down Expand Up @@ -267,11 +267,11 @@ export default class RichText extends Component {

if ( isEmpty && this.props.onReplace ) {
// Necessary to allow the paste bin to be removed without errors.
setTimeout( () => this.props.onReplace( content ) );
this.props.setTimeout( () => this.props.onReplace( content ) );
} else if ( this.props.onSplit ) {
// Necessary to get the right range.
// Also done in the TinyMCE paste plugin.
setTimeout( () => this.splitContent( content ) );
this.props.setTimeout( () => this.splitContent( content ) );
}

event.preventDefault();
Expand Down Expand Up @@ -855,3 +855,5 @@ RichText.defaultProps = {
formattingControls: DEFAULT_FORMATS,
formatters: [],
};

export default withSafeTimeout( RichText );
21 changes: 3 additions & 18 deletions blocks/rich-text/patterns.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,11 @@ import { keycodes } from '@wordpress/utils';
*/
import { getBlockTypes } from '../api/registration';

/**
* Browser dependencies
*/
const { setTimeout } = window;

const { ESCAPE, ENTER, SPACE, BACKSPACE } = keycodes;

/**
* Sets a timeout and checks if the given editor still exists.
*
* @param {Editor} editor TinyMCE editor instance.
* @param {Function} callback The function to call.
*/
function setSafeTimeout( editor, callback ) {
setTimeout( () => ! editor.removed && callback() );
}

export default function( editor ) {
const getContent = this.getContent.bind( this );
const { onReplace } = this.props;
const { setTimeout, onReplace } = this.props;

const VK = tinymce.util.VK;
const settings = editor.settings.wptextpattern || {};
Expand Down Expand Up @@ -74,9 +59,9 @@ export default function( editor ) {
enter();
// Wait for the browser to insert the character.
} else if ( keyCode === SPACE ) {
setSafeTimeout( editor, () => searchFirstText( spacePatterns ) );
setTimeout( () => searchFirstText( spacePatterns ) );
} else if ( keyCode > 47 && ! ( keyCode >= 91 && keyCode <= 93 ) ) {
setSafeTimeout( editor, inline );
setTimeout( inline );
}
}, true );

Expand Down
2 changes: 1 addition & 1 deletion blocks/rich-text/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { shallow } from 'enzyme';
/**
* Internal dependencies
*/
import RichText, { createTinyMCEElement, isLinkBoundary, getFormatProperties } from '../';
import { RichText, createTinyMCEElement, isLinkBoundary, getFormatProperties } from '../';
import { diffAriaProps, pickAriaProps } from '../aria';

describe( 'createTinyMCEElement', () => {
Expand Down
25 changes: 25 additions & 0 deletions components/higher-order/with-safe-timeout/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
withSafeTimeout
===============

`withSafeTimeout` is a React [higher-order component](https://facebook.github.io/react/docs/higher-order-components.html) which provides a special version of `window.setTimeout` which respects the original component's lifecycle. Simply put, a function set to be called in the future via `setSafeTimeout` will never be called if the original component instance ceases to exist in the meantime.

## Usage

```jsx
/**
* WordPress dependencies
*/
import { withSafeTimeout } from '@wordpress/components';

function MyEffectfulComponent( { setSafeTimeout } ) {
return (
<TextField
onBlur={ () => {
setSafeTimeout( delayedAction, 0 );
} }
/>
);
}

export default withSafeTimeout( MyEffectfulComponent );
```
63 changes: 63 additions & 0 deletions components/higher-order/with-safe-timeout/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* External dependencies
*/
import { without } from 'lodash';

/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';

/**
* Browser dependencies
*/
const { clearTimeout, setTimeout } = window;

/**
* A higher-order component used to provide and manage delayed function calls
* that ought to be bound to a component's lifecycle.
*
* @param {Component} OriginalComponent Component requiring setTimeout
*
* @return {Component} Wrapped component.
*/
function withSafeTimeout( OriginalComponent ) {
return class WrappedComponent extends Component {
constructor() {
super( ...arguments );
this.timeouts = [];
this.setTimeout = this.setTimeout.bind( this );
this.clearTimeout = this.clearTimeout.bind( this );
}

componentWillUnmount() {
this.timeouts.forEach( clearTimeout );
}

setTimeout( fn, delay ) {
const id = setTimeout( () => {
fn();
this.clearTimeout( id );
}, delay );
this.timeouts.push( id );
return id;
}

clearTimeout( id ) {
clearTimeout( id );
this.timeouts = without( this.timeouts, id );
}

render() {
return (
<OriginalComponent
{ ...this.props }
setTimeout={ this.setTimeout }
Copy link
Member

Choose a reason for hiding this comment

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

Should we return the timeoutID, in case someone wants to clear the timeout not just on unmount? Should we pass clearTimeout as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Should we return the timeoutID

Absolutely, which I just noticed I didn't do.

Pass clearTimeout

This I'm not so sure. What would we provide? The same as window.clearTimeout?

Copy link
Member

Choose a reason for hiding this comment

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

Yes. It might be more convenient to get it from the same place. Without it I'd need to get one from props, and "import" the other from the window. Maybe it's also more future-proof.

Copy link
Member

Choose a reason for hiding this comment

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

Also, I guess to be super correct, it would also need to call this.clear( id ).

clearTimeout={ this.clearTimeout }
/>
);
}
};
}

export default withSafeTimeout;
1 change: 1 addition & 0 deletions components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,6 @@ export { default as withFilters } from './higher-order/with-filters';
export { default as withFocusOutside } from './higher-order/with-focus-outside';
export { default as withFocusReturn } from './higher-order/with-focus-return';
export { default as withInstanceId } from './higher-order/with-instance-id';
export { default as withSafeTimeout } from './higher-order/with-safe-timeout';
export { default as withSpokenMessages } from './higher-order/with-spoken-messages';
export { default as withState } from './higher-order/with-state';