diff --git a/includes/advanced-form/advanced-form-cpt.php b/includes/advanced-form/advanced-form-cpt.php index 5feb37882..54dee6652 100644 --- a/includes/advanced-form/advanced-form-cpt.php +++ b/includes/advanced-form/advanced-form-cpt.php @@ -1486,6 +1486,11 @@ public function register_meta() { 'type' => 'array', 'children_type' => 'string' ), + array( + 'key' => '_kad_form_importId', + 'default' => '', + 'type' => 'string' + ), ); register_post_meta( 'kadence_form', diff --git a/includes/class-kadence-blocks-prebuilt-library-rest-api.php b/includes/class-kadence-blocks-prebuilt-library-rest-api.php index 988e9eda8..043a6ef36 100644 --- a/includes/class-kadence-blocks-prebuilt-library-rest-api.php +++ b/includes/class-kadence-blocks-prebuilt-library-rest-api.php @@ -184,6 +184,14 @@ class Kadence_Blocks_Prebuilt_Library_REST_Controller extends WP_REST_Controller */ protected $remote_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/get/'; + /** + * The remote URL. + * + * @access protected + * @var string + */ + protected $remote_cat_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/categories/'; + /** * The remote URL. * @@ -192,6 +200,14 @@ class Kadence_Blocks_Prebuilt_Library_REST_Controller extends WP_REST_Controller */ protected $remote_pages_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/pages/'; + /** + * The remote URL. + * + * @access protected + * @var string + */ + protected $remote_pages_cat_url = 'https://patterns.startertemplatecloud.com/wp-json/kadence-cloud/v1/pages-categories/'; + /** * The remote URL. * @@ -368,6 +384,18 @@ public function register_routes() { ), ) ); + register_rest_route( + $this->namespace, + '/get_library_categories', + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_library_categories' ), + 'permission_callback' => array( $this, 'get_items_permission_check' ), + 'args' => $this->get_collection_params(), + ), + ) + ); register_rest_route( $this->namespace, '/get_local_contexts', @@ -767,7 +795,52 @@ public function process_images( WP_REST_Request $request ): array { return kadence_blocks()->get( Image_Downloader::class )->download( $parameters ); } - + /** + * Creates the forms if needed. + * + * @param string $content The content to process. + */ + public function process_forms( $content, $forms ) { + $new_forms = array(); + foreach ( $forms as $form_id => $form_content ) { + if ( empty( $form_content['name'] ) ) { + continue; + } + $import_key = $form_id . sanitize_key( $form_content['name'] ); + // Lets not duplicate forms. + $has_form = get_posts( array( + 'post_type' => 'kadence_form', + 'meta_key' => '_kad_form_importId', + 'meta_value' => $import_key, + 'title' => $form_content['name'], + ) ); + if ( $has_form ) { + $new_forms[ $form_id ] = $has_form[0]->ID; + continue; + } + $new_form_id = wp_insert_post( + array( + 'post_title' => wp_strip_all_tags( $form_content['name'] ), + 'post_content' => $form_content['content'], + 'post_status' => 'publish', + 'post_type' => 'kadence_form', + ) + ); + if ( ! is_wp_error( $new_form_id ) ) { + if ( ! empty( $form_content['meta'] ) ) { + foreach ( $form_content['meta'] as $meta_key => $meta_value ) { + update_post_meta( $new_form_id, $meta_key, $meta_value ); + } + } + update_post_meta( $new_form_id, '_kad_form_importId', $import_key ); + $new_forms[ $form_id ] = $new_form_id; + } + } + foreach ( $new_forms as $old_id => $new_id ) { + $content = str_replace( '"id":' . absint( $old_id) . ',', '"id":' . absint( $new_id ) . ',', $content ); + } + return $content; + } /** * Retrieves a collection of objects. * @@ -780,8 +853,11 @@ public function process_pattern( WP_REST_Request $request ) { return rest_ensure_response( 'failed' ); } $content = $parameters['content']; + $forms = isset( $parameters['forms'] ) ? $parameters['forms'] : array(); $image_library = $parameters['image_library']; - //error_log( print_r( $image_library, true ) ); + if ( ! empty( $forms ) ) { + $content = $this->process_forms( $content, $forms ); + } // Find all urls. preg_match_all( '/https?:\/\/[^\'" ]+/i', $content, $match ); // preg_match_all( '#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $content, $match ); @@ -941,7 +1017,79 @@ public function get_pattern_content( WP_REST_Request $request ) { return rest_ensure_response( 'error' ); } + /** + * Retrieves a collection of objects. + * + * @param WP_REST_Request $request Full details about the request. + * @return WP_REST_Response Response object on success, or WP_Error object on failure. + */ + public function get_library_categories( WP_REST_Request $request ) { + $this->get_license_keys(); + $reload = $request->get_param( self::PROP_FORCE_RELOAD ); + $library = $request->get_param( self::PROP_LIBRARY ); + $library_url = $request->get_param( self::PROP_LIBRARY_URL ); + $key = $request->get_param( self::PROP_KEY ); + if ( ! empty( $library_url ) ) { + $library_url = rtrim( $library_url, '/' ) . '/wp-json/kadence-cloud/v1/categories/'; + } elseif ( ! empty( $library ) && 'pages' === $library ) { + $library_url = $this->remote_pages_cat_url; + $key = 'new-pages'; + } else { + $library_url = $this->remote_cat_url; + } + + $identifier = 'library-categories' . $library; + + if ( ! empty( $this->api_key ) ) { + $identifier .= '_' . $this->api_key; + } + + if ( ! empty( $key ) ) { + $identifier .= '_' . $key; + } + + if ( 'templates' !== $library && 'pages' !== $library && 'section' !== $library && 'template' !== $library ) { + $cloud_settings = json_decode( get_option( 'kadence_blocks_cloud' ), true ); + if ( ! empty( $cloud_settings['connections'][ $library ]['expires'] ) ) { + $expires = strtotime( get_date_from_gmt( $cloud_settings['connections'][ $library ]['expires'] ) ); + $now = strtotime( get_date_from_gmt( current_time( 'Y-m-d H:i:s' ) ) ); + + if ( $expires < $now ) { + $refresh = ( ! empty( $cloud_settings['connections'][ $library ]['refresh'] ) ? $cloud_settings['connections'][ $library ]['refresh'] : 'month' ); + if ( 'day' === $refresh ) { + $expires_add = DAY_IN_SECONDS; + } elseif ( 'week' === $refresh ) { + $expires_add = WEEK_IN_SECONDS; + } else { + $expires_add = MONTH_IN_SECONDS; + } + $cloud_settings['connections'][ $library ]['expires'] = gmdate( 'Y-m-d H:i:s', strtotime( current_time( 'mysql' ) ) + $expires_add ); + update_option( 'kadence_blocks_cloud', json_encode( $cloud_settings ) ); + $reload = true; + } + } + } + + // Check if we have a local file. + if ( ! $reload ) { + try { + return rest_ensure_response( $this->block_library_cache->get( $identifier ) ); + } catch ( NotFoundException $e ) { + } + } + + // Access via remote. + $response = $this->get_remote_library_categories( $library, $library_url, $key ); + + if ( 'error' === $response ) { + return rest_ensure_response( 'error' ); + } + + $this->block_library_cache->cache( $identifier, $response ); + + return rest_ensure_response( $response ); + } /** * Retrieves a collection of objects. * @@ -1660,6 +1808,53 @@ public function get_remote_library_contents( $library, $library_url, $key ) { return $contents; } + + /** + * Get remote file contents. + * + * @access public + * @return string Returns the remote URL contents. + */ + public function get_remote_library_categories( $library, $library_url, $key ) { + $site_url = get_original_domain(); + $args = array( + 'key' => $key, + 'site' => $site_url, + ); + if ( 'templates' === $library || 'section' === $library || 'pages' === $library || 'template' === $library ) { + $args['api_email'] = $this->api_email; + $args['api_key'] = $this->api_key; + $args['product_id'] = $this->product_id; + + if ( 'iThemes' === $this->api_email ) { + $args['site_url'] = $site_url; + } + } + if ( 'templates' === $library ) { + $args['request'] = 'blocks'; + } + // Get the response. + $api_url = add_query_arg( $args, $library_url ); + $response = wp_safe_remote_get( + $api_url, + array( + 'timeout' => 30, + ) + ); + // Early exit if there was an error. + if ( is_wp_error( $response ) || $this->is_response_code_error( $response ) ) { + return 'error'; + } + + // Get the CSS from our response. + $contents = wp_remote_retrieve_body( $response ); + // Early exit if there was an error. + if ( is_wp_error( $contents ) ) { + return 'error'; + } + + return $contents; + } /** * Get remote file contents. * @@ -2197,19 +2392,31 @@ public function get_image_info( $images, $target_src ) { */ public function check_for_local_image( $image_data ) { global $wpdb; - - // Thanks BrainstormForce for this idea. - // Check if image is already local based on meta key and custom hex value. - $image_id = $wpdb->get_var( - $wpdb->prepare( - 'SELECT `post_id` FROM `' . $wpdb->postmeta . '` - WHERE `meta_key` = \'_kadence_blocks_image_hash\' - AND `meta_value` = %s - ;', - sha1( $image_data['url'] ) - ) - ); - if ( $image_id ) { + $image_id = ''; + if ( ! empty( $image_data['url'] ) && strpos( $image_data['url'], get_site_url() ) !== false ) { + $image_id = attachment_url_to_postid( $image_data['url'] ); + if ( empty( $image_id ) ) { + // Get unsized version use Regular expression to find the pattern -numberxnumber + $pattern = "/-\d+x\d+/"; + // Replace the pattern with an empty string. + $cleaned_url = preg_replace( $pattern, '', $image_data['url'] ); + $image_id = attachment_url_to_postid( $cleaned_url ); + } + } + if ( empty( $image_id ) ) { + // Thanks BrainstormForce for this idea. + // Check if image is already local based on meta key and custom hex value. + $image_id = $wpdb->get_var( + $wpdb->prepare( + 'SELECT `post_id` FROM `' . $wpdb->postmeta . '` + WHERE `meta_key` = \'_kadence_blocks_image_hash\' + AND `meta_value` = %s + ;', + sha1( $image_data['url'] ) + ) + ); + } + if ( ! empty( $image_id ) ) { $local_image = array( 'id' => $image_id, 'url' => wp_get_attachment_url( $image_id ), @@ -2233,10 +2440,7 @@ public function check_for_image( $link = '' ) { if ( empty( $link ) ) { return false; } - if ( strpos( $link, 'prophecyimg.fly.dev' ) !== false ) { - return true; - } - if ( strpos( $link, 'images.pexels.com' ) !== false ) { + if ( strpos( $link, 'https://images.pexels.com' ) !== false ) { return true; } return preg_match( '/^((https?:\/\/)|(www\.))([a-z0-9-].?)+(:[0-9]+)?\/[\w\-]+\.(jpg|png|gif|webp|jpeg)\/?$/i', $link ); diff --git a/includes/class-local-gfonts.php b/includes/class-local-gfonts.php index f56d65378..fe19b86e8 100644 --- a/includes/class-local-gfonts.php +++ b/includes/class-local-gfonts.php @@ -348,7 +348,7 @@ public function get_remote_url_contents() { $user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:73.0) Gecko/20100101 Firefox/73.0'; } // Get the response. - $response = wp_remote_get( $this->remote_url, array( 'user-agent' => $user_agent ) ); + $response = wp_safe_remote_get( $this->remote_url, array( 'user-agent' => $user_agent ) ); // Early exit if there was an error. if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { return ''; diff --git a/src/plugins/prebuilt-library/cloud-library.js b/src/plugins/prebuilt-library/cloud-library.js index 1835053f1..0ef022f99 100644 --- a/src/plugins/prebuilt-library/cloud-library.js +++ b/src/plugins/prebuilt-library/cloud-library.js @@ -9,21 +9,27 @@ const { * External dependencies */ import Masonry from 'react-masonry-css' -import { debounce } from 'lodash'; /** * WordPress dependencies */ import { - withSelect, + useSelect, withDispatch, + useDispatch, } from '@wordpress/data'; -import { rawHandler } from '@wordpress/blocks'; +import { parse, rawHandler } from '@wordpress/blocks'; +import { debounce, isEqual } from 'lodash'; import { Component, Fragment, } from '@wordpress/element'; -import { compose } from '@wordpress/compose'; +import { store as noticesStore } from '@wordpress/notices'; +import { useMemo, useEffect, useState } from '@wordpress/element'; +import { + store as blockEditorStore, +} from '@wordpress/block-editor'; +import { getAsyncData } from './data-fetch/get-async-data'; import { Button, TextControl, @@ -45,37 +51,160 @@ import { __, sprintf } from '@wordpress/i18n'; import { SafeParseJSON } from '@kadence/helpers' -class CloudSections extends Component { - constructor() { - super( ...arguments ); - this.loadTemplateData = this.loadTemplateData.bind( this ); - this.onInsertContent = this.onInsertContent.bind( this ); - this.capitalizeFirstLetter = this.capitalizeFirstLetter.bind( this ); - this.reloadTemplateData = this.reloadTemplateData.bind( this ); - this.state = { - category: {}, - search: null, - tab: 'section', - items: false, - errorItems: false, - isLoading: false, - isImporting: false, - sidebar:false, - gridSize: 'normal', - categories: { 'category': 'Category' }, - }; - this.debouncedReloadTemplateData = debounce( this.reloadTemplateData.bind( this ), 200 ); +function CloudSections ( { + importContent, + clientId, + reload = false, + onReload, + tab, + libraries, + } ) { + const [ category, setCategory ] = useState( '' ); + const [ pageCategory, setPageCategory ] = useState( '' ); + const [ pageStyles, setPageStyles ] = useState(); + const [ search, setSearch ] = useState( null ); + const [ subTab, setSubTab ] = useState( '' ); + const [ patterns, setPatterns ] = useState( false ); + const [ pages, setPages ] = useState( false ); + const [ sidebar, setSidebar ] = useState( '' ); + const [ context, setContext ] = useState( '' ); + const [ credits, setCredits ] = useState( '' ); + const [ contextTab, setContextTab ] = useState( '' ); + const [ localContexts, setLocalContexts ] = useState( false ); + const [ imageCollection, setImageCollection ] = useState( {} ); + const [ teamCollection, setTeamCollection ] = useState( {} ); + const [ categories, setCategories ] = useState( {} ); + const [ categoryListOptions, setCategoryListOptions ] = useState( [] ); + const [ styleListOptions, setStyleListOptions ] = useState( [] ); + const [ stateGridSize, setGridSize ] = useState( ''); + const [ contextListOptions, setContextListOptions ] = useState( [] ); + const [ pagesCategories, setPagesCategories ] = useState( {} ); + const [ pageCategoryListOptions, setPageCategoryListOptions ] = useState( [] ); + const [ pageContextListOptions, setPageContextListOptions ] = useState( [] ); + const [ isLoading, setIsLoading ] = useState( false ); + const [ isImporting, setIsImporting ] = useState( false ); + const [ isError, setIsError ] = useState( false ); + const [ isErrorType, setIsErrorType ] = useState( 'general' ); + + const activeStorage = SafeParseJSON( localStorage.getItem( 'kadenceBlocksPrebuilt' ), true ); + const savedSelectedCategory = ( undefined !== activeStorage?.kbCat && '' !== activeStorage?.kbCat ? activeStorage.kbCat : 'all' ); + const savedSelectedPageCategory = ( undefined !== activeStorage?.kbPageCat && '' !== activeStorage?.kbPageCat ? activeStorage.kbPageCat : 'home' ); + const selectedCategory = ( category ? category : savedSelectedCategory ); + const selectedPageCategory = ( pageCategory ? pageCategory : savedSelectedPageCategory ); + const selectedSubTab = ( subTab ? subTab : 'patterns' ); + + const { createErrorNotice } = useDispatch( + noticesStore + ); + + // Setting category options + useEffect( () => { + setCategoryListOptions( Object.keys( categories ).map( function( key, index ) { + return { value: ( 'category' === key ? 'all' : key ), label: ( 'category' === key ? __( 'All', 'kadence-blocks' ) : categories[key] ) } + } ) ); + }, [ categories ] ); + + // Setting style options + useEffect( () => { + const patternStyles = Object.keys( patterns ).map( function( key ) { + return patterns[ key ].styles; + } ); + + // If array is empty, return + if ( ! patternStyles.length ) { + return; + } + + // Clear duplicates + const uniqueMap = new Map(); + patternStyles.forEach( ( item ) => { + if ( ! item ) { + return; + } + const key = Object.keys( item )[ 0 ]; + const value = item[ key ]; + uniqueMap.set( value, item ); + } ); + + const uniqueArray = Array.from( uniqueMap.values() ); + const styleOptions = uniqueArray.map( function( key ) { + const keyValue = Object.keys( key )[ 0 ]; + const keyName = key[ keyValue ]; + return { value: keyValue, label: keyName }; + } ); + + setStyleListOptions( styleOptions ); + }, [ patterns ] ); + + useEffect( () => { + setPageCategoryListOptions( Object.keys( pagesCategories ).map( function( key, index ) { + return { value: ( 'category' === key ? 'all' : key ), label: ( 'category' === key ? __( 'All', 'kadence-blocks' ) : pagesCategories[key] ) } + } ) ); + let tempPageContexts = []; + Object.keys( pagesCategories ).map( function( key, index ) { + if ( 'category' !== key ) { + tempPageContexts.push( { value: ( 'category' === key ? 'all' : key ), label: ( 'category' === key ? __( 'All', 'kadence-blocks' ) : pagesCategories[key] ) } ); + } + } ); + setPageContextListOptions( tempPageContexts ); + }, [ pagesCategories ] ); + const { getPatterns, getPattern, processPattern, getPatternCategories } = getAsyncData(); + const forceRefreshLibrary = () => { + if ( ! isLoading && patterns ) { + setPatterns( JSON.parse(JSON.stringify(patterns)) ); + } + if ( ! isLoading && pages ) { + setPages( JSON.parse(JSON.stringify(pages)) ); + } } - onInsertContent( blockcode ) { - this.importProcess( blockcode ); + async function onInsertContent( pattern ) { + setIsImporting( true ); + // const patternSend = { + // id: pattern.id, + // slug:pattern.slug, + // } + let action = []; + if ( tab !== 'section' ) { + action = libraries.filter( obj => { + return obj.slug === tab; + }); + } + if ( action === undefined || action.length == 0 ) { + const cloudSettings = kadence_blocks_params?.cloud_settings ? JSON.parse( kadence_blocks_params.cloud_settings ) : {}; + if ( cloudSettings && cloudSettings['connections'] ) { + action = cloudSettings['connections'].filter( obj => { + return obj.slug === tab; + }); + } + } + if ( action === undefined || action.length == 0 ) { + if ( typeof kadence_blocks_params?.prebuilt_libraries === 'object' && kadence_blocks_params?.prebuilt_libraries !== null ) { + action = kadence_blocks_params.prebuilt_libraries.filter( obj => { + return obj.slug === tab; + }); + } + } + if ( action?.[0]?.url ) { + const response = await getPattern( tab, 'pattern', ( pattern?.id ? pattern.id : '' ), 'light', ( action?.[0]?.url ? action[0].url : '' ), action?.[0]?.key ? action[0].key : '' ); + if ( response ) { + try { + const tempContent = JSON.parse( response ); + if ( tempContent ) { + pattern.content = tempContent; + } + } catch ( e ) { } + } + } + if ( pattern?.content ) { + processImportContent( pattern ); + } } - importProcess( blockcode ) { - this.setState( { isImporting: true } ); + const ajaxImportProcess = ( blockcode ) => { var data = new FormData(); - data.append( 'action', 'kadence_import_process_data' ); + data.append( 'action', 'kadence_import_process_image_data' ); data.append( 'security', kadence_blocks_params.ajax_nonce ); data.append( 'import_content', blockcode ); - var control = this; + data.append( 'image_library', JSON.stringify( imageCollection ) ); jQuery.ajax( { method: 'POST', url: kadence_blocks_params.ajax_url, @@ -85,423 +214,452 @@ class CloudSections extends Component { } ) .done( function( response, status, stately ) { if ( response ) { - //console.log( response ); - control.props.import( response ); - control.setState( { isImporting: false } ); + importContent( response, clientId ); + } else { + setIsError( true ); + setIsErrorType( 'reload' ); } + setIsImporting( false ); }) .fail( function( error ) { console.log( error ); - control.setState( { isImporting: false } ); + setIsError( true ); + setIsErrorType( 'reload' ); + setIsImporting( false ); }); } - capitalizeFirstLetter( string ) { - return string.charAt( 0 ).toUpperCase() + string.slice( 1 ); - } - reloadTemplateData() { - this.setState( { errorItems: false, isLoading: true, items: 'loading', tab: this.props.tab } ); - let action = {} - if ( this.props.tab !== 'section' ) { - action = this.props.libraries.filter( obj => { - return obj.slug === this.props.tab; - }); + async function processImportContent( pattern ) { + const response = await processPattern( pattern.content, imageCollection, ( pattern?.forms ? pattern.forms : [] ) ); + if ( response === 'failed' ) { + // It could fail because cloudflare is blocking the request. Lets try with ajax. + ajaxImportProcess( blockCode, imageCollection ); + console.log( 'Import Process Failed when processing data through rest api... Trying ajax.' ); + } else { + importContent( response, clientId ); + setIsImporting( false ); } - var data = new FormData(); - data.append( 'action', 'kadence_import_reload_prebuilt_data' ); - data.append( 'security', kadence_blocks_params.ajax_nonce ); - data.append( 'package', this.props.tab ); - data.append( 'url', this.props.tab !== 'section' && action[0] && action[0].url ? action[0].url : '' ); - data.append( 'key', this.props.tab !== 'section' && action[0] && action[0].key ? action[0].key : '' ); - var control = this; - jQuery.ajax( { - method: 'POST', - url: kadence_blocks_params.ajax_url, - data: data, - contentType: false, - processData: false, - } ) - .done( function( response, status, stately ) { - if ( response ) { - const o = SafeParseJSON( response, false ); - if ( o ) { - const cats = { 'category': 'Category' }; - { Object.keys( o ).map( function( key, index ) { - //console.log( o[ key ].categories ); - if ( o[ key ].categories && typeof o[ key ].categories === "object") { - { Object.keys( o[ key ].categories ).map( function( ckey, i ) { - if ( ! cats.hasOwnProperty( ckey ) ) { - cats[ ckey ] = o[ key ].categories[ ckey ]; - } - } ) } - } - } ) } - control.setState( { items: o, errorItems: false, isLoading: false, categories: cats } ); - } else { - control.setState( { items: 'error', errorItems: true, isLoading: false } ); - } - } - }) - .fail( function( error ) { - console.log(error); - control.setState( { items: 'error', errorItems: true, isLoading: false } ); - }); } - loadTemplateData() { - this.setState( { errorItems: false, isLoading: true, items: 'loading', tab: this.props.tab } ); + + async function getLibraryContent( tempReload ) { + setIsLoading( true ); + setIsError( false ); + setIsErrorType( 'general' ); let action = []; - if ( this.props.tab !== 'section' ) { - action = this.props.libraries.filter( obj => { - return obj.slug === this.props.tab; + if ( tab !== 'section' ) { + action = libraries.filter( obj => { + return obj.slug === tab; }); } if ( action === undefined || action.length == 0 ) { - const cloudSettings = kadence_blocks_params.cloud_settings ? JSON.parse( kadence_blocks_params.cloud_settings ) : {}; + const cloudSettings = kadence_blocks_params?.cloud_settings ? JSON.parse( kadence_blocks_params.cloud_settings ) : {}; if ( cloudSettings && cloudSettings['connections'] ) { action = cloudSettings['connections'].filter( obj => { - return obj.slug === this.props.tab; + return obj.slug === tab; }); } } if ( action === undefined || action.length == 0 ) { - if ( typeof kadence_blocks_params.prebuilt_libraries === 'object' && kadence_blocks_params.prebuilt_libraries !== null ) { - this.setState( { actions: kadence_blocks_params.prebuilt_libraries.concat( this.state.actions ) } ); + if ( typeof kadence_blocks_params?.prebuilt_libraries === 'object' && kadence_blocks_params?.prebuilt_libraries !== null ) { action = kadence_blocks_params.prebuilt_libraries.filter( obj => { - return obj.slug === this.props.tab; + return obj.slug === tab; }); } } - var data = new FormData(); - data.append( 'action', 'kadence_import_get_prebuilt_data' ); - data.append( 'security', kadence_blocks_params.ajax_nonce ); - data.append( 'package', this.props.tab ); - data.append( 'url', this.props.tab !== 'section' && action[0] && action[0].url ? action[0].url : '' ); - data.append( 'key', this.props.tab !== 'section' && action[0] && action[0].key ? action[0].key : '' ); - var control = this; - jQuery.ajax( { - method: 'POST', - url: kadence_blocks_params.ajax_url, - data: data, - contentType: false, - processData: false, - } ) - .done( function( response, status, stately ) { - if ( response ) { - const o = SafeParseJSON( response, false ); - if ( o ) { - const cats = { 'category': 'Category' }; - { Object.keys( o ).map( function( key, index ) { - //console.log( o[ key ].categories ); - if ( o[ key ].categories && typeof o[ key ].categories === "object") { - { Object.keys( o[ key ].categories ).map( function( ckey, i ) { - if ( ! cats.hasOwnProperty( ckey ) ) { - cats[ckey] = o[ key ].categories[ ckey ]; - } - } ) } - } - } ) } - control.setState( { items: o, errorItems: false, isLoading: false, categories: cats } ); + if ( ! action?.[0]?.url ) { + setIsLoading( false ); + setIsError( true ); + setIsErrorType( 'general' ); + return; + } + const response = await getPatterns( tab, tempReload, action?.[0]?.url ? action[0].url : '', action?.[0]?.key ? action[0].key : '' ); + if ( response === 'failed' ) { + console.log( 'Permissions Error getting library Content' ); + if ( subTab === 'pages' ) { + setPages( 'error' ); + } else { + setPatterns( 'error' ); + } + setIsError( true ); + setIsErrorType( 'reload' ); + setIsLoading( false ); + } else if ( response === 'error' ) { + console.log( 'Error getting library Content.' ); + if ( subTab === 'pages' ) { + setPages( 'error' ); + } else { + setPatterns( 'error' ); + } + setIsError( true ); + setIsLoading( false ); + } else { + const o = SafeParseJSON( response, false ); + if ( o ) { + const categories = await getPatternCategories( tab, tempReload, action?.[0]?.url ? action[0].url : '', action?.[0]?.key ? action[0].key : '' ); + if ( categories ) { + const catOrder = SafeParseJSON( categories, false ); + if ( subTab === 'pages' ) { + const pageCats = catOrder ? catOrder : {}; + kadence_blocks_params.library_pages = o; + { Object.keys( o ).map( function( key, index ) { + if ( o[ key ].categories && typeof o[ key ].categories === "object") { + { Object.keys( o[ key ].categories ).map( function( ckey, i ) { + if ( ! pageCats.hasOwnProperty( ckey ) ) { + pageCats[ ckey ] = o[ key ].categories[ ckey ]; + } + } ) } + } + } ) } + setPages( o ); + setPagesCategories( JSON.parse(JSON.stringify( pageCats ) ) ); + } else { + const cats = catOrder ? catOrder : {}; + kadence_blocks_params.library_sections = o; + { Object.keys( o ).map( function( key, index ) { + if ( o[ key ].categories && typeof o[ key ].categories === "object") { + { Object.keys( o[ key ].categories ).map( function( ckey, i ) { + if ( ! cats.hasOwnProperty( ckey ) ) { + cats[ ckey ] = o[ key ].categories[ ckey ]; + } + } ) } + } + } ) } + setPatterns( o ); + setCategories( JSON.parse(JSON.stringify( cats ) ) ); + } } else { - control.setState( { items: 'error', errorItems: true, isLoading: false } ); + if ( subTab === 'pages' ) { + setPages( 'error' ); + } else { + setPatterns( 'error' ); + } + setIsError( true ); } + } else { + if ( subTab === 'pages' ) { + setPages( 'error' ); + } else { + setPatterns( 'error' ); + } + setIsError( true ); } - }) - .fail( function( error ) { - console.log(error); - control.setState( { items: 'error', errorItems: true, isLoading: false } ); - }); + setIsLoading( false ); + } } - render() { - if ( this.props.reload ) { - this.props.onReload(); - this.debouncedReloadTemplateData(); + useEffect( () => { + if ( reload && ! isLoading ) { + onReload(); + getLibraryContent( true ); + } else if ( ! isLoading ) { + getLibraryContent( false ); } - const activePanel = SafeParseJSON( localStorage.getItem( 'kadenceBlocksPrebuilt' ), true ); - const sidebar_saved_enabled = ( activePanel && activePanel['sidebar'] ? activePanel['sidebar'] : 'show' ); - const sidebarEnabled = ( this.state.sidebar ? this.state.sidebar : sidebar_saved_enabled ); - const roundAccurately = (number, decimalPlaces) => Number(Math.round(Number(number + "e" + decimalPlaces)) + "e" + decimalPlaces * -1); - const libraryItems = this.props.tab !== this.state.tab ? false : this.state.items; - const categoryItems = this.state.categories; - const savedGridSize = ( activePanel && activePanel['grid'] ? activePanel['grid'] : 'normal' ); - const gridSize = ( this.state.gridSize ? this.state.gridSize : savedGridSize ); - const catOptions = Object.keys( categoryItems ).map( function( key, index ) { - return { value: ( 'category' === key ? 'all' : key ), label: categoryItems[key] } - } ); - const sideCatOptions = Object.keys( categoryItems ).map( function( key, index ) { - return { value: ( 'category' === key ? 'all' : key ), label: ( 'category' === key ? __( 'All', 'kadence-blocks' ) : categoryItems[key] ) } - } ); - const getActiveCat = ( this.state.category[activePanel.activeTab] ? this.state.category[activePanel.activeTab] : 'all' ); - const control = this; - let breakpointColumnsObj = { - default: 5, - 1600: 4, - 1200: 3, - 500: 2, + }, [reload, tab] ); + const activePanel = SafeParseJSON( localStorage.getItem( 'kadenceBlocksPrebuilt' ), true ); + const sidebar_saved_enabled = ( activePanel && activePanel['sidebar'] ? activePanel['sidebar'] : 'show' ); + const sidebarEnabled = ( sidebar ? sidebar : sidebar_saved_enabled ); + const roundAccurately = (number, decimalPlaces) => Number(Math.round(Number(number + "e" + decimalPlaces)) + "e" + decimalPlaces * -1); + const categoryItems = categories; + const savedGridSize = ( activePanel && activePanel['grid'] ? activePanel['grid'] : 'normal' ); + const gridSize = ( stateGridSize ? stateGridSize : savedGridSize ); + const catOptions = Object.keys( categoryItems ).map( function( key, index ) { + return { value: ( 'category' === key ? 'all' : key ), label: categoryItems[key] } + } ); + const sideCatOptions = Object.keys( categoryItems ).map( function( key, index ) { + return { value: ( 'category' === key ? 'all' : key ), label: ( 'category' === key ? __( 'All', 'kadence-blocks' ) : categoryItems[key] ) } + } ); + const getActiveCat = ( category[activePanel.activeTab] ? category[activePanel.activeTab] : 'all' ); + const control = this; + let breakpointColumnsObj = { + default: 5, + 1600: 4, + 1200: 3, + 500: 2, + }; + if ( gridSize === 'large' ) { + breakpointColumnsObj = { + default: 4, + 1600: 3, + 1200: 2, + 500: 1, + }; + } + if ( sidebarEnabled === 'show' ) { + breakpointColumnsObj = { + default: 4, + 1600: 3, + 1200: 2, + 500: 1, }; if ( gridSize === 'large' ) { breakpointColumnsObj = { - default: 4, - 1600: 3, + default: 3, + 1600: 2, 1200: 2, 500: 1, }; } - if ( sidebarEnabled === 'show' ) { - breakpointColumnsObj = { - default: 4, - 1600: 3, - 1200: 2, - 500: 1, - }; - if ( gridSize === 'large' ) { - breakpointColumnsObj = { - default: 3, - 1600: 2, - 1200: 2, - 500: 1, - }; - } - } - return ( -