How to use the @wordpress/element.useCallback function in @wordpress/element

To help you get started, we’ve selected a few @wordpress/element examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github WordPress / gutenberg / packages / block-editor / src / components / rich-text / index.js View on Github external
// middle block is enough to set focus in.
		if ( hasPastedBlocks || ! onSplitMiddle || ! isEmpty( after ) ) {
			blocks.push( onSplit( toHTMLString( {
				value: after,
				multilineTag,
			} ) ) );
		}

		// If there are pasted blocks, set the selection to the last one.
		// Otherwise, set the selection to the second block.
		const indexToSelect = hasPastedBlocks ? blocks.length - 1 : 1;

		onReplace( blocks, indexToSelect );
	}, [ onReplace, onSplit, multilineTag, onSplitMiddle ] );

	const onEnter = useCallback( ( { value, onChange, shiftKey } ) => {
		const canSplit = onReplace && onSplit;

		if ( onReplace ) {
			const transforms = getBlockTransforms( 'from' )
				.filter( ( { type } ) => type === 'enter' );
			const transformation = findTransform( transforms, ( item ) => {
				return item.regExp.test( value.text );
			} );

			if ( transformation ) {
				onReplace( [
					transformation.transform( { content: value.text } ),
				] );
				__unstableMarkAutomaticChange();
			}
		}
github ampproject / amp-wp / assets / src / edit-story / panels / panel / handle.js View on Github external
function DragHandle( { handleHeightChange } ) {
	const handle = useRef();
	const lastPosition = useRef();
	const [ isDragging, setIsDragging ] = useState( false );

	// On mouse move, check difference since last record vertical mouse position
	// and invoke callback with this difference.
	// Then record new vertical mouse position for next iteration.
	const handleMouseMove = useCallback( ( evt ) => {
		const delta = lastPosition.current - evt.pageY;
		handleHeightChange( delta );
		lastPosition.current = evt.pageY;
	}, [ handleHeightChange ] );

	// On mouse up, set dragging as false
	// - will cause useLayoutEffect to unregister listeners.
	const handleMouseUp = useCallback( () => setIsDragging( false ), [] );

	// On mouse down, set dragging as true
	// - will cause useLayoutEffect to register listeners.
	// Also record the initial vertical mouse position on the page.
	const handleMouseDown = useCallback( ( evt ) => {
		lastPosition.current = evt.pageY;
		setIsDragging( true );
	}, [] );
github eventespresso / event-espresso-core / assets / src / editor / events / dates-and-times / editor-date / add-new-date-entity-button.js View on Github external
createDateEntity();
			setToggleDateEditor( true );
		}
	} );
	// because we have to wait for a valid date entity to be created,
	// we can't simply open the editor via the Add New Date click event,
	// so instead we toggle the following flag to indicate this
	if ( toggleDateEditor ) {
		openDateEditor();
	}
	// a similar timing scenario exists with the ticket assignments editor
	if ( toggleTamEditor ) {
		openTamEditor();
	}
	// once the date editor has been opened, we can flip that toggle to off
	const onDateEditorOpen = useCallback( () => {
		setToggleDateEditor( false );
	}, [] );
	// when the date editor closes, indicate that we want the tam editor opened
	const onDateEditorClose = useCallback( () => {
		setToggleTamEditor( true );
	}, [] );
	// then upon the tam editor opening set the toggle to off again
	const onTamEditorOpen = useCallback( () => {
		setToggleTamEditor( false );
	}, [] );
	// once the tam editor closes, unset the cached date,
	// which will get picked up by the main date editor list
	// and free up the cache for creating another new date
	const onTamEditorClose = useCallback( () => {
		cacheNewDate( null );
	}, [] );
