From 9eb8f619668e52ac3e89d50abb037b27fe2f4ae2 Mon Sep 17 00:00:00 2001 From: Ben Ritner Date: Wed, 14 Feb 2024 16:35:20 -0700 Subject: [PATCH] get categories --- ...dence-blocks-prebuilt-library-rest-api.php | 159 +++++++++++++++++- src/plugins/prebuilt-library/cloud-library.js | 72 ++++---- .../data-fetch/get-async-data.js | 25 +++ src/plugins/prebuilt-library/editor.scss | 5 - src/plugins/prebuilt-library/pattern-list.js | 68 +++++--- src/plugins/settings.js | 2 +- 6 files changed, 262 insertions(+), 69 deletions(-) diff --git a/includes/class-kadence-blocks-prebuilt-library-rest-api.php b/includes/class-kadence-blocks-prebuilt-library-rest-api.php index 6dabd0f7e..522ddaf21 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', @@ -964,7 +992,7 @@ public function get_pattern_content( WP_REST_Request $request ) { } // Get the response. $api_url = add_query_arg( $args, $library_url ); - $response = wp_safe_remote_get( + $response = wp_remote_get( $api_url, array( 'timeout' => 20, @@ -989,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. * @@ -1688,7 +1788,54 @@ public function get_remote_library_contents( $library, $library_url, $key ) { } // Get the response. $api_url = add_query_arg( $args, $library_url ); - $response = wp_safe_remote_get( + $response = wp_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. + * + * @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_remote_get( $api_url, array( 'timeout' => 30, @@ -1838,7 +1985,7 @@ public function get_remote_remaining_credits() { $args['email'] = $this->api_email; } $api_url = add_query_arg( $args, $this->remote_credits_url . 'get-remaining' ); - $response = wp_safe_remote_get( + $response = wp_remote_get( $api_url, array( 'timeout' => 20, @@ -1866,7 +2013,7 @@ public function get_remote_remaining_credits() { */ public function get_remote_image_collections() { $api_url = $this->remote_ai_url . 'images/collections'; - $response = wp_safe_remote_get( + $response = wp_remote_get( $api_url, array( 'timeout' => 20, @@ -1975,7 +2122,7 @@ public function get_keyword_suggestions( WP_REST_Request $request ) { */ public function get_remote_industry_verticals() { $api_url = $this->remote_ai_url . 'verticals'; - $response = wp_safe_remote_get( + $response = wp_remote_get( $api_url, array( 'timeout' => 20, @@ -2136,7 +2283,7 @@ public function import_image( $image_data ) { return $local_image['image']; } $file_content = wp_remote_retrieve_body( - wp_safe_remote_get( + wp_remote_get( $image_data['url'], array( 'timeout' => '60', diff --git a/src/plugins/prebuilt-library/cloud-library.js b/src/plugins/prebuilt-library/cloud-library.js index 823ebe4b7..0ef022f99 100644 --- a/src/plugins/prebuilt-library/cloud-library.js +++ b/src/plugins/prebuilt-library/cloud-library.js @@ -148,7 +148,7 @@ function CloudSections ( { } ); setPageContextListOptions( tempPageContexts ); }, [ pagesCategories ] ); - const { getPatterns, getPattern, processPattern } = getAsyncData(); + const { getPatterns, getPattern, processPattern, getPatternCategories } = getAsyncData(); const forceRefreshLibrary = () => { if ( ! isLoading && patterns ) { setPatterns( JSON.parse(JSON.stringify(patterns)) ); @@ -190,7 +190,6 @@ function CloudSections ( { try { const tempContent = JSON.parse( response ); if ( tempContent ) { - console.log( tempContent ); pattern.content = tempContent; } } catch ( e ) { } @@ -295,34 +294,45 @@ function CloudSections ( { } else { const o = SafeParseJSON( response, false ); if ( o ) { - if ( subTab === 'pages' ) { - const pageCats = {}; - 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 ) ) ); + 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 { - const cats = {}; - 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 ) ) ); + if ( subTab === 'pages' ) { + setPages( 'error' ); + } else { + setPatterns( 'error' ); + } + setIsError( true ); } } else { if ( subTab === 'pages' ) { @@ -342,7 +352,7 @@ function CloudSections ( { } else if ( ! isLoading ) { getLibraryContent( false ); } - }, [reload, selectedSubTab] ); + }, [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 ); @@ -544,7 +554,6 @@ function CloudSections ( { { Object.keys( patterns ).map( function( key, index ) { const name = patterns[key].name; const slug = patterns[key].slug; - const content = patterns[key].content; const image = patterns[key].image; const imageWidth = patterns[key].imageW; const imageHeight = patterns[key].imageH; @@ -554,7 +563,6 @@ function CloudSections ( { const pro = patterns[key].pro; const locked = patterns[key].locked; const descriptionId = `${ slug }_kb_cloud__item-description`; - console.log( patterns[key] ); if ( ( 'all' === getActiveCat || Object.keys( categories ).includes( getActiveCat ) ) && ( ! search || ( keywords && keywords.some( x => x.toLowerCase().includes( search.toLowerCase() ) ) ) ) ) { return (
diff --git a/src/plugins/prebuilt-library/data-fetch/get-async-data.js b/src/plugins/prebuilt-library/data-fetch/get-async-data.js index 069d19633..6dd0c372d 100644 --- a/src/plugins/prebuilt-library/data-fetch/get-async-data.js +++ b/src/plugins/prebuilt-library/data-fetch/get-async-data.js @@ -362,6 +362,30 @@ export function getAsyncData() { return 'failed'; } } + /** + * Get library data. + * + * @param {(object)} userData + * + * @return {Promise} Promise returns object + */ + async function getPatternCategories( library, reload, library_url = null, key = null ) { + try { + const response = await apiFetch( { + path: addQueryArgs( '/kb-design-library/v1/get_library_categories', { + force_reload: reload, + library: library, + library_url: library_url ? library_url : '', + key: key ? key : library, + } ), + } ); + return response; + } catch (error) { + const message = error?.message ? error.message : error; + console.log(`ERROR: ${ message }`); + return 'failed'; + } + } /** * Get library data. @@ -446,6 +470,7 @@ export function getAsyncData() { getAIWizardData, getCollectionByIndustry, getPatterns, + getPatternCategories, getPattern, processPattern, getLocalAIContexts, diff --git a/src/plugins/prebuilt-library/editor.scss b/src/plugins/prebuilt-library/editor.scss index 4ac438d91..7dded90e0 100644 --- a/src/plugins/prebuilt-library/editor.scss +++ b/src/plugins/prebuilt-library/editor.scss @@ -1054,11 +1054,6 @@ button.components-button.kb-trigger-ai.has-icon { max-height: calc(95vh - 80px); padding: 5px 20px 0px; } -.kb-cloud-library-sidebar .kb-library-sidebar-bottom { - overflow: auto; - height: 100%; - max-height: calc(95vh - 284px); -} .kb-wizard-advanced-text { flex-grow: 1; } diff --git a/src/plugins/prebuilt-library/pattern-list.js b/src/plugins/prebuilt-library/pattern-list.js index f161a1447..96259e861 100644 --- a/src/plugins/prebuilt-library/pattern-list.js +++ b/src/plugins/prebuilt-library/pattern-list.js @@ -461,6 +461,7 @@ function PatternList( { styles, } ) { const [ failedAI, setFailedAI ] = useState( false ); + const [ importing, setImporting ] = useState( false ); const [ failedAIType, setFailedAIType ] = useState( 'general' ); const [rootScroll, setRootScroll] = useState(); const [ categoryFilter, setCategoryFilter ] = useState( [] ); @@ -481,10 +482,11 @@ function PatternList( { const isAuthorized = window?.kadence_blocks_params?.isAuthorized; const isAIDisabled = window?.kadence_blocks_params?.isAIDisabled ? true : false; const data_key = ( window?.kadence_blocks_params?.proData?.api_key ? kadence_blocks_params.proData.api_key : '' ); - async function onSelectBlockPattern( info ) { + async function onSelectBlockPattern( pattern ) { + setImporting( true ); const patternSend = { - id: info.id, - slug:info.slug, + id: pattern.id, + slug:pattern.slug, type: 'pattern', style: selectedStyle ? selectedStyle : 'light', } @@ -498,19 +500,21 @@ function PatternList( { } } catch ( e ) { } } - console.log( newInfo ); - // sendEvent( 'pattern_added_to_page', { - // categories: info.categories, - // id: info.id, - // slug: info.slug, - // name: info.name, - // style: selectedStyle ? selectedStyle : 'light', - // is_ai: contextTab === 'context', - // // Only send context when using AI patterns. - // context: contextTab === 'context' ? contextLabel : '', - // } ); + if ( ! newInfo && pattern?.content ) { + newInfo = pattern.content; + } + sendEvent( 'pattern_added_to_page', { + categories: pattern.categories, + id: pattern.id, + slug: pattern.slug, + name: pattern.name, + style: selectedStyle ? selectedStyle : 'light', + is_ai: contextTab === 'context', + // Only send context when using AI patterns. + context: contextTab === 'context' ? contextLabel : '', + } ); - + newInfo = replaceImages( newInfo, imageCollection, pattern.categories, pattern.id, pattern.variation, teamCollection); newInfo = wooContent( newInfo ); if ( userData?.locationType && 'Online Only' !== userData?.locationType && userData?.locationInput ) { newInfo = replaceAddressContent( newInfo, userData.locationInput ); @@ -528,8 +532,12 @@ function PatternList( { } const thePatterns = useMemo( () => { let allPatterns = []; + let variation = 0; Object.keys( patterns ).map( function( key, index ) { const temp = []; + if ( variation === 11 ) { + variation = 0; + } temp.title = patterns[ key ].name; temp.name = patterns[ key ].name; temp.image = patterns[ key ].image; @@ -545,15 +553,13 @@ function PatternList( { if ( patterns[ key ]?.html ) { temp.html = replaceMasks( patterns[ key ].html ); } - if ( index === 1 ) { - console.log( patterns[ key ] ); - console.log( patterns[ key ].content ); - } temp.content = patterns[ key ]?.content || ''; temp.pro = patterns[ key ].pro; temp.locked = ( patterns[ key ].pro && 'true' !== kadence_blocks_params.pro ? true : false ); temp.proRender = false; temp.viewportWidth = 1200; + temp.variation = variation; + variation ++; allPatterns.push( temp ); } ); return allPatterns; @@ -636,10 +642,10 @@ function PatternList( { variation = 0; } if ( item?.html ) { - item['html'] = replaceImages( item.html, imageCollection, item.categories, item.id, variation, teamCollection); - item['content'] = replaceImages( item.content, imageCollection, item.categories, item.id, variation, teamCollection); + item['html'] = replaceImages( item.html, imageCollection, item.categories, item.id, item.variation, teamCollection); + item['content'] = replaceImages( item.content, imageCollection, item.categories, item.id, item.variation, teamCollection); } else { - item['content'] = replaceImages( item.content, imageCollection, item.categories, item.id, variation, teamCollection); + item['content'] = replaceImages( item.content, imageCollection, item.categories, item.id, item.variation, teamCollection); } variation ++; return item; @@ -653,13 +659,13 @@ function PatternList( { variation = 0; } if ( item?.html) { - item['html'] = replaceContent( item.html, allContext, item.categories, aiContext, item.name, true ); - item['content'] = replaceContent( item.content, allContext, item.categories, aiContext, item.name ); + item['html'] = replaceContent( item.html, allContext, item.categories, aiContext, item.variation, true ); + item['content'] = replaceContent( item.content, allContext, item.categories, aiContext, item.variation ); if ( userData?.locationType && 'Online Only' !== userData?.locationType && userData?.locationInput ) { item['html'] = replaceAddressContent( item['html'], userData.locationInput ); } } else { - item['content'] = replaceContent( item.content, allContext, item.categories, aiContext, variation ); + item['content'] = replaceContent( item.content, allContext, item.categories, aiContext, item.variation ); } variation ++; return item; @@ -817,6 +823,18 @@ function PatternList( { ); } + if ( importing ) { + return ( +
+
+
+ +

{ __( 'Preparing Content...', 'kadence-blocks' ) }

+
+
+
+ ); + } return (
diff --git a/src/plugins/settings.js b/src/plugins/settings.js index 1a29188f5..bfa88d170 100644 --- a/src/plugins/settings.js +++ b/src/plugins/settings.js @@ -29,7 +29,7 @@ function KadenceSetting( props ) { const saveConfig = (key, value) => { setIsSaving(true); - console.log('saveConfig', key, value); + // console.log('saveConfig', key, value); const config = (kadence_blocks_params.globalSettings ? JSON.parse(kadence_blocks_params.globalSettings) : {}); config[key] = value; const settingModel = new wp.api.models.Settings({kadence_blocks_settings: JSON.stringify(config)});