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

Edit in place hook #28924

Closed
wants to merge 22 commits into from
Closed
Show file tree
Hide file tree
Changes from 16 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
2 changes: 2 additions & 0 deletions packages/components/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,5 @@ export {
__unstableWithNext,
__unstableComponentSystemProvider,
} from './__next/context';

export { useInlineEdit as __unstableUseInlineEdit } from './inline-edit';
5 changes: 5 additions & 0 deletions packages/components/src/inline-edit/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Hook providing with refs to bind two elements.

One ref is used to set 'isEdit' state to true upon clicking. The second is used to set 'isEdit' state to false on 'Enter'/onBlur event and triggering onCommit callback with its value.

The hook was designed to be a component in the first place, but a hook gives more flexibility.
134 changes: 134 additions & 0 deletions packages/components/src/inline-edit/hook.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* External dependencies
*/
import { isUndefined, negate, noop, flow } from 'lodash';
/**
* WordPress dependencies
*/
import { useEffect, useState, useRef } from '@wordpress/element';

/**
* @param {import("react").ChangeEvent<HTMLInputElement>} event
*/
const cancelEvent = ( event ) => (
event.preventDefault(), event.stopPropagation(), event
);

/**
* @param {import("react").ChangeEvent<HTMLInputElement>} event
*/
const getEventValue = ( { target: { value } } ) => value;

/**
* @param {Function[]} handlers
*/
const mergeEvent = ( ...handlers ) =>
/**
* @param {import("react").ChangeEvent<HTMLInputElement>} event
*/
( event ) => handlers.forEach( ( handler = noop ) => handler( event ) );

/**
* @typedef Props
* @property {(value: string) => boolean} validate predicate
* @property {( value: string ) => void} onWrongInput called when a validate predicate fails
* @property {( value: string ) => void} onCommit called on enter/blur
* @property {string} value input value
*/

/**
* @param {Props} props
*/
export default function useInlineEdit( {
validate = negate( isUndefined ),
onWrongInput = noop,
onCommit = noop,
value: propValue,
} ) {
grzim marked this conversation as resolved.
Show resolved Hide resolved
const [ isInEditMode, setIsInEditMode ] = useState( false );
const [ editingValue, setEditingValue ] = useState( propValue );
/** @type {import('react').RefObject<HTMLInputElement>} */
const inputRef = useRef( null );
/** @type {import('react').RefObject<HTMLInputElement>} */
grzim marked this conversation as resolved.
Show resolved Hide resolved
const toggleRef = useRef( null );
const isInvalid = negate( validate );
const changeToEditMode = () => setIsInEditMode( true );
const changeToToggleMode = () => setIsInEditMode( false );

useEffect( () => {
setEditingValue( propValue );
if ( isInvalid( value ) ) onWrongInput( value );
}, [ propValue ] );
Copy link
Member

Choose a reason for hiding this comment

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

isInvalid and onWrongInput functions are being omitted from the effect dependencies. I understand it would be annoying to include them there since those props could be passed as inline functions and would trigger the effect on every re-render. But I think we should at least add a comment explaining that the effect will get out of sync if the validate logic is changed while value remains the same. I remember @ItsJonQ worked on something similar.

The local value is also omitted from the deps.

Can't we just call onWrongInput on the onChange/onBlur event? It would be much simpler than doing that in an effect.

Copy link

@ItsJonQ ItsJonQ Mar 19, 2021

Choose a reason for hiding this comment

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

I remember @ItsJonQ worked on something similar.

@diegohaz Ah! Are you referring to this usePropRef pattern I came up with?
https://github.com/ItsJonQ/g2/blob/main/packages/utils/src/hooks/use-prop-ref.js

// example
const propRefs = usePropRef({ value, step })

const increment = useCallback(() => {
  const { value, step } = propRefs.current
  onChange(value + step)
}, [onChange, propRefs])

call onWrongInput on the onChange/onBlur event?

I haven't tried it, but that seems like that would be simpler 🤔

Copy link
Contributor Author

@grzim grzim Mar 19, 2021

Choose a reason for hiding this comment

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

@diegohaz As far as I understand what you mean is that we want to make it possible the component will react if a validation (or error handling) function changes. From my perspective, we can do only two things: add those functions as the dependencies and the component will rerender every time, which will lead to poor performance or to skip these dependencies (with a comment as you suggest) as I think it is an edge case.

Solution with usePropRef would not apply here as the component would not react for a function change, please see the sandbox:
https://codesandbox.io/s/suspicious-sanne-74lv9?file=/src/App.js

We can use this pattern though, in order to add references to the hooks dependency array and not to make it rerender every time. This will make a code cleaner but the problem will remain the same.

But all in all, if we validate the value only onCommit (see my recent commit) then the entire problem just vanishes 🦩


useEffect( () => {
if ( isInEditMode ) {
inputRef.current?.focus();
inputRef.current?.select();
setEditingValue( propValue );
} else {
toggleRef.current?.focus();
}
}, [ isInEditMode ] );
grzim marked this conversation as resolved.
Show resolved Hide resolved

/**
* @param {import("react").ChangeEvent<HTMLInputElement>} event
*/
const commit = ( event ) => {
const { value } = event.target;
cancelEvent( event );
if ( validate( value ) ) {
changeToToggleMode();
onCommit( value );
} else {
onWrongInput( value );
}
};

/**
* @param {import("react").KeyboardEvent<HTMLInputElement> & import("react").ChangeEvent<HTMLInputElement>} event
sarayourfriend marked this conversation as resolved.
Show resolved Hide resolved
*/
const handleInputActions = ( event ) => {
if ( 'Enter' === event.key ) {
commit( event );
}
if ( 'Escape' === event.key ) {
cancelEvent( event );
event.target.blur();
changeToToggleMode();
} else {
const { value } = event.target;
setEditingValue( value );
}
};

const amendInputProps = ( {
onChange = noop,
onKeyDown = noop,
onBlur = noop,
...inputProps
} = {} ) => ( {
ref: inputRef,
onChange: mergeEvent(
flow( [ getEventValue, setEditingValue ] ),
onChange
),
onKeyDown: mergeEvent( handleInputActions, onKeyDown ),
onBlur: mergeEvent( commit, onBlur ),
...inputProps,
} );

const amendToggleProps = ( { onClick = noop, ...toggleProps } = {} ) => ( {
ref: toggleRef,
onClick: mergeEvent( changeToEditMode, onClick ),
...toggleProps,
} );

const value = isInEditMode ? editingValue : propValue;
grzim marked this conversation as resolved.
Show resolved Hide resolved

return {
isEdit: isInEditMode,
amendInputProps,
amendToggleProps,
value,
};
}
1 change: 1 addition & 0 deletions packages/components/src/inline-edit/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as useInlineEdit } from './hook';
76 changes: 76 additions & 0 deletions packages/components/src/inline-edit/stories/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* External dependencies
*/
import { text } from '@storybook/addon-knobs';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { pick } from 'lodash';

/**
* Internal dependencies
*/
import useInlineEdit from '../hook';

export default {
title: 'Components/EditInPlaceControl',
component: MyCustomEditInPlaceControl,
};

function MyCustomEditInPlaceControl( props = {} ) {
const { isEdit, amendInputProps, amendToggleProps, value } = useInlineEdit(
props
);
return (
<>
{ isEdit ? (
<input { ...amendInputProps( { value } ) } />
) : (
<button { ...amendToggleProps( pick( props, 'onClick' ) ) }>
{ value }
</button>
) }
</>
);
}

export const _default = () => {
const validate = ( _value = '' ) => _value.length > 0;
const initialValue = text( 'Initial value', 'Input initial value' );
const [ onClickCallbacks, setOnClickCallbacks ] = useState( 0 );
const [ ocCommitCallbacks, setOnCommitCallbacks ] = useState( 0 );
const [ value, setValue ] = useState( initialValue );
const [ isInputValid, setIsInputValid ] = useState( true );

const incrementOnClickCallbacks = () =>
setOnClickCallbacks( 1 + onClickCallbacks );

const incrementOnCommitCallbacks = () =>
setOnCommitCallbacks( 1 + ocCommitCallbacks );

const props = {
value,
validate,
onClick: incrementOnClickCallbacks,
inputValidator: validate,
onCommit: ( _value ) => (
setValue( _value ),
incrementOnCommitCallbacks(),
setIsInputValid( true )
),
onWrongInput: () => setIsInputValid( false ),
};

return (
<>
<MyCustomEditInPlaceControl { ...props } />
<ul>
<li> onClick callbacks: { onClickCallbacks } </li>
<li> onCommit callback: { ocCommitCallbacks } </li>
<li> inputValidator: is defined </li>
<li> is commited input valid: { isInputValid + '' } </li>
</ul>
</>
);
};
3 changes: 2 additions & 1 deletion packages/components/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"src/utils/**/*",
"src/view/**/*",
"src/visually-hidden/**/*",
"src/text/**/*",
"src/text/**/*",
"src/inline-edit/**/*",
"src/grid/**/*",
"src/__next/**/*"
],
Expand Down