github eventespresso / event-espresso-core / assets / src / higher-order-components / pagination / index.js View on Github external
const EntityPagination = ( {
	paginationConfig = {},
	entities,
	instanceId,
	entitiesPerPage = 10,
	position = 'top',
	onPageChange = () => null,
	EntityList = () => null,
	...otherProps
} ) => {
	const [ pagedEntities, setPagedEntities ] = useState( entities );
	const currentEntities = useRef( entities );
	const onPaginationChange = useCallback( ( updatedPagedEntities ) => {
		setPagedEntities( updatedPagedEntities );
		onPageChange( updatedPagedEntities );
	}, [ onPageChange ] );
	useEffect(
		() => {
			// because jwPagination uses the incoming entities array to determine
			// whether to recalculate the paged entities, we need to force
			// that array to change if entitiesPerPage changes.
			currentEntities.current = [ ...entities ];
			// forces re-render because useEffect executes after initial
			// render calculation done.
			setPagedEntities( [] );
		},
		[ entitiesPerPage, entities ]
	);
	paginationConfig.labels = paginationConfig.labels &&
github WordPress / gutenberg / packages / block-editor / src / components / link-control / index.js View on Github external
const handleEntitySearch = async ( value ) => {
		const results = await Promise.all( [
			fetchSearchSuggestions( value ),
			handleDirectEntry( value ),
		] );

		const couldBeURL = ! value.includes( ' ' );

		// If it's potentially a URL search then concat on a URL search suggestion
		// just for good measure. That way once the actual results run out we always
		// have a URL option to fallback on.
		return couldBeURL ? results[ 0 ].concat( results[ 1 ] ) : results[ 0 ];
	};

	// Effects
	const getSearchHandler = useCallback( ( value ) => {
		const protocol = getProtocol( value ) || '';
		const isMailto = protocol.includes( 'mailto' );
		const isInternal = startsWith( value, '#' );
		const isTel = protocol.includes( 'tel' );

		const handleManualEntry = isInternal || isMailto || isTel || isURL( value ) || ( value && value.includes( 'www.' ) );

		return ( handleManualEntry ) ? handleDirectEntry( value ) : handleEntitySearch( value );
	}, [ handleDirectEntry, fetchSearchSuggestions ] );

	// Render Components
	const renderSearchResults = ( { suggestionsListProps, buildSuggestionItemProps, suggestions, selectedSuggestion, isLoading } ) => {
		const resultsListClasses = classnames( 'block-editor-link-control__search-results', {
			'is-loading': isLoading,
		} );
github eventespresso / event-espresso-core / assets / src / editor / events / ticket-assignments-manager / filters / date-filters.js View on Github external
const DateFilters = ( {
	showDateFilters,
	showArchivedDates,
	showExpiredDates,
	dateFiltersOffset,
	setFilter,
} ) => {
	const toggleArchivedDates = useCallback(
		() => setFilter( showArchivedDatesAction ),
		[ setFilter, showArchivedDatesAction ]
	);
	const toggleExpiredDates = useCallback(
		() => setFilter( showExpiredDatesAction ),
		[ setFilter, showExpiredDatesAction ]
	);
	return showDateFilters && (
github ampproject / amp-wp / assets / src / stories-editor / components / rotatable-box / index.js View on Github external
let newAngle = Math.ceil( -( rad2deg * Math.atan2( x, y ) ) );

		newAngle = findClosestSnap( newAngle, snap, snapGap );

		if ( currentAngle === newAngle ) {
			return;
		}

		setAngle( newAngle );

		if ( onRotate ) {
			onRotate( e, newAngle );
		}
	}, [ currentAngle, isRotating, snap, snapGap, onRotate ] );

	const onMouseUp = useCallback( ( e ) => {
		if ( ! isRotating ) {
			return;
		}

		e.preventDefault();

		setIsRotating( false );

		if ( onRotateStop ) {
			onRotateStop( e, currentAngle );
		}
	}, [ currentAngle, isRotating, onRotateStop ] );

	useEffect( () => {
		document.addEventListener( 'mousemove', onMouseMove );
		document.addEventListener( 'mouseup', onMouseUp );
github ampproject / amp-wp / assets / src / edit-story / components / inspector / documentInspector.js View on Github external
const allStatuses = useMemo( () => {
		const disabledStatuses = ( status === 'future' ) ? [ 'pending' ] : [ 'future', 'pending' ];
		return statuses.filter( ( { value } ) => ! disabledStatuses.includes( value ) );
	}, [ status, statuses ] );

	const handleChangeValue = useCallback(
		( prop ) => ( value ) => updateStory( { properties: { [ prop ]: value } } ),
		[ updateStory ],
	);

	const handleChangeImage = useCallback(
		( image ) => updateStory( { properties: { featuredMedia: image.id, featuredMediaUrl: ( image.sizes && image.sizes.medium ) ? image.sizes.medium.url : image.url } } ),
		[ updateStory ],
	);

	const handleRemoveImage = useCallback(
		( evt ) => {
			updateStory( { properties: { featuredMedia: 0, featuredMediaUrl: '' } } );
			evt.preventDefault();
		},	[ updateStory ],
	);

	const handleRemoveStory = useCallback(
		( evt ) => {
			deleteStory();
			evt.preventDefault();
		},	[ deleteStory ],
	);

	return (
		<>
			<h2></h2>
github php4dev / heroku-wordpress / wp-content / plugins / woocommerce / packages / woocommerce-blocks / assets / js / base / components / price-slider / index.js View on Github external
}, [
		minPrice,
		maxPrice,
		minConstraint,
		maxConstraint,
		hasValidConstraints,
		stepValue,
	] );

	/**
	 * Works around an IE issue where only one range selector is visible by changing the display order
	 * based on the mouse position.
	 *
	 * @param {Object} event event data.
	 */
	const findClosestRange = useCallback(
		( event ) => {
			if ( isLoading || ! hasValidConstraints ) {
				return;
			}
			const bounds = event.target.getBoundingClientRect();
			const x = event.clientX - bounds.left;
			const minWidth = minRange.current.offsetWidth;
			const minValue = minRange.current.value;
			const maxWidth = maxRange.current.offsetWidth;
			const maxValue = maxRange.current.value;

			const minX = minWidth * ( minValue / maxConstraint );
			const maxX = maxWidth * ( maxValue / maxConstraint );

			const minXDiff = Math.abs( x - minX );
			const maxXDiff = Math.abs( x - maxX );
github WordPress / gutenberg / packages / core-data / src / entity-provider.js View on Github external
const editKeys = Object.keys( _edits );
			return [
				props ?
					editKeys.some( ( key ) =>
						typeof props === 'string' ? key === props : props.includes( key )
					) :
					editKeys.length > 0,
				isSavingEntityRecord( kind, type, id ),
				_edits,
			];
		},
		[ kind, type, id, props ]
	);

	const { saveEntityRecord } = useDispatch( 'core' );
	const save = useCallback( () => {
		let filteredEdits = edits;
		if ( typeof props === 'string' ) {
			filteredEdits = { [ props ]: filteredEdits[ props ] };
		} else if ( props ) {
			filteredEdits = filteredEdits.reduce( ( acc, key ) => {
				if ( props.includes( key ) ) {
					acc[ key ] = filteredEdits[ key ];
				}
				return acc;
			}, {} );
		}
		saveEntityRecord( kind, type, { id, ...filteredEdits } );
	}, [ kind, type, id, props, edits ] );

	return [ isDirty, isSaving, save ];
}