How to use @wordpress/element - 10 common examples

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 WordPress / gutenberg / packages / block-library / src / navigation-menu-item / edit.js View on Github external
function NavigationMenuItemEdit( {
	attributes,
	isSelected,
	isParentOfSelectedBlock,
	setAttributes,
} ) {
	const plainTextRef = useRef( null );
	const [ isLinkOpen, setIsLinkOpen ] = useState( false );
	const [ isEditingLink, setIsEditingLink ] = useState( false );
	const [ urlInput, setUrlInput ] = useState( null );

	const inputValue = urlInput !== null ? urlInput : url;

	const onKeyDown = ( event ) => {
		if ( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( event.keyCode ) > -1 ) {
			// Stop the key event from propagating up to ObserveTyping.startTypingInTextField.
			event.stopPropagation();
		}
	};

	const closeURLPopover = () => {
		setIsEditingLink( false );
		setUrlInput( null );
github htmlburger / carbon-fields / packages / metaboxes / containers / index.js View on Github external
export function renderContainer( container, context ) {
	const node = document.querySelector( `.container-${ container.id }` );
	const Component = getContainerType( container.type, context );

	if ( node ) {
		render(
			,
			node,
			() => {
				node.dataset.mounted = true;
			}
		);
	} else {
		// eslint-disable-next-line no-console
		console.error( sprintf( __( 'Could not find DOM element for container "%1$s".', 'carbon-fields-ui' ), container.id ) );
	}
}
github WordPress / gutenberg / packages / components / src / tooltip / index.js View on Github external
render() {
		const { children, position, text, shortcut } = this.props;
		if ( Children.count( children ) !== 1 ) {
			if ( 'development' === process.env.NODE_ENV ) {
				// eslint-disable-next-line no-console
				console.error( 'Tooltip should be called with only a single child element.' );
			}

			return children;
		}

		const child = Children.only( children );
		const { isOver } = this.state;
		return cloneElement( child, {
			onMouseEnter: this.createToggleIsOver( 'onMouseEnter', true ),
			onMouseLeave: this.createToggleIsOver( 'onMouseLeave' ),
			onClick: this.createToggleIsOver( 'onClick' ),
			onFocus: this.createToggleIsOver( 'onFocus' ),
			onBlur: this.createToggleIsOver( 'onBlur' ),
			children: concatChildren(
				child.props.children,
				isOver && (
					
						{ text }
github php4dev / heroku-wordpress / wp-content / plugins / woocommerce / packages / woocommerce-blocks / assets / js / base / hooks / use-collection-data.js View on Github external
useEffect( () => {
		if (
			calculatePriceRangeQueryState !== currentQueryPrices &&
			currentQueryPrices !== undefined
		) {
			setCalculatePriceRangeQueryState( currentQueryPrices );
		}
	}, [
		currentQueryPrices,
		setCalculatePriceRangeQueryState,
		calculatePriceRangeQueryState,
	] );

	// Defer the select query so all collection-data query vars can be gathered.
	const [ shouldSelect, setShouldSelect ] = useState( false );
	const [ debouncedShouldSelect ] = useDebounce( shouldSelect, 200 );

	if ( ! shouldSelect ) {
		setShouldSelect( true );
	}

	const collectionDataQueryVars = useMemo( () => {
		return buildCollectionDataQuery( collectionDataQueryState );
	}, [ collectionDataQueryState ] );

	return useCollection( {
		namespace: '/wc/store',
		resourceName: 'products/collection-data',
		query: {
			...queryState,
			page: undefined,
github gambitph / Stackable / src / block / icon / edit.js View on Github external
className,
		setAttributes,
		attributes,
		isSelected,
	} = props

	const {
		design = 'basic',
		columns = 1,
		showTitle = false,
		titleTop = false,
		titleTag = '',
	} = props.attributes

	const [ selected, setSelected ] = useState( false )
	const [ urlPopupPosition, setUrlPopupPosition ] = useState( 'bottom center' )
	const [ refreshPositionInterval, setRefreshPositionInterval ] = useState( null )

	const show = showOptions( props )

	const mainClasses = classnames( [
		className,
		`ugb-icon--design-${ design }`,
	], applyFilters( 'stackable.icon.mainclasses', {
	}, props ) )

	// Updates the position of the url popup to be opposite of the icon popup.
	const refreshPosition = () => {
		const popover = document.querySelector( '.ugb-icon-popover' )
		if ( popover ) {
			if ( popover.classList.contains( 'is-from-top' ) ) {
				setUrlPopupPosition( 'top center' )
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,
		} );