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

Feature: Add campaign title block #7648

Merged
merged 14 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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
42 changes: 42 additions & 0 deletions src/Campaigns/Actions/RegisterCampaignBlocks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Give\Campaigns\Actions;

use Give\Framework\Support\Facades\Scripts\ScriptAsset;

class RegisterCampaignBlocks
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
{
public function __invoke()
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
{
$blocks = glob(dirname(__DIR__) . '/Blocks/*', GLOB_ONLYDIR);

foreach ($blocks as $block) {
register_block_type(dirname(__DIR__) . '/Blocks/' . basename($block));
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
}

$this->enqueueBlocksAssets();
}

private function enqueueBlocksAssets()
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
{
$handleName = 'givewp-campaign-blocks';
$scriptAsset = ScriptAsset::get(GIVE_PLUGIN_DIR . 'build/campaignBlocks.asset.php');

wp_register_script(
$handleName,
GIVE_PLUGIN_URL . 'build/campaignBlocks.js',
$scriptAsset['dependencies'],
$scriptAsset['version'],
true
);

wp_enqueue_script($handleName);
wp_enqueue_style(
$handleName,
GIVE_PLUGIN_URL . 'build/campaignBlocks.css',
/** @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-components/#usage */
['wp-components'],
$scriptAsset['version']
);
}
}
27 changes: 27 additions & 0 deletions src/Campaigns/Actions/RegisterCampaignIdRestField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Give\Campaigns\Actions;

class RegisterCampaignIdRestField
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
{
public function __invoke()
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
{
register_rest_field(
'give_campaign_page',
'campaignId',
[
'get_callback' => function ($object) {
return get_post_meta($object['id'], 'campaignId', true);
},
'update_callback' => function ($value, $object) {
return update_post_meta($object->ID, 'campaignId', (int) $value);
},
'schema' => [
'description' => 'Campaign ID',
'type' => 'string',
'context' => ['view', 'edit'],
],
]
);
}
}
69 changes: 69 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "givewp/campaign-title-block",
"version": "1.0.0",
"title": "Campaign Title",
"category": "give",
"icon": "heading",
"description": "Displays the title of the campaign.",
"attributes": {
"campaignId": {
"type": "integer"
},
"headingLevel": {
"type": "number",
"default": 1
},
"textAlign": {
"type": "string"
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
}
},
"supports": {
"align": [
"wide",
"full"
],
"anchor": true,
"className": true,
"splitting": true,
"__experimentalBorder": {
"color": true,
"radius": true,
"style": true,
"width": true
},
"color": {
"gradients": true,
"link": true,
"__experimentalDefaultControls": {
"background": true,
"text": true
}
},
"spacing": {
"margin": true,
"padding": true,
"__experimentalDefaultControls": {
"margin": false,
"padding": false
}
},
"typography": {
"fontSize": true,
"lineHeight": true,
"__experimentalFontFamily": true,
"__experimentalFontStyle": true,
"__experimentalFontWeight": true,
"__experimentalLetterSpacing": true,
"__experimentalTextTransform": true,
"__experimentalTextDecoration": true,
"__experimentalWritingMode": true,
"__experimentalDefaultControls": {
"fontSize": true
}
}
},
"textdomain": "give",
"render": "file:./render.php"
}
75 changes: 75 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/edit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {
AlignmentControl,
BlockControls,
HeadingLevelDropdown,
InspectorControls,
useBlockProps,
} from '@wordpress/block-editor';
import {BaseControl, Icon, PanelBody, TextareaControl} from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import {CampaignSelector} from '../shared/components/CampaignSelector';
import useCampaign from '../shared/hooks/useCampaign';
import {__} from '@wordpress/i18n';
import {useSelect} from '@wordpress/data';
import {external} from '@wordpress/icons';

import './editor.scss';

export default function Edit({attributes, setAttributes}) {
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
const blockProps = useBlockProps();
const {campaign, hasResolved} = useCampaign(attributes.campaignId);

const adminBaseUrl = useSelect(
// @ts-ignore
(select) => select('core').getSite()?.url + '/wp-admin/edit.php?post_type=give_forms&page=give-campaigns',
[]
);

const editCampaignUrl = `${adminBaseUrl}&id=${attributes.campaignId}&tab=settings`;

return (
<div {...blockProps}>
<CampaignSelector attributes={attributes} setAttributes={setAttributes}>
<ServerSideRender block="givewp/campaign-title-block" attributes={attributes} />
</CampaignSelector>

{hasResolved && campaign && (
<InspectorControls>
<PanelBody title="Settings" initialOpen={true}>
<BaseControl label="Title">
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The BaseControl component requires an id attribute.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/WordPress/gutenberg/blob/trunk/packages/components/src/base-control/README.md#id

Per the docs, the only required attribute is children. Anyway, added here: 817d364

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The weird thing is that the IDE says it's required.

image

<TextareaControl
value={campaign.title}
readOnly={true}
onChange={() => null}
help={
<a
href={editCampaignUrl}
target="_blank"
rel="noopener noreferrer"
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
className="givewp-campaign-title-block__edit-campaign-link"
>
{__('Edit campaign title', 'give')}
<Icon icon={external} />
</a>
}
/>
</BaseControl>
</PanelBody>
</InspectorControls>
)}

<BlockControls>
<HeadingLevelDropdown
value={attributes.headingLevel}
onChange={(newLevel: string) => setAttributes({headingLevel: newLevel})}
/>
<AlignmentControl
value={attributes.textAlign}
onChange={(nextAlign) => {
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
setAttributes({textAlign: nextAlign});
}}
/>
</BlockControls>
</div>
);
}
13 changes: 13 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/editor.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.givewp-campaign-title-block {
&__edit-campaign-link {
display: inline-flex;
align-items: center;
gap: 0.125rem;

svg {
fill: currentColor;
height: 1.25rem;
width: 1.25rem;
}
}
}
12 changes: 12 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import metadata from './block.json';
import Edit from './edit';
import initBlock from '../shared/utils/init-block';

const {name} = metadata;

export {metadata, name};
export const settings = {
edit: Edit,
};

export const init = () => initBlock({name, metadata, settings});
27 changes: 27 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/render.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use Give\Campaigns\Models\Campaign;
use Give\Campaigns\Repositories\CampaignRepository;

if (empty($attributes) || !isset($attributes['campaignId'])) {
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
return;
}

/** @var Campaign $campaign */
$campaign = give(CampaignRepository::class)->getById($attributes['campaignId']);

if (! $campaign) {
return;
}

$headingLevel = isset($attributes['headingLevel']) ? (int) $attributes['headingLevel'] : 1;
$headingTag = 'h' . min(6, max(1, $headingLevel));

$textAlignClass = isset($attributes['textAlign']) ? 'has-text-align-' . $attributes['textAlign'] : '';
?>

<<?php
echo $headingTag; ?> <?php
echo wp_kses_data(get_block_wrapper_attributes(['class' => $textAlignClass])); ?>>
<?php echo esc_html($campaign->title); ?>
</<?php echo $headingTag; ?>>
9 changes: 9 additions & 0 deletions src/Campaigns/Blocks/blocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as campaignTitleBlock from './CampaignTitleBlock';

const getAllBlocks = () => {
return [campaignTitleBlock];
};

getAllBlocks().forEach((block) => {
block.init();
});
48 changes: 48 additions & 0 deletions src/Campaigns/Blocks/shared/components/CampaignDropdown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {PanelBody, SelectControl} from '@wordpress/components';
import {InspectorControls} from '@wordpress/block-editor';
import useCampaigns from '../hooks/useCampaigns';
import {Campaign} from '@givewp/campaigns/admin/components/types';
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
import {__} from '@wordpress/i18n';

export default function CampaignDropdown({campaignId, setAttributes, placement = 'sidebar'}) {
const {campaigns, hasResolved} = useCampaigns();

const options = (() => {
if (!hasResolved) {
return [{label: __('Loading...', 'give'), value: ''}];
}

if (campaigns.length) {
const campaignOptions = campaigns.map((campaign) => ({
label: campaign.title,
value: campaign.id.toString(),
}));

return [{label: __('Select...', 'give'), value: ''}, ...campaignOptions];
}

return [{label: __('No campaigns found.', 'give'), value: ''}];
})();

const dropdown = (
<SelectControl
label={__('Select a Campaign', 'give')}
value={campaignId || ''}
options={options}
disabled={options.length === 1}
onChange={(newValue) => setAttributes({campaignId: newValue ? parseInt(newValue) : null})}
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
/>
);

if (placement === 'sidebar') {
return (
<InspectorControls>
<PanelBody title={__('Campaign', 'give')} initialOpen={true}>
{dropdown}
</PanelBody>
</InspectorControls>
);
}

return dropdown;
}
28 changes: 28 additions & 0 deletions src/Campaigns/Blocks/shared/components/CampaignSelector.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import useCampaignId from '../hooks/useCampaignId';
import CampaignDropdown from './CampaignDropdown';

export function CampaignSelector({attributes, setAttributes, children}) {
const campaignId = useCampaignId(attributes, setAttributes);

return (
<>
{!campaignId && !attributes?.campaignId && (
<CampaignDropdown
campaignId={attributes?.campaignId}
setAttributes={setAttributes}
placement="inline"
/>
)}

{!campaignId && (
<CampaignDropdown
campaignId={attributes?.campaignId}
setAttributes={setAttributes}
placement="sidebar"
/>
)}

{attributes?.campaignId && children}
</>
);
}
11 changes: 11 additions & 0 deletions src/Campaigns/Blocks/shared/hooks/useCampaign.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {useEntityRecord} from '@wordpress/core-data';
import {Campaign} from '@givewp/campaigns/admin/components/types';

export default function useCampaign(campaignId) {
glaubersilva marked this conversation as resolved.
Show resolved Hide resolved
const data = useEntityRecord('givewp', 'campaign', campaignId);

return {
campaign: data?.record as Campaign,
hasResolved: data?.hasResolved,
};
}
20 changes: 20 additions & 0 deletions src/Campaigns/Blocks/shared/hooks/useCampaignId.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {useSelect} from '@wordpress/data';

export default function useCampaignId(attributes, setAttributes) {
const campaignIdFromContext = useSelect((select) => {
// @ts-ignore
const postType = select('core/editor').getCurrentPostType();

if (postType === 'give_campaign_page') {
// @ts-ignore
return select('core/editor').getEditedPostAttribute('campaignId');
}
return null;
}, []);

if (campaignIdFromContext && campaignIdFromContext !== attributes?.campaignId) {
setAttributes({campaignId: campaignIdFromContext});
}

return campaignIdFromContext;
}
Loading
Loading