How to use the @wordpress/element.createContext 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 ampproject / amp-wp / assets / src / onboarding-wizard / components / navigation-context-provider.js View on Github external
/**
 * WordPress dependencies
 */
import { createContext, useState, useContext, useEffect, useMemo } from '@wordpress/element';

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
/**
 * Internal dependencies
 */
import { Options } from '../../components/options-context-provider';
import { READER } from '../../common/constants';

export const Navigation = createContext();

/**
 * Context provider for navigating between and keeping track of pages in the app.
 *
 * @param {Object} props Component props.
 * @param {?any} props.children Component children.
 * @param {Array} props.pages Pages in the app.
 */
export function NavigationContextProvider( { children, pages } ) {
	const [ activePageIndex, setActivePageIndex ] = useState( 0 );
	const [ canGoForward, setCanGoForward ] = useState( true ); // Allow immediately moving forward on first page. @todo This may need to change in 2.1.
	const { editedOptions, readerModeWasOverridden } = useContext( Options );

	const { theme_support: themeSupport } = editedOptions;

	const adaptedPages = useMemo( () => {
github Automattic / sensei / assets / setup-wizard / query-string-router / index.js View on Github external
import {
	useState,
	useMemo,
	useContext,
	createContext,
} from '@wordpress/element';

import { useEventListener } from '../../react-hooks';
import { updateQueryString, getParam } from './url-functions';

/**
 * Query string router context.
 */
const QueryStringRouterContext = createContext();

/**
 * Query string router component.
 * It creates a provider with the following values in the context:
 * - `currentRoute`: The string of the current route.
 * - `goTo`: Functions that send the user to another route.
 *
 * @param {Object} props
 * @param {string} props.paramName    Param used as reference in the query string.
 * @param {string} props.defaultRoute Default route to open if there is nothing in the URL.
 * @param {Object} props.children     Render this children if it matches the route.
 */
const QueryStringRouter = ( { paramName, defaultRoute, children } ) => {
	// Current route.
	const [ currentRoute, setRoute ] = useState( getParam( paramName ) );
github WordPress / gutenberg / packages / compose / src / hooks / use-viewport-match / index.js View on Github external
const CONDITIONS = {
	'>=': 'min-width',
	'<': 'max-width',
};

/**
 * Object mapping media query operators to a function that given a breakpointValue and a width evaluates if the operator matches the values.
 *
 * @type {Object}
 */
const OPERATOR_EVALUATORS = {
	'>=': ( breakpointValue, width ) => ( width >= breakpointValue ),
	'<': ( breakpointValue, width ) => ( width < breakpointValue ),
};

const ViewportMatchWidthContext = createContext( null );

/**
 * Returns true if the viewport matches the given query, or false otherwise.
 *
 * @param {WPBreakpoint}       breakpoint      Breakpoint size name.
 * @param {WPViewportOperator} [operator=">="] Viewport operator.
 *
 * @example
 *
 * ```js
 * useViewportMatch( 'huge', <' );
 * useViewportMatch( 'medium' );
 * ```
 *
 * @return {boolean} Whether viewport matches query.
 */
github woocommerce / woocommerce-gutenberg-products-block / assets / js / base / context / product-layout-context.js View on Github external
import { assertValidContextValue } from './utils';

const validationMap = {
	layoutStyleClassPrefix: {
		required: true,
		type: 'string',
	},
};

/**
 * ProductLayoutContext is a configuration object for layout options shared
 * among all components in a tree.
 *
 * @member {Object} ProductLayoutContext A react context object
 */
const ProductLayoutContext = createContext( {
	layoutStyleClassPrefix: '',
} );

export const useProductLayoutContext = () => useContext( ProductLayoutContext );
export const ProductLayoutContextProvider = ( { value, children } ) => {
	useEffect( () => {
		assertValidContextValue(
			'ProductLayoutContextProvider',
			validationMap,
			value
		);
	}, [ value ] );
	return (
		
			{ children }
github ampproject / amp-wp / assets / src / setup / components / reader-themes-context-provider.js View on Github external
import { createContext, useEffect, useState, useRef, useContext, useMemo } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * Internal dependencies
 */
import { useError } from '../utils/use-error';
import { Options } from './options-context-provider';

export const ReaderThemes = createContext();

/**
 * Context provider for options retrieval and updating.
 *
 * @param {Object} props Component props.
 * @param {string} props.wpAjaxUrl WP AJAX URL.
 * @param {?any} props.children Component children.
 * @param {string} props.readerThemesEndpoint REST endpoint to fetch reader themes.
 * @param {string} props.updatesNonce Nonce for the AJAX request to install a theme.
 */
export function ReaderThemesContextProvider( { wpAjaxUrl, children, readerThemesEndpoint, updatesNonce } ) {
	const [ themes, setThemes ] = useState( null );
	const [ fetchingThemes, setFetchingThemes ] = useState( false );
	const [ downloadingTheme, setDownloadingTheme ] = useState( false );

	const { setError } = useError();
github ampproject / amp-wp / assets / src / onboarding-wizard / components / template-mode-override-context-provider.js View on Github external
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { createContext, useState, useEffect, useContext } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { Options } from '../../components/options-context-provider';
import { ReaderThemes } from '../../components/reader-themes-context-provider';
import { Navigation } from './navigation-context-provider';
import { User } from './user-context-provider';

export const TemplateModeOverride = createContext();

/**
 * Responds to user selections with overrides to the template mode setting.
 *
 * @param {Object} props Component props.
 * @param {any} props.children Children to consume the context.
 */
export function TemplateModeOverrideContextProvider( { children } ) {
	const { editedOptions, originalOptions, updateOptions, readerModeWasOverridden, setReaderModeWasOverridden } = useContext( Options );
	const { currentPage: { slug: currentPageSlug } } = useContext( Navigation );
	const { selectedTheme, currentTheme } = useContext( ReaderThemes );
	const { developerToolsOption, fetchingUser, originalDeveloperToolsOption } = useContext( User );
	const [ respondedToDeveloperToolsOptionChange, setRespondedToDeveloperToolsOptionChange ] = useState( false );
	const [ mostRecentlySelectedThemeSupport, setMostRecentlySelectedThemeSupport ] = useState( null );
	const [ technicalQuestionChangedAtLeastOnce, setTechnicalQuestionChangedAtLeastOnce ] = useState( false );
github WordPress / gutenberg / packages / data / src / components / registry-provider / context.js View on Github external
/**
 * WordPress dependencies
 */
import { createContext } from '@wordpress/element';

/**
 * Internal dependencies
 */
import defaultRegistry from '../../default-registry';

export const Context = createContext( defaultRegistry );

const { Consumer, Provider } = Context;

/**
 * A custom react Context consumer exposing the provided `registry` to
 * children components. Used along with the RegistryProvider.
 *
 * You can read more about the react context api here:
 * https://reactjs.org/docs/context.html#contextprovider
 *
 * @example
 * ```js
 * const {
 *   RegistryProvider,
 *   RegistryConsumer,
 *   createRegistry
github dsifford / academic-bloggers-toolkit / src / js / gutenberg / context.tsx View on Github external
type: 'article',
    },
    update() {
        return;
    },
});

type Person = Readonly<{ kind: CSL.PersonFieldKey } & CSL.Person>;

interface PeopleContext {
    people: readonly Person[];
    update(index: number, person: Person): void;
    add(): void;
    remove(): void;
}
export const PeopleContext = createContext({
    people: [],
    update() {
        return;
    },
    add() {
        return;
    },
    remove() {
        return;
    },
});
github ampproject / amp-wp / assets / src / onboarding-wizard / components / __mocks__ / user-context-provider.js View on Github external
/**
 * External dependencies
 */
import PropTypes from 'prop-types';

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

export const User = createContext();

/**
 * MOCK.
 *
 * @param {Object} props
 * @param {any} props.children
 */
export function UserContextProvider( { children } ) {
	return (
		
			{ children }
github php4dev / heroku-wordpress / wp-content / plugins / woo-gutenberg-products-block / assets / js / base / context / query-state-context.js View on Github external
/**
 * External dependencies
 */
import { createContext, useContext } from '@wordpress/element';

/**
 * Query state context is the index for used for a query state store. By
 * exposing this via context, it allows for all children blocks to be
 * synchronized to the same query state defined by the parent in the tree.
 *
 * Defaults to 'page' for general global query state shared among all blocks
 * in a view.
 *
 * @member  {Object}  QueryStateContext A react context object
 */
const QueryStateContext = createContext( 'page' );

export const useQueryStateContext = () => useContext( QueryStateContext );
export const QueryStateContextProvider = QueryStateContext.Provider;