Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix dynamic bg images #1513

Merged
merged 9 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/blocks/element/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@
"usesContext": [
"generateblocks/queryData",
"generateblocks/queryType",
"generateblocks/paginationType"
"generateblocks/paginationType",
"postId"
],
"editorScript": "file:./index.js",
"editorStyle": [
Expand Down
20 changes: 5 additions & 15 deletions src/blocks/element/components/InlineBackgroundImage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function InlineBackgroundImage( { htmlAttributes, setAttributes, styles,
}

const inlineBackgroundPart = styleParts.find( ( part ) => (
part.startsWith( '--inline-bg-image' )
part.trim().startsWith( '--inline-bg-image' )
) );

if ( ! inlineBackgroundPart ) {
Expand All @@ -26,25 +26,15 @@ export function InlineBackgroundImage( { htmlAttributes, setAttributes, styles,
function onChange( value ) {
const { style = '' } = htmlAttributes;

if ( ! value ) {
if ( style ) {
const newHtmlAttributes = { ...htmlAttributes };
delete newHtmlAttributes.style;
setAttributes( {
htmlAttributes: newHtmlAttributes,
} );
}

return;
}

const styleParts = style
.split( ';' )
.filter( ( part ) => (
'' !== part && ! part.startsWith( '--inline-bg-image' )
'' !== part && ! part.trim().startsWith( '--inline-bg-image' )
) );

styleParts.push( '--inline-bg-image: url(' + value + ')' );
if ( value ) {
styleParts.push( '--inline-bg-image: url(' + value + ')' );
}

setAttributes( {
htmlAttributes: {
Expand Down
20 changes: 20 additions & 0 deletions src/dynamic-tags/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import apiFetch from '@wordpress/api-fetch';

export async function replaceTags( content, context = {} ) {
// Define an async function to fetch data
try {
const response = await apiFetch( {
path: '/generateblocks/v1/dynamic-tag-replacements',
method: 'POST',
data: {
content,
context,
},
} );

return response;
} catch ( error ) {
console.error( 'Error fetching data:', error ); // eslint-disable-line no-console
return '';
}
}
28 changes: 8 additions & 20 deletions src/hoc/withDynamicTag.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, useEffect } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { replaceTags } from '../dynamic-tags/utils';

export function withDynamicTag( WrappedComponent ) {
return ( ( props ) => {
Expand All @@ -16,6 +16,7 @@ export function withDynamicTag( WrappedComponent ) {

const [ dynamicTagValue, setDynamicTagValue ] = useState( '' );
const [ contentMode, setContentMode ] = useState( 'edit' );

const getContentValue = () => {
if ( 'img' === tagName ) {
return htmlAttributes?.src;
Expand All @@ -40,27 +41,14 @@ export function withDynamicTag( WrappedComponent ) {
return;
}

// Define an async function to fetch data
const fetchData = async() => {
try {
const response = await apiFetch( {
path: '/generateblocks/v1/dynamic-tag-replacements',
method: 'POST',
data: {
content: contentValue,
context,
},
} );
async function fetchData() {
const response = await replaceTags( contentValue, context );

setDynamicTagValue( response );
} catch ( error ) {
console.error( 'Error fetching data:', error ); // eslint-disable-line no-console
setDynamicTagValue( null ); // Handle error case
}
};
setDynamicTagValue( response );
}

fetchData(); // Call the async function
}, [ contentValue, contentMode ] );
fetchData();
}, [ contentValue, contentMode, context ] );

return (
<WrappedComponent
Expand Down
41 changes: 37 additions & 4 deletions src/hoc/withHtmlAttributes.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useEffect, useMemo } from '@wordpress/element';
import { useEffect, useMemo, useState } from '@wordpress/element';
import { InspectorAdvancedControls } from '@wordpress/block-editor';
import { TextControl } from '@wordpress/components';

import { convertInlineStyleStringToObject } from '@utils/convertInlineStyleStringToObject';
import { replaceTags } from '../dynamic-tags/utils';

export const booleanAttributes = [
'allowfullscreen',
Expand Down Expand Up @@ -68,16 +69,48 @@ export function withHtmlAttributes( WrappedComponent ) {
uniqueId,
} = attributes;

const [ styleWithReplacements, setStyleWithReplacements ] = useState( '' );
const { style = '', href, ...otherAttributes } = htmlAttributes;
const inlineStyleObject = typeof style === 'string'
? convertInlineStyleStringToObject( style )
: style;

useEffect( () => {
async function getReplacements() {
// Check if any replacements need to be made if not, do nothing.
if ( ! style.includes( '{{' ) ) {
setStyleWithReplacements( style );
return;
}

const replacements = await replaceTags( style, context );

if ( ! replacements.length ) {
setStyleWithReplacements( style );
return;
}

const withReplacements = replacements.reduce( ( acc, { original, replacement, fallback } ) => {
if ( ! replacement ) {
return acc.replaceAll( original, fallback );
}

return acc.replaceAll( original, replacement );
}, style );

setStyleWithReplacements( withReplacements ? withReplacements : style );
}

getReplacements();
}, [ style, context ] );

const inlineStyleObject = typeof styleWithReplacements === 'string'
? convertInlineStyleStringToObject( styleWithReplacements )
: '';
const combinedAttributes = {
...otherAttributes,
style: inlineStyleObject,
'data-gb-id': uniqueId,
'data-context-post-id': context?.postId ?? 0,
};

const frontendHtmlAttributes = useMemo( () => {
if ( Array.isArray( htmlAttributes ) ) {
return {};
Expand Down
Loading