Skip to content

Commit

Permalink
New block: Knowledge Base Articles
Browse files Browse the repository at this point in the history
  • Loading branch information
ajaydsouza committed Dec 14, 2024
1 parent c5a2464 commit b035623
Show file tree
Hide file tree
Showing 12 changed files with 540 additions and 11 deletions.
44 changes: 44 additions & 0 deletions includes/blocks/build/kb-articles/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "knowledgebase/articles",
"version": "2.3.0",
"title": "Knowledge Base Articles",
"category": "design",
"icon": "book",
"keywords": [
"knowledgbase",
"articles",
"kb"
],
"description": "Display the Knowledge Base Articles",
"supports": {
"html": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"limit": {
"type": "string",
"default": ""
},
"showExcerpt": {
"type": "boolean",
"default": false
},
"termID": {
"type": "string",
"default": ""
},
"title": {
"type": "string",
"default": ""
}
},
"example": {},
"textdomain": "knowledgebase",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css"
}
1 change: 1 addition & 0 deletions includes/blocks/build/kb-articles/index-rtl.css

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

1 change: 1 addition & 0 deletions includes/blocks/build/kb-articles/index.asset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<?php return array('dependencies' => array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-core-data', 'wp-data', 'wp-i18n', 'wp-server-side-render'), 'version' => 'af27dffe54569e88bed6');
1 change: 1 addition & 0 deletions includes/blocks/build/kb-articles/index.css

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

1 change: 1 addition & 0 deletions includes/blocks/build/kb-articles/index.js

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

78 changes: 71 additions & 7 deletions includes/blocks/class-blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

namespace WebberZone\Knowledge_Base\Blocks;

use WebberZone\Knowledge_Base\Frontend\Display;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
Expand Down Expand Up @@ -38,8 +40,9 @@ public function __construct() {
*/
public function register_blocks() {
$blocks = array(
'kb' => 'render_kb_block',
'alerts' => 'render_alerts_block',
'kb' => 'render_kb_block',
'alerts' => 'render_alerts_block',
'kb-articles' => 'render_articles_block',
);

foreach ( $blocks as $block_name => $render_callback ) {
Expand All @@ -52,6 +55,24 @@ public function register_blocks() {
}
}

/**
* Maps JavaScript attribute names to PHP attribute names.
*
* @since 2.3.0
*
* @param array $attributes The block attributes.
* @param array $mappings Array of mappings with PHP attributes as keys and JS attributes as values.
* @return array Modified attributes array with mapped values.
*/
private function map_attributes( $attributes, $mappings ) {
foreach ( $mappings as $php_attr => $js_attr ) {
if ( isset( $attributes[ $js_attr ] ) ) {
$attributes[ $php_attr ] = $attributes[ $js_attr ];
}
}
return $attributes;
}

/**
* Renders the `knowledgebase/knowledgebase` block on server.
*
Expand All @@ -71,11 +92,7 @@ public function render_kb_block( $attributes ) {
'extra_class' => 'className',
);

foreach ( $mappings as $php_attr => $js_attr ) {
if ( isset( $attributes[ $js_attr ] ) ) {
$attributes[ $php_attr ] = $attributes[ $js_attr ];
}
}
$attributes = $this->map_attributes( $attributes, $mappings );

$arguments = array_merge(
$attributes,
Expand Down Expand Up @@ -113,4 +130,51 @@ public function render_kb_block( $attributes ) {
public function render_alerts_block( $attributes, $content, $block ) {

Check warning on line 130 in includes/blocks/class-blocks.php

View workflow job for this annotation

GitHub Actions / PHPCS check

The method parameter $block is never used
return wp_kses_post( $content );
}

/**
* Renders the `knowledgebase/articles` block on server.
*
* @since 2.3.0
*
* @param array $attributes The block attributes.
*
* @return string Returns the post content with latest posts added.
*/
public function render_articles_block( $attributes ) {
$mappings = array(
'term_id' => 'termID',
'show_excerpt' => 'showExcerpt',
);

$attributes = $this->map_attributes( $attributes, $mappings );

$limit = (int) ( ! empty( $attributes['limit'] ) ? $attributes['limit'] : wzkb_get_option( 'limit', 5 ) );

$show_excerpt = isset( $attributes['show_excerpt'] ) ? (bool) $attributes['show_excerpt'] : false;

if ( empty( $attributes['term_id'] ) ) {
return '';
}

$term = get_term( (int) $attributes['term_id'], 'wzkb_category' );

if ( empty( $term ) || is_wp_error( $term ) ) {
return '';
}

$list_of_posts = Display::get_posts_by_term(
$term,
0,
array(
'show_excerpt' => $show_excerpt,
'limit' => $limit,
)
);

if ( empty( $list_of_posts ) ) {
return __( 'No articles found.', 'knowledgebase' );
}

return $list_of_posts;
}
}
40 changes: 40 additions & 0 deletions includes/blocks/src/kb-articles/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "knowledgebase/articles",
"version": "2.3.0",
"title": "Knowledge Base Articles",
"category": "design",
"icon": "book",
"keywords": ["knowledgbase", "articles", "kb"],
"description": "Display the Knowledge Base Articles",
"supports": {
"html": false
},
"attributes": {
"className": {
"type": "string",
"default": ""
},
"limit": {
"type": "string",
"default": ""
},
"showExcerpt": {
"type": "boolean",
"default": false
},
"termID": {
"type": "string",
"default": ""
},
"title": {
"type": "string",
"default": ""
}
},
"example": {},
"textdomain": "knowledgebase",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css"
}
145 changes: 145 additions & 0 deletions includes/blocks/src/kb-articles/edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { __ } from '@wordpress/i18n';
import ServerSideRender from '@wordpress/server-side-render';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';

import {
Disabled,
ComboboxControl,
ToggleControl,
PanelBody,
PanelRow,
Spinner,
TextControl,
Notice,
} from '@wordpress/components';

import './editor.scss';

export default function Edit({ attributes, setAttributes }) {
const { termID, limit, showExcerpt } = attributes;

const blockProps = useBlockProps();

const { terms, hasResolved, error } = useSelect((select) => {
const query = { per_page: -1 };
const selectorArgs = ['taxonomy', 'wzkb_category', query];

try {
return {
terms: select(coreStore).getEntityRecords(...selectorArgs),
hasResolved: select(coreStore).hasFinishedResolution(
'getEntityRecords',
selectorArgs
),
error: null,
};
} catch (fetchError) {
return {
terms: [],
hasResolved: true,
error: fetchError,
};
}
}, []);

const termOptions =
terms?.map((term) => ({
label: `${term.name} (#${term.id})`,
value: term.id.toString(),
})) || [];

const handleLimitChange = (newLimit) => {
const parsedLimit = parseInt(newLimit, 10);
setAttributes({
limit: isNaN(parsedLimit) || parsedLimit <= 0 ? 5 : parsedLimit,
});
};

return (
<>
<InspectorControls>
{error && (
<Notice status="error" isDismissible={false}>
{__(
'Error loading categories. Please try again.',
'knowledgebase'
)}
</Notice>
)}

<PanelBody
title={__(
'Knowledge Base Articles Settings',
'knowledgebase'
)}
initialOpen={true}
>
<PanelRow>
{!hasResolved ? (
<Spinner />
) : (
<ComboboxControl
label={__(
'Select Knowledge Base Section',
'knowledgebase'
)}
value={termID}
onChange={(value) =>
setAttributes({ termID: value })
}
options={termOptions}
help={__(
'Search and select a knowledge base section',
'knowledgebase'
)}
/>
)}
</PanelRow>
<PanelRow>
<TextControl
label={__('Number of posts', 'knowledgebase')}
value={limit}
type="number"
min="1"
onChange={handleLimitChange}
help={__(
'Enter the number of posts to display (default: 5)',
'knowledgebase'
)}
/>
</PanelRow>
<PanelRow>
<ToggleControl
label={__('Show excerpt', 'knowledgebase')}
help={
showExcerpt
? __(
'Excerpt is displayed',
'knowledgebase'
)
: __('No excerpt shown', 'knowledgebase')
}
checked={showExcerpt}
onChange={() =>
setAttributes({
showExcerpt: !showExcerpt,
})
}
/>
</PanelRow>
</PanelBody>
</InspectorControls>

<div {...blockProps}>
<Disabled>
<ServerSideRender
block="knowledgebase/articles"
attributes={attributes}
/>
</Disabled>
</div>
</>
);
}
Loading

0 comments on commit b035623

Please sign in to comment.