add Gutenberg events list block

This commit is contained in:
Daniel Waxweiler 2022-06-03 23:48:19 +02:00
parent c042851184
commit 3360a9e7a7
20 changed files with 1558 additions and 797 deletions

View File

@ -3,6 +3,9 @@
"browser": true,
"es2020": true
},
"globals": {
"MOBILIZON_CONNECTOR": "readonly"
},
"parser": "@babel/eslint-parser",
"extends": [
"eslint:recommended",

View File

@ -24,5 +24,7 @@ jobs:
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --omit=dev --ignore-scripts
- name: Upgrade NPM
run: npm install -g npm
- run: npm ci --ignore-scripts
- run: npm run build-prod

1890
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -31,23 +31,23 @@
},
"devDependencies": {
"@babel/core": "7.17.12",
"@babel/eslint-parser": "^7.16.5",
"@babel/eslint-parser": "7.16.5",
"@babel/preset-env": "7.17.12",
"@babel/preset-react": "^7.16.5",
"@babel/preset-react": "7.16.5",
"@wordpress/eslint-plugin": "12.4.0",
"ava": "4.2.0",
"babel-loader": "8.2.5",
"browser-env": "3.3.0",
"c8": "7.11.3",
"copy-webpack-plugin": "11.0.0",
"eslint": "8.15.0",
"eslint-plugin-ava": "13.2.0",
"eslint-plugin-jsx": "^0.1.0",
"eslint-plugin-react": "^7.27.1",
"eslint-plugin-jsx": "0.1.0",
"eslint-plugin-react": "7.27.1",
"esm": "3.2.25",
"gulp": "4.0.2",
"gulp-replace": "1.1.3",
"husky": "8.0.1",
"jsdom": "19.0.0",
"lint-staged": "12.4.1",
"prettier": "2.6.2",
"rimraf": "3.0.2",

View File

@ -1,6 +1,9 @@
### [Unreleased]
#### Added
- Add Gutenberg events list block
- Show loading indicator during request
#### Changed
- Set list style type to none and left padding to zero for all occurences
#### Deprecated
#### Removed
#### Fixed

View File

@ -12,6 +12,7 @@
require_once __DIR__ . '/includes/constants.php';
require_once __DIR__ . '/includes/settings.php';
require_once __DIR__ . '/includes/events-list-block.php';
require_once __DIR__ . '/includes/events-list-shortcut.php';
require_once __DIR__ . '/includes/events-list-widget.php';
@ -24,7 +25,7 @@ final class Mobilizon_Connector {
private function __construct() {
add_action('init', [$this, 'register_blocks']);
add_action('init', [$this, 'register_settings']);
add_action('init', [$this, 'register_settings'], 1); // required for register_blocks
add_action('init', [$this, 'register_shortcut']);
add_action('widgets_init', [$this, 'register_widget']);
add_action('wp_enqueue_scripts', [$this, 'register_scripts']);
@ -44,16 +45,19 @@ final class Mobilizon_Connector {
MobilizonConnector\Settings::setDefaultOptions();
}
private function load_settings_globally_before_script($scriptName) {
$settings = array(
'isShortOffsetNameShown' => MobilizonConnector\Settings::isShortOffsetNameShown(),
'locale' => str_replace('_', '-', get_locale()),
'timeZone' => wp_timezone_string(),
'url' => MobilizonConnector\Settings::getUrl()
);
wp_add_inline_script($scriptName, 'var MOBILIZON_CONNECTOR = ' . json_encode($settings), 'before');
}
public function register_blocks() {
wp_register_script(MobilizonConnector\NAME . '-block-starter', plugins_url('front/block-events-loader.js', __FILE__ ), [
'wp-blocks',
'wp-components',
'wp-editor',
'wp-i18n'
]);
register_block_type(MobilizonConnector\NAME . '/events-list', [
'editor_script' => MobilizonConnector\NAME . '-block-starter'
]);
$scriptName = MobilizonConnector\EventsListBlock::initAndReturnScriptName();
$this->load_settings_globally_before_script($scriptName);
}
public function register_settings() {
@ -61,7 +65,9 @@ final class Mobilizon_Connector {
}
public function register_scripts() {
wp_enqueue_script(MobilizonConnector\NAME . '-js', plugins_url('front/events-loader.js', __FILE__ ));
$name = MobilizonConnector\NAME . '-js';
wp_enqueue_script($name, plugins_url('front/events-loader.js', __FILE__ ));
$this->load_settings_globally_before_script($name);
}
public function register_shortcut() {

View File

@ -1 +1 @@
import './blocks/events-list'
import './blocks/events-list/index.js'

View File

@ -1,15 +1,44 @@
const { InspectorControls } = wp.blockEditor
/* eslint-disable @wordpress/i18n-ellipsis */
import { loadEventList } from '../../events-loader.js'
const { InspectorControls, useBlockProps } = wp.blockEditor
const { PanelBody } = wp.components
const { useEffect } = wp.element
const { __ } = wp.i18n
const NAME = '<wordpress-name>'
let timer
export default ({ attributes, setAttributes }) => {
const blockProps = useBlockProps({
className: NAME + '_events-list',
'data-maximum': attributes.eventsCount,
'data-group-name': attributes.groupName,
})
function reloadEventList() {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
const container = document.getElementById(blockProps.id)
if (container) {
loadEventList(container)
}
}, 500)
}
useEffect(() => {
reloadEventList()
}, [])
function updateEventsCount(event) {
let newValue = Number(event.target.value)
if (newValue < 1) newValue = 1
setAttributes({ eventsCount: newValue })
reloadEventList()
}
function updateGroupName(event) {
setAttributes({ groupName: event.target.value })
reloadEventList()
}
return [
<InspectorControls>
@ -42,12 +71,17 @@ export default ({ attributes, setAttributes }) => {
/>
</PanelBody>
</InspectorControls>,
<ul>
{[...Array(attributes.eventsCount)].map((_, i) => (
<li className="busterCards" key={i}>
{__('Event', '<wordpress-name>')} {i}
</li>
))}
</ul>,
<div {...blockProps}>
<div className="general-error" style={{ display: 'none' }}>
{__('The events could not be loaded!', '<wordpress-name>')}
</div>
<div className="group-not-found" style={{ display: 'none' }}>
{__('The group could not be found!', '<wordpress-name>')}
</div>
<div className="loading-indicator" style={{ display: 'none' }}>
{__('Loading...', '<wordpress-name>')}
</div>
<ul style={{ 'list-style-type': 'none', 'padding-left': 0 }}></ul>
</div>,
]
}

View File

@ -1,31 +1,7 @@
import edit from './edit'
import save from './save'
import edit from './edit.js'
const { registerBlockType } = wp.blocks
const { __ } = wp.i18n
const NAME = '<wordpress-name>'
registerBlockType(NAME + '/events-list', {
title: __('Events List', '<wordpress-name>'),
description: __(
'A list of the upcoming events of the connected Mobilizon instance.',
'<wordpress-name>'
),
icon: 'list-view',
category: 'widgets',
attributes: {
eventsCount: {
type: 'number',
default: 3,
},
groupName: {
type: 'string',
},
},
supports: {
html: false,
},
edit,
save,
})
registerBlockType(NAME + '/events-list', { edit })

View File

@ -1,25 +0,0 @@
const { __ } = wp.i18n
const NAME = '<wordpress-name>'
const URL = 'https://mobilizon.fr' // TODO
const LOCALE = 'en-GB' // TODO
const TIMEZONE = 'Europe/Rome' // TODO
const isShortOffsetNameShown = true // eslint-disable-line no-unused-vars
export default ({ attributes }) => {
return (
<ul
className={NAME + '_events-list'}
data-url={URL}
data-locale={LOCALE}
data-maximum={attributes.eventsCount}
data-group-name={attributes.groupName}
data-time-zone={TIMEZONE}
>
<li style="display: none;">
{__('The events could not be loaded!', '<wordpress-name>')}
</li>
</ul>
)
}

View File

@ -1,29 +1,45 @@
import test from 'ava'
import { JSDOM } from 'jsdom'
import browserEnv from 'browser-env'
import { displayEvents, displayErrorMessage } from './events-displayer.js'
let document
import {
displayEvents,
displayErrorMessage,
hideErrorMessages,
showLoadingIndicator,
} from './events-displayer.js'
test.before(() => {
document = new JSDOM().window.document
browserEnv()
window.MOBILIZON_CONNECTOR = {
locale: 'en-GB',
timeZone: 'utc',
}
})
test.beforeEach((t) => {
t.context.list = document.createElement('ul')
t.context.list.setAttribute('data-locale', 'en-GB')
t.context.list.setAttribute('data-maximum', '2')
t.context.list.setAttribute('data-time-zone', 'utc')
const listElement = document.createElement('li')
listElement.setAttribute('style', 'display: none;')
t.context.list.appendChild(listElement)
const listElement2 = document.createElement('li')
listElement2.setAttribute('style', 'display: none;')
t.context.list.appendChild(listElement2)
t.context.container = document.createElement('div')
t.context.container.setAttribute('data-maximum', '2')
const errorMessageGeneral = document.createElement('div')
errorMessageGeneral.setAttribute('class', 'general-error')
errorMessageGeneral.setAttribute('style', 'display: none;')
t.context.container.appendChild(errorMessageGeneral)
const errorMessageGroupNotFound = document.createElement('div')
errorMessageGroupNotFound.setAttribute('class', 'group-not-found')
errorMessageGroupNotFound.setAttribute('style', 'display: none;')
t.context.container.appendChild(errorMessageGroupNotFound)
const loadingIndicator = document.createElement('div')
loadingIndicator.setAttribute('class', 'loading-indicator')
loadingIndicator.setAttribute('style', 'display: none;')
t.context.container.appendChild(loadingIndicator)
const list = document.createElement('ul')
t.context.container.appendChild(list)
})
test('#displayEvents one event', (t) => {
const list = t.context.list
const data = {
events: {
elements: [
@ -40,32 +56,35 @@ test('#displayEvents one event', (t) => {
],
},
}
displayEvents({ data, document, list })
t.is(list.children.length, 3)
t.is(list.children[2].childNodes[0].tagName, 'A')
t.is(list.children[2].childNodes[0].getAttribute('href'), 'b')
t.is(list.children[2].childNodes[0].childNodes[0].nodeValue, 'a')
t.is(list.children[2].childNodes[1].tagName, 'BR')
t.is(list.children[2].childNodes[2].nodeValue, '15/04/2021 10:30 - 15:30')
t.is(list.children[2].childNodes[3].tagName, 'BR')
t.is(list.children[2].childNodes[4].nodeValue, 'c, d')
const container = t.context.container
displayEvents({ data, document, container })
const list = container.querySelector('ul')
t.is(list.children[0].childNodes[0].tagName, 'A')
t.is(list.children[0].childNodes[0].getAttribute('href'), 'b')
t.is(list.children[0].childNodes[0].childNodes[0].nodeValue, 'a')
t.is(list.children[0].childNodes[1].tagName, 'BR')
t.is(list.children[0].childNodes[2].nodeValue, '15/04/2021 10:30 - 15:30')
t.is(list.children[0].childNodes[3].tagName, 'BR')
t.is(list.children[0].childNodes[4].nodeValue, 'c, d')
})
test('#displayErrorMessage no children added', (t) => {
const list = t.context.list
displayErrorMessage({ data: '', list })
t.is(list.children.length, 2)
test('#displayErrorMessage no list entries shown', (t) => {
const container = t.context.container
displayErrorMessage({ data: '', container })
const list = container.querySelector('ul')
t.is(list.children.length, 0)
})
test('#displayErrorMessage error message display', (t) => {
const list = t.context.list
displayErrorMessage({ data: '', list })
t.is(list.children[0].style.display, 'block')
t.is(list.children[1].style.display, 'none')
test('#displayErrorMessage general error message display', (t) => {
const container = t.context.container
displayErrorMessage({ data: '', container })
t.is(container.querySelector('.general-error').style.display, 'block')
t.is(container.querySelector('.group-not-found').style.display, 'none')
t.is(container.querySelector('.loading-indicator').style.display, 'none')
})
test('#displayErrorMessage group not found error message display', (t) => {
const list = t.context.list
const container = t.context.container
const data = {
response: {
errors: [
@ -75,7 +94,29 @@ test('#displayErrorMessage group not found error message display', (t) => {
],
},
}
displayErrorMessage({ data, list })
t.is(list.children[0].style.display, 'none')
t.is(list.children[1].style.display, 'block')
displayErrorMessage({ data, container })
t.is(container.querySelector('.general-error').style.display, 'none')
t.is(container.querySelector('.group-not-found').style.display, 'block')
t.is(container.querySelector('.loading-indicator').style.display, 'none')
})
test('#showLoadingIndicator remove events', (t) => {
const container = t.context.container
const loadingIndicator = container.querySelector('.loading-indicator')
t.is(loadingIndicator.style.display, 'none')
showLoadingIndicator(container)
t.is(loadingIndicator.style.display, 'block')
})
test('#hideErrorMessages remove events', (t) => {
const container = t.context.container
const generalErrorMessage = container.querySelector('.general-error')
const groupNotFoundErrorMessage = container.querySelector('.group-not-found')
generalErrorMessage.style.display = 'block'
groupNotFoundErrorMessage.style.display = 'block'
t.is(generalErrorMessage.style.display, 'block')
t.is(groupNotFoundErrorMessage.style.display, 'block')
hideErrorMessages(container)
t.is(generalErrorMessage.style.display, 'none')
t.is(groupNotFoundErrorMessage.style.display, 'none')
})

View File

@ -1,17 +1,25 @@
import Formatter from './formatter.js'
import { createAnchorElement } from './html-creator.js'
export function displayEvents({ data, document, list }) {
const locale = list.getAttribute('data-locale')
const maxEventsCount = list.getAttribute('data-maximum')
const timeZone = list.getAttribute('data-time-zone')
const isShortOffsetNameShown = list.hasAttribute(
'data-is-short-offset-name-shown'
)
export function clearEventsList(container) {
const list = container.querySelector('ul')
list.replaceChildren()
}
export function displayEvents({ data, document, container }) {
hideLoadingIndicator(container)
const isShortOffsetNameShown =
window.MOBILIZON_CONNECTOR.isShortOffsetNameShown
const locale = window.MOBILIZON_CONNECTOR.locale
const maxEventsCount = container.getAttribute('data-maximum')
const timeZone = window.MOBILIZON_CONNECTOR.timeZone
const events = data.events
? data.events.elements
: data.group.organizedEvents.elements
const eventsCount = Math.min(maxEventsCount, events.length)
const list = container.querySelector('ul')
for (let i = 0; i < eventsCount; i++) {
const li = document.createElement('li')
@ -53,8 +61,8 @@ export function displayEvents({ data, document, list }) {
}
}
export function displayErrorMessage({ data, list }) {
console.error(data)
export function displayErrorMessage({ data, container }) {
hideLoadingIndicator(container)
if (
Object.prototype.hasOwnProperty.call(data, 'response') &&
Object.prototype.hasOwnProperty.call(data.response, 'errors') &&
@ -62,8 +70,26 @@ export function displayErrorMessage({ data, list }) {
Object.prototype.hasOwnProperty.call(data.response.errors[0], 'code') &&
data.response.errors[0].code === 'group_not_found'
) {
list.children[1].style.display = 'block'
const message = container.querySelector('.group-not-found')
message.style.display = 'block'
} else {
list.children[0].style.display = 'block'
const message = container.querySelector('.general-error')
message.style.display = 'block'
console.error(data)
}
}
export function showLoadingIndicator(container) {
const indicator = container.querySelector('.loading-indicator')
indicator.style.display = 'block'
}
function hideLoadingIndicator(container) {
const indicator = container.querySelector('.loading-indicator')
indicator.style.display = 'none'
}
export function hideErrorMessages(container) {
container.querySelector('.group-not-found').style.display = 'none'
container.querySelector('.general-error').style.display = 'none'
}

View File

@ -1,22 +1,38 @@
import { displayEvents, displayErrorMessage } from './events-displayer.js'
import {
clearEventsList,
displayEvents,
displayErrorMessage,
hideErrorMessages,
showLoadingIndicator,
} from './events-displayer.js'
import * as GraphqlWrapper from './graphql-wrapper.js'
const NAME = '<wordpress-name>'
const URL_SUFFIX = '/api'
document.addEventListener('DOMContentLoaded', () => {
document.addEventListener('DOMContentLoaded', loadEventLists)
function loadEventLists() {
const eventLists = document.getElementsByClassName(NAME + '_events-list')
for (const list of eventLists) {
const url = list.getAttribute('data-url') + '/api'
const limit = parseInt(list.getAttribute('data-maximum'))
const groupName = list.getAttribute('data-group-name')
if (groupName) {
GraphqlWrapper.getUpcomingEventsByGroupName({ url, limit, groupName })
.then((data) => displayEvents({ data, document, list }))
.catch((data) => displayErrorMessage({ data, list }))
} else {
GraphqlWrapper.getUpcomingEvents({ url, limit })
.then((data) => displayEvents({ data, document, list }))
.catch((data) => displayErrorMessage({ data, list }))
}
loadEventList(list)
}
})
}
export function loadEventList(container) {
const url = MOBILIZON_CONNECTOR.url + URL_SUFFIX
const limit = parseInt(container.getAttribute('data-maximum'))
const groupName = container.getAttribute('data-group-name')
hideErrorMessages(container)
clearEventsList(container)
showLoadingIndicator(container)
if (groupName) {
GraphqlWrapper.getUpcomingEventsByGroupName({ url, limit, groupName })
.then((data) => displayEvents({ data, document, container }))
.catch((data) => displayErrorMessage({ data, container }))
} else {
GraphqlWrapper.getUpcomingEvents({ url, limit })
.then((data) => displayEvents({ data, document, container }))
.catch((data) => displayErrorMessage({ data, container }))
}
}

View File

@ -1,12 +1,10 @@
import test from 'ava'
import { JSDOM } from 'jsdom'
import browserEnv from 'browser-env'
import { createAnchorElement } from './html-creator.js'
let document
test.beforeEach(() => {
document = new JSDOM().window.document
browserEnv()
})
test('#createAnchorElement usual parameters', (t) => {

View File

@ -0,0 +1,54 @@
<?php
namespace MobilizonConnector;
// Exit if this file is called directly.
if (!defined('ABSPATH')) {
exit;
}
class EventsListBlock {
public static function initAndReturnScriptName(): string {
$scriptName = NAME . '-block-starter';
wp_register_script($scriptName, plugins_url(NAME . '/front/block-events-loader.js'), [
'wp-block-editor',
'wp-blocks',
'wp-components',
'wp-editor',
'wp-i18n'
]);
register_block_type(NAME . '/events-list', [
'api_version' => 2,
'title' => __('Events List', 'connector-mobilizon'),
'description' => __('A list of the upcoming events of the connected Mobilizon instance.', 'connector-mobilizon'),
'category' => 'widgets',
'icon' => 'list-view',
'supports' => [
'html' => false
],
'attributes' => [
'eventsCount' => [
'type' => 'number',
'default' => 3,
],
'groupName' => [
'type' => 'string',
],
],
'editor_script' => $scriptName,
'render_callback' => 'MobilizonConnector\EventsListBlock::render',
]);
return $scriptName;
}
public static function render($block_attributes, $content) {
$classNamePrefix = NAME;
$eventsCount = $block_attributes['eventsCount'];
$groupName = isset($block_attributes['groupName']) ? $block_attributes['groupName'] : '';
ob_start();
require dirname(__DIR__) . '/view/events-list.php';
$output = ob_get_clean();
return $output;
}
}

View File

@ -26,11 +26,7 @@ class EventsListShortcut {
$classNamePrefix = NAME;
$eventsCount = $atts_with_overriden_defaults['events-count'];
$locale = str_replace('_', '-', get_locale());
$groupName = $atts_with_overriden_defaults['group-name'];
$url = Settings::getUrl();
$timeZone = wp_timezone_string();
$isShortOffsetNameShown = Settings::isShortOffsetNameShown();
ob_start();
require dirname(__DIR__) . '/view/events-list.php';

View File

@ -27,11 +27,7 @@ class EventsListWidget extends \WP_Widget {
$classNamePrefix = NAME;
$eventsCount = $options['eventsCount'];
$locale = str_replace('_', '-', get_locale());
$groupName = isset($options['groupName']) ? $options['groupName'] : '';
$url = Settings::getUrl();
$timeZone = wp_timezone_string();
$isShortOffsetNameShown = Settings::isShortOffsetNameShown();
require dirname(__DIR__) . '/view/events-list.php';

View File

@ -15,11 +15,11 @@ License: <wordpress-license>
<wordpress-nice-name> allows you to display the upcoming events of [Mobilizon](https://joinmobilizon.org/), which is a federated event listing platform, on your WordPress website.
Features
- Display events as widget and as shortcut
- Display events as Gutenberg block, as widget and as shortcut
- Display events' title, date, and location if available
- Cache requests' responses for 2 minutes in the browser's `sessionStorage`
- Configure number of events to show per widget and per shortcut
- Optionally filter events by a specific group per widget and per shortcut
- Configure number of events to show per block, per widget and per shortcut
- Optionally filter events by a specific group per block, per widget and per shortcut
- Set the URL of the Mobilizon instance in the settings
- Toggle adding named offset in brackets after the time in the settings

View File

@ -4,13 +4,11 @@ if (!defined('ABSPATH')) {
exit;
}
?>
<ul class="<?php echo esc_attr($classNamePrefix); ?>_events-list"
data-url="<?php echo esc_attr($url); ?>"
data-locale="<?php echo esc_attr($locale); ?>"
<div class="<?php echo esc_attr($classNamePrefix); ?>_events-list"
data-maximum="<?php echo esc_attr($eventsCount); ?>"
data-group-name="<?php echo esc_attr($groupName); ?>"
data-time-zone="<?php echo esc_attr($timeZone); ?>"
<?php echo $isShortOffsetNameShown ? 'data-is-short-offset-name-shown' : ''; ?>>
<li style="display: none;"><?php esc_html_e('The events could not be loaded!', 'connector-mobilizon'); ?></li>
<li style="display: none;"><?php esc_html_e('The group could not be found!', 'connector-mobilizon'); ?></li>
</ul>
data-group-name="<?php echo esc_attr($groupName); ?>">
<div class="general-error" style="display: none;"><?php esc_html_e('The events could not be loaded!', 'connector-mobilizon'); ?></div>
<div class="group-not-found" style="display: none;"><?php esc_html_e('The group could not be found!', 'connector-mobilizon'); ?></div>
<div class="loading-indicator" style="display: none;"><?php esc_html_e('Loading...', 'connector-mobilizon'); ?></div>
<ul style="list-style-type: none; padding-left: 0;"></ul>
</div>

View File

@ -14,17 +14,6 @@ module.exports = {
filename: '[name].js',
path: path.resolve(__dirname, 'build/front'),
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
},
},
],
},
module: {
rules: [
{