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

Open
wants to merge 4 commits into
base: epic/campaigns
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions src/Campaigns/Actions/RegisterCampaignBlocks.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Give\Campaigns\Actions;

class RegisterCampaignBlocks
{
public function __invoke()
{
$blocks = glob(dirname(__DIR__) . '/Blocks/*', GLOB_ONLYDIR);

foreach ($blocks as $block) {
register_block_type(dirname(__DIR__) . '/Blocks/' . basename($block));
}
}
}
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
{
public function __invoke()
{
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'],
],
]
);
}
}
26 changes: 26 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"$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.",
"supports": {
"html": false
},
"attributes": {
"campaignId": {
"type": "integer"
},
"headingLevel": {
"type": "number",
"default": 1
}
},
"textdomain": "give",
"editorScript": "file:./../../../../build/Campaigns/Blocks/campaignTitleBlock.js",
"editorStyle": "file:./../../../../build/Campaigns/Blocks/campaignTitleBlock.css",
"render": "file:./render.php"
}
62 changes: 62 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/edit.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {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}) {
const blockProps = useBlockProps();
const {campaign, hasResolved} = useCampaign(attributes.campaignId);

const adminBaseUrl = useSelect(
(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">
<TextareaControl
value={campaign.title}
readOnly={true}
onChange={() => null}
help={
<a
href={editCampaignUrl}
target="_blank"
rel="noopener noreferrer"
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})}
/>
</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;
}
}
}
8 changes: 8 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {registerBlockType} from '@wordpress/blocks';
import metadata from './block.json';
import Edit from './edit';

// @ts-ignore
registerBlockType(metadata.name, {
edit: Edit
});
23 changes: 23 additions & 0 deletions src/Campaigns/Blocks/CampaignTitleBlock/render.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

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

if (empty($attributes) || !isset($attributes['campaignId'])) {
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));
?>

<<?php echo $headingTag; ?> <?php echo wp_kses_data(get_block_wrapper_attributes()); ?>>
<?php echo esc_html($campaign->title); ?>
</<?php echo $headingTag; ?>>
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';
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})}
/>
);

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) {
const data = useEntityRecord('givewp', 'campaign', campaignId);

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

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

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

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

return campaignIdFromContext;
}
11 changes: 11 additions & 0 deletions src/Campaigns/Blocks/shared/hooks/useCampaigns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {useEntityRecords} from '@wordpress/core-data';
import {Campaign} from '@givewp/campaigns/admin/components/types';

export default function useCampaigns() {
const data = useEntityRecords('givewp', 'campaign');

return {
campaigns: data?.records as Campaign[],
hasResolved: data?.hasResolved,
};
}
10 changes: 10 additions & 0 deletions src/Campaigns/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function boot(): void
$this->registerMigrations();
$this->registerRoutes();
$this->registerCampaignEntity();
$this->registerCampaignBlocks();
$this->setupCampaignForms();
}

Expand Down Expand Up @@ -148,4 +149,13 @@ private function setupCampaignForms()
Hooks::addAction('givewp_donation_form_created', AddCampaignFormFromRequest::class, 'visualFormBuilder');
Hooks::addAction('givewp_campaign_created', CreateDefaultCampaignForm::class);
}

/**
* @unreleased
*/
private function registerCampaignBlocks()
{
Hooks::addAction('rest_api_init', Actions\RegisterCampaignIdRestField::class);
Hooks::addAction('init', Actions\RegisterCampaignBlocks::class);
}
}
21 changes: 21 additions & 0 deletions wordpress-scripts-webpack.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* External Dependencies
*/
const fs = require('fs');
const path = require('path');

/**
Expand Down Expand Up @@ -63,6 +64,7 @@ module.exports = {
campaignEntity: srcPath('Campaigns/resources/entity.ts'),
campaignDetails: srcPath('Campaigns/resources/admin/campaign-details.tsx'),
adminBlocks: path.resolve(process.cwd(), 'blocks', 'load.js'),
...getDynamicEntries(srcPath('Campaigns/Blocks'), 'Campaigns/Blocks/'),
},
};

Expand All @@ -75,3 +77,22 @@ module.exports = {
function srcPath(relativePath) {
return path.resolve(process.cwd(), 'src', relativePath);
}

function getDynamicEntries(basePath, destinationPath = '') {
const entries = {};
const directories = fs.readdirSync(basePath, {withFileTypes: true});

directories.forEach((dir) => {
if (dir.isDirectory()) {
const blockPath = path.join(basePath, dir.name);
const indexPath = path.join(blockPath, 'index.ts');
const entryKey = dir.name.charAt(0).toLowerCase() + dir.name.slice(1);

if (fs.existsSync(indexPath)) {
entries[`${destinationPath}${entryKey}`] = indexPath;
}
}
});

return entries;
}
Loading