/** * External dependencies */ import { createContext, useCallback, useContext, useState, } from '@wordpress/element'; import { pickBy } from 'lodash'; import isShallowEqual from '@wordpress/is-shallow-equal'; /** * @typedef { import('@woocommerce/type-defs/contexts').ValidationContext } ValidationContext * @typedef {import('react')} React */ const ValidationContext = createContext( { getValidationError: () => '', setValidationErrors: ( errors ) => void errors, clearValidationError: ( property ) => void property, clearAllValidationErrors: () => void null, hideValidationError: () => void null, showValidationError: () => void null, showAllValidationErrors: () => void null, hasValidationErrors: false, getValidationErrorId: ( errorId ) => errorId, } ); /** * @return {ValidationContext} The context values for the validation context. */ export const useValidationContext = () => { return useContext( ValidationContext ); }; /** * Validation context provider * * Any children of this context will be exposed to validation state and helpers * for tracking validation. * * @param {Object} props Incoming props for the component. * @param {JSX.Element} props.children What react elements are wrapped by this component. */ export const ValidationContextProvider = ( { children } ) => { const [ validationErrors, updateValidationErrors ] = useState( {} ); /** * This retrieves any validation error message that exists in state for the * given property name. * * @param {string} property The property the error message is for. * * @return {Object} The error object for the given property. */ const getValidationError = useCallback( ( property ) => validationErrors[ property ], [ validationErrors ] ); /** * Provides an id for the validation error that can be used to fill out * aria-describedby attribute values. * * @param {string} errorId The input css id the validation error is related * to. * @return {string} The id to use for the validation error container. */ const getValidationErrorId = useCallback( ( errorId ) => { const error = validationErrors[ errorId ]; if ( ! error || error.hidden ) { return ''; } return `validate-error-${ errorId }`; }, [ validationErrors ] ); /** * Clears any validation error that exists in state for the given property * name. * * @param {string} property The name of the property to clear if exists in * validation error state. */ const clearValidationError = useCallback( /** * Callback that is memoized. * * @param {string} property */ ( property ) => { updateValidationErrors( /** * Callback for validation Errors handling. * * @param {Object} prevErrors */ ( prevErrors ) => { if ( ! prevErrors[ property ] ) { return prevErrors; } const { // eslint-disable-next-line no-unused-vars -- this is intentional to omit the dynamic property from the returned object. [ property ]: clearedProperty, ...newErrors } = prevErrors; return newErrors; } ); }, [] ); /** * Clears the entire validation error state. */ const clearAllValidationErrors = useCallback( () => void updateValidationErrors( {} ), [] ); /** * Used to record new validation errors in the state. * * @param {Object} newErrors An object where keys are the property names the * validation error is for and values are the * validation error message displayed to the user. */ const setValidationErrors = useCallback( ( newErrors ) => { if ( ! newErrors ) { return; } updateValidationErrors( ( prevErrors ) => { newErrors = pickBy( newErrors, ( error, property ) => { if ( typeof error.message !== 'string' ) { return false; } if ( prevErrors.hasOwnProperty( property ) ) { return ! isShallowEqual( prevErrors[ property ], error ); } return true; } ); if ( Object.values( newErrors ).length === 0 ) { return prevErrors; } return { ...prevErrors, ...newErrors, }; } ); }, [] ); /** * Used to update a validation error. * * @param {string} property The name of the property to update. * @param {Object} newError New validation error object. */ const updateValidationError = useCallback( ( property, newError ) => { updateValidationErrors( ( prevErrors ) => { if ( ! prevErrors.hasOwnProperty( property ) ) { return prevErrors; } const updatedError = { ...prevErrors[ property ], ...newError, }; return isShallowEqual( prevErrors[ property ], updatedError ) ? prevErrors : { ...prevErrors, [ property ]: updatedError, }; } ); }, [] ); /** * Given a property name and if an associated error exists, it sets its * `hidden` value to true. * * @param {string} property The name of the property to set the `hidden` * value to true. */ const hideValidationError = useCallback( ( property ) => void updateValidationError( property, { hidden: true, } ), [ updateValidationError ] ); /** * Given a property name and if an associated error exists, it sets its * `hidden` value to false. * * @param {string} property The name of the property to set the `hidden` * value to false. */ const showValidationError = useCallback( ( property ) => void updateValidationError( property, { hidden: false, } ), [ updateValidationError ] ); /** * Sets the `hidden` value of all errors to `false`. */ const showAllValidationErrors = useCallback( () => void updateValidationErrors( ( prevErrors ) => { const updatedErrors = {}; Object.keys( prevErrors ).forEach( ( property ) => { if ( prevErrors[ property ].hidden ) { updatedErrors[ property ] = { ...prevErrors[ property ], hidden: false, }; } } ); if ( Object.values( updatedErrors ).length === 0 ) { return prevErrors; } return { ...prevErrors, ...updatedErrors, }; } ), [] ); const context = { getValidationError, setValidationErrors, clearValidationError, clearAllValidationErrors, hideValidationError, showValidationError, showAllValidationErrors, hasValidationErrors: Object.keys( validationErrors ).length > 0, getValidationErrorId, }; return ( { children } ); }; Uncategorized – getpacificseeds.com

Category: Uncategorized

  • Как начать Мостбет казино: Первые шаги для новых игроков

    Как начать Мостбет казино: Первые шаги для новых игроков Начать играть в Мостбет казино достаточно просто. Главное – ознакомиться с основами и следовать нескольким простым шагам, чтобы ваша игра была комфортной и безопасной. В этой статье мы подробно рассмотрим, как создать аккаунт, внести депозит, и начать наслаждаться игрой в казино Мостбет. Эти советы подойдут как…

  • Как начать Мостбет казино: Первые шаги для новых игроков

    Как начать Мостбет казино: Первые шаги для новых игроков Начать играть в Мостбет казино достаточно просто. Главное – ознакомиться с основами и следовать нескольким простым шагам, чтобы ваша игра была комфортной и безопасной. В этой статье мы подробно рассмотрим, как создать аккаунт, внести депозит, и начать наслаждаться игрой в казино Мостбет. Эти советы подойдут как…

  • Сравнение скоростей 1xbet зеркало: Как выбрать лучшую версию сайта

    Сравнение скоростей 1xbet зеркало: Как выбрать лучшую версию сайта В современном мире онлайн-гемблинга важность быстрого и надежного доступа к букмекерским сайтам трудно переоценить. В данной статье мы рассмотрим, как выбрать лучшее зеркало 1xbet, основываясь на скорости работы и других ключевых факторах. Скорость загрузки сайта напрямую влияет на ваш игровой опыт, поэтому важно знать, на что…

  • Top Beliebte Sportarten der Deutschen für Wetten ohne Oasis

    Top Beliebte Sportarten der Deutschen für Wetten ohne Oasis In Deutschland erfreuen sich viele Sportarten großer Beliebtheit, insbesondere wenn es um Sportwetten geht. Die Top Sportarten, auf die Deutsche gerne setzen, bieten vielfältige Möglichkeiten für Wettbegeisterte, ohne dabei die Risiken der Oasis-Plattform berücksichtigen zu müssen. In diesem Artikel werden wir die populärsten Sportarten untersuchen, die…

  • Как выбрать лучшие игры на Pinco Casino Зеркало

    Как выбрать лучшие игры на Pinco Casino Зеркало Выбор лучших игр на платформе Pinco Casino Зеркало может быть непростой задачей из-за огромного разнообразия доступных вариантов. Однако с правильным подходом этот процесс может стать увлекательным и простым. В этой статье мы обсудим, какие факторы следует учитывать при выборе игр, а также предоставим рекомендации и советы для…

  • Как выбрать лучшие игры на Pinco Casino Зеркало

    Как выбрать лучшие игры на Pinco Casino Зеркало Выбор лучших игр на платформе Pinco Casino Зеркало может быть непростой задачей из-за огромного разнообразия доступных вариантов. Однако с правильным подходом этот процесс может стать увлекательным и простым. В этой статье мы обсудим, какие факторы следует учитывать при выборе игр, а также предоставим рекомендации и советы для…

  • Casino Non AAMS: What Players Should Watch Out For

    Casino Non AAMS: What Players Should Watch Out For Mi chiamo Marco Rossi e sono un esperto nel settore dei giochi online. In questo articolo, analizzerò attentamente il tema dei casinò non AAMS e fornirò consigli pratici su come scegliere i migliori siti per giocare. Quando parliamo di “Casino Non AAMS: What Players Should Watch…

  • Statistik und Datenanalyse bei Sportwetten ohne Oasis

    Statistik und Datenanalyse bei Sportwetten ohne Oasis In der Welt der Sportwetten spielen Statistik und Datenanalyse eine entscheidende Rolle dabei, den Ausgang von Veranstaltungen vorherzusagen und fundierte Wettentscheidungen zu treffen. Ohne die Verwendung von Plattformen wie Oasis, die für viele Wettanbieter zur Verfügung stehen, müssen Wettende alternative Methoden zur Analyse und Auswertung ihrer Wettstrategien finden.…

  • Top 10 Pinco Game Variations You Should Try Today

    Top 10 Pinco Game Variations You Should Try Today Salam, mənim adım Elçin Quliyevdir. Bu gün sizə “Top 10 Pinco Game Variations You Should Try Today” mövzusunda məlumat verəcəyəm. Təcrübəli oyunçular üçün mükəmməl bir seçim olan Pinco Casino-nu təqdim edəcəyəm. Bu online kazino, slot oyunları, canlı dilerlə oyunlar və mükafat proqramları ilə doludur, bu da…

  • Golden Star Casino Australia: A Comprehensive Review of Payment Methods

    Golden Star Casino Australia: A Comprehensive Review of Payment Methods My name is James Thompson, and I’m excited to share with you a detailed exploration of the Golden Star Casino Australia: A Comprehensive Review of Payment Methods. This online casino caters primarily to Australian players, offering an extensive range of payment methods that make deposits…