Merge branch 'main' into block

This commit is contained in:
Daniel Waxweiler 2021-12-14 15:33:07 +01:00
commit 53d08e7174
31 changed files with 3557 additions and 5123 deletions

View File

@ -3,6 +3,7 @@
"browser": true, "browser": true,
"es2020": true "es2020": true
}, },
"parser": "@babel/eslint-parser",
"extends": [ "extends": [
"eslint:recommended", "eslint:recommended",
"plugin:ava/recommended", "plugin:ava/recommended",
@ -10,13 +11,15 @@
], ],
"parserOptions": { "parserOptions": {
"ecmaVersion": 11, "ecmaVersion": 11,
"sourceType": "module" "requireConfigFile": false,
"sourceType": "module",
"babelOptions": {
"presets": ["@babel/preset-react"]
}
}, },
"plugins": [ "plugins": [
"ava" "ava",
], "jsx"
"ignorePatterns": [
"gulpfile.js"
], ],
"rules": { "rules": {
"indent": [ "indent": [

View File

@ -9,14 +9,14 @@
# the `language` matrix defined below to confirm you have the correct set of # the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages. # supported CodeQL languages.
# #
name: "CodeQL" name: 'CodeQL'
on: on:
push: push:
branches: [ main ] branches: [main]
pull_request: pull_request:
# The branches below must be a subset of the branches above # The branches below must be a subset of the branches above
branches: [ main ] branches: [main]
schedule: schedule:
- cron: '39 19 * * 4' - cron: '39 19 * * 4'
@ -32,40 +32,40 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
language: [ 'javascript' ] language: ['javascript']
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more: # Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v2 uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v1 uses: github/codeql-action/init@v1
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file. # By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file. # Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main # queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild #- name: Autobuild
uses: github/codeql-action/autobuild@v1 # uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell. # Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl # 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project # and modify them (or add more) to build your code if your project
# uses a compiled language # uses a compiled language
#- run: | - run: |
# make bootstrap npm install
# make release npm run build-prod
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1 uses: github/codeql-action/analyze@v1

View File

@ -5,13 +5,12 @@ name: Node.js CI
on: on:
push: push:
branches: [ main ] branches: [main]
pull_request: pull_request:
branches: [ main ] branches: [main]
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
@ -20,10 +19,10 @@ jobs:
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2 uses: actions/setup-node@v2
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- run: npm ci - run: npm ci --omit=dev --ignore-scripts
- run: npm run build-prod - run: npm run build-prod

5
.husky/pre-commit Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm test
npx lint-staged

8
.prettierignore Normal file
View File

@ -0,0 +1,8 @@
.idea
build
coverage
node_modules
vendor
.eslintrc.json
composer.lock
LICENSE.md

4
.prettierrc.json Normal file
View File

@ -0,0 +1,4 @@
{
"semi": false,
"singleQuote": true
}

View File

@ -7,33 +7,37 @@ More details can be found in the [WordPress Plugin Directory](https://wordpress.
## Development ## Development
### Setup ### Setup
1. Make sure `npm` and `composer` are installed. 1. Make sure `npm` and `composer` are installed.
2. Run: `npm install` 2. Run: `npm install`
3. Run: `composer install` 3. Run: `composer install`
### Development build ### Development build
1. Build: `npm run build-dev` 1. Build: `npm run build-dev`
2. Make sure to keep `changelog.txt` up-to-date. 2. Make sure to keep `changelog.txt` up-to-date.
### Release procedure ### Release procedure
1. Make sure `changelog.txt` is up-to-date. Use a new version number and copy over the new section into `readme.txt`. 1. Make sure `changelog.txt` is up-to-date. Use a new version number and copy over the new section into `readme.txt`.
2. Update `package.json` with the same version number. 2. Update `package.json` with the same version number.
3. Update the `package-lock.json`: `npm i --package-lock-only` 3. Update the `package-lock.json`: `npm i --package-lock-only`
4. Build: `npm run build-prod` 4. Build: `npm run build-prod`
5. Determine minimum PHP version for code and update package.json if needed: `./vendor/bin/phpcompatinfo analyser:run ./source` 5. Make sure screenshots are up-to-date.
6. Make sure screenshots are up-to-date. 6. Copy the built plugin into `/trunk` of SVN.
7. Copy the built plugin into `/trunk` of SVN. 7. Create a new tag of the new version: `svn cp trunk tags/<version>`
8. Create a new tag of the new version: `svn cp trunk tags/<version>` 8. Check the version number occurrences in both folders.
9. Check the version number occurrences in both folders. 9. Commit everything together to the release SVN: `svn ci -m "release version <version>"`
10. Commit everything together to the release SVN: `svn ci -m "release version <version>"` 10. Commit the new version in git with the same message.
11. Commit the new version in git with the same message. 11. Tag the new version: `git tag v<version>`
12. Tag the new version: `git tag v<version>` 12. Push the new tag to the repository: `git push --tags`
13. Push the new tag to the repository: `git push --tags`
### Other commands ### Other commands
- Run ESLint: `npm run eslint` - Run ESLint: `npm run eslint`
- Run JavaScript code coverage with tests: `npm run coverage` - Run JavaScript code coverage with tests: `npm run coverage`
- Run tests: `npm test` - Run tests: `npm test`
- Delete build folder: `gulp clean` - Delete build folder: `npm run clean`
- Update PHP dependencies: `composer update` - Update PHP dependencies: `composer update`
- Check for direct PHP dependency updates: `composer outdated --direct` - Check for direct PHP dependency updates: `composer outdated --direct`
- Format code with prettier: `npm run format`

3
babel.config.json Normal file
View File

@ -0,0 +1,3 @@
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}

View File

@ -1,5 +1 @@
{ {}
"require": {
"bartlett/php-compatinfo": "^5.4"
}
}

2912
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,101 +1,50 @@
const { dest, series, src } = require('gulp'); /* eslint-disable no-undef */
const { dest, src } = require('gulp')
const del = require('del'); const replace = require('gulp-replace')
const replace = require('gulp-replace');
const webpack = require('webpack-stream');
const PACKAGE = require('./package.json'); const PACKAGE = require('./package.json')
const FOLDER_SOURCE = './source' const FOLDER_BUILD = './build'
const FOLDER_BUILD = './build';
let mode = 'development';
function clean(cb) {
del(FOLDER_BUILD);
cb();
}
const eventsLoaderOutputPath = PACKAGE.name + '/front/events-loader';
const blockEventsLoaderOutputPath = PACKAGE.name + '/front/block-events-loader';
const eventsLoaderInputPath = FOLDER_SOURCE + '/' + PACKAGE.name + '/front/events-loader.js';
const blockEventsLoaderInputPath = FOLDER_SOURCE + '/' + PACKAGE.name + '/front/block-events-loader.js';
function bundleFrontend() {
return src([
FOLDER_SOURCE + '/' + PACKAGE.name + '/front/events-loader.js',
FOLDER_SOURCE + '/' + PACKAGE.name + '/front/block-events-loader.js',
])
.pipe(webpack({
mode,
entry: {
[eventsLoaderOutputPath]: eventsLoaderInputPath,
[blockEventsLoaderOutputPath]: blockEventsLoaderInputPath,
},
output: {
filename: '[name].js',
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
}
]
}
}))
.pipe(dest(FOLDER_BUILD));
}
function copyBackend() {
return src([
FOLDER_SOURCE + '/**/*.php',
FOLDER_SOURCE + '/**/*.txt'
])
.pipe(dest(FOLDER_BUILD));
}
function injectMetadata() { function injectMetadata() {
return src([ return src(
FOLDER_BUILD + '/' + eventsLoaderOutputPath + '.js', [
FOLDER_BUILD + '/' + blockEventsLoaderOutputPath + '.js', FOLDER_BUILD + '/' + PACKAGE.name + '/front/events-loader.js',
FOLDER_BUILD + '/' + PACKAGE.name + '/' + PACKAGE.name + '.php', FOLDER_BUILD + '/' + PACKAGE.name + '/front/block-events-loader.js',
FOLDER_BUILD + '/' + PACKAGE.name + '/includes/constants.php', FOLDER_BUILD + '/' + PACKAGE.name + '/' + PACKAGE.name + '.php',
FOLDER_BUILD + '/' + PACKAGE.name + '/readme.txt' FOLDER_BUILD + '/' + PACKAGE.name + '/includes/constants.php',
], { base: './' }) FOLDER_BUILD + '/' + PACKAGE.name + '/readme.txt',
],
{ base: './' }
)
.pipe(replace('<wordpress-author-name>', PACKAGE.author.name)) .pipe(replace('<wordpress-author-name>', PACKAGE.author.name))
.pipe(replace('<wordpress-author-url>', PACKAGE.author.url)) .pipe(replace('<wordpress-author-url>', PACKAGE.author.url))
.pipe(replace('<wordpress-description>', PACKAGE.description)) .pipe(replace('<wordpress-description>', PACKAGE.description))
.pipe(replace('<wordpress-donation-link>', PACKAGE.funding.url)) .pipe(replace('<wordpress-donation-link>', PACKAGE.funding.url))
.pipe(replace('<wordpress-license>', PACKAGE.license)) .pipe(replace('<wordpress-license>', PACKAGE.license))
.pipe(replace('<wordpress-minimum-version>', PACKAGE.additionalDetails.wordpressMinimumVersion)) .pipe(
replace(
'<wordpress-minimum-version>',
PACKAGE.additionalDetails.wordpressMinimumVersion
)
)
.pipe(replace('<wordpress-name>', PACKAGE.name)) .pipe(replace('<wordpress-name>', PACKAGE.name))
.pipe(replace('<wordpress-nice-name>', PACKAGE.additionalDetails.niceName)) .pipe(replace('<wordpress-nice-name>', PACKAGE.additionalDetails.niceName))
.pipe(replace('<wordpress-php-minimum-version>', PACKAGE.additionalDetails.phpMinimumVersion)) .pipe(
.pipe(replace('<wordpress-tested-up-to-version>', PACKAGE.additionalDetails.wordpressTestedUpToVersion)) replace(
'<wordpress-php-minimum-version>',
PACKAGE.additionalDetails.phpMinimumVersion
)
)
.pipe(
replace(
'<wordpress-tested-up-to-version>',
PACKAGE.additionalDetails.wordpressTestedUpToVersion
)
)
.pipe(replace('<wordpress-version>', PACKAGE.version)) .pipe(replace('<wordpress-version>', PACKAGE.version))
.pipe(dest('.')); .pipe(dest('.'))
} }
exports.front = bundleFrontend; exports.inject = injectMetadata
exports.copy = copyBackend;
exports.inject = injectMetadata;
const build = series(clean, bundleFrontend, copyBackend, injectMetadata);
const buildDev = series((cb) => { mode = 'development'; cb(); }, build);
const buildProd = series((cb) => { mode = 'production'; cb(); }, build);
exports.clean = clean;
exports.dev = buildDev;
exports.default = buildDev;
exports.prod = buildProd;

5029
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -4,10 +4,13 @@
"description": "Display Mobilizon events in WordPress.", "description": "Display Mobilizon events in WordPress.",
"private": true, "private": true,
"scripts": { "scripts": {
"build-dev": "gulp dev", "build-dev": "webpack --mode=development && gulp inject",
"build-prod": "ava && gulp prod", "build-prod": "ava && webpack --mode=production && gulp inject",
"clean": "rimraf -- build",
"coverage": "c8 --all --reporter=html --reporter=text --include=source/**/*.js ava", "coverage": "c8 --all --reporter=html --reporter=text --include=source/**/*.js ava",
"eslint": "npx eslint source/**/*.js", "eslint": "npx eslint source/**/*.js",
"format": "npx prettier --write .",
"prepare": "husky install",
"test": "ava" "test": "ava"
}, },
"author": { "author": {
@ -20,28 +23,35 @@
}, },
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"graphql": "^15.6.1", "graphql": "^16.1.0",
"graphql-request": "^3.6.1", "graphql-request": "^3.7.0",
"luxon": "^2.0.2", "luxon": "^2.1.1",
"object-hash": "^2.2.0" "object-hash": "^2.2.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.16.5",
"@babel/eslint-parser": "^7.16.5",
"@babel/preset-env": "^7.15.8", "@babel/preset-env": "^7.15.8",
"@babel/preset-react": "^7.14.5", "@babel/preset-react": "^7.16.5",
"@wordpress/eslint-plugin": "^9.2.0", "@wordpress/eslint-plugin": "^9.2.0",
"ava": "^3.15.0", "ava": "^3.15.0",
"babel-loader": "^8.2.3", "babel-loader": "^8.2.3",
"c8": "^7.10.0", "c8": "^7.10.0",
"del": "^6.0.0", "copy-webpack-plugin": "^10.0.0",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"eslint-plugin-ava": "^13.1.0", "eslint-plugin-ava": "^13.1.0",
"eslint-plugin-jsx": "^0.1.0",
"eslint-plugin-react": "^7.27.1",
"esm": "^3.2.25", "esm": "^3.2.25",
"gulp": "^4.0.2", "gulp": "^4.0.2",
"gulp-replace": "^1.1.3", "gulp-replace": "^1.1.3",
"jsdom": "^18.0.0", "husky": "^7.0.4",
"webpack": "^5.60.0", "jsdom": "^19.0.0",
"webpack-cli": "^4.9.1", "lint-staged": "^12.1.2",
"webpack-stream": "^7.0.0" "prettier": "2.5.1",
"rimraf": "^3.0.2",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}, },
"ava": { "ava": {
"files": [ "files": [
@ -53,8 +63,12 @@
}, },
"additionalDetails": { "additionalDetails": {
"niceName": "Connector for Mobilizon", "niceName": "Connector for Mobilizon",
"phpMinimumVersion": 7.3, "phpMinimumVersion": 7.4,
"wordpressMinimumVersion": 5.6, "wordpressMinimumVersion": 5.6,
"wordpressTestedUpToVersion": 5.8 "wordpressTestedUpToVersion": 5.8
},
"lint-staged": {
"source/**/*.js": "eslint",
"**/*": "prettier --write --ignore-unknown"
} }
} }

View File

@ -1,7 +1,11 @@
### [Unreleased] ### [Unreleased]
#### Added #### Added
- Add specific error message for the case the group is not found
- Add code formatter prettier
#### Changed #### Changed
- Set minimum PHP version to oldest officially supported 7.4
- Update dependencies - Update dependencies
- Simplify build process
#### Deprecated #### Deprecated
#### Removed #### Removed
#### Fixed #### Fixed

View File

@ -20,36 +20,61 @@ if (!defined('ABSPATH')) {
exit; exit;
} }
function mobilizon_connector_activate() { final class Mobilizon_Connector {
MobilizonConnector\Settings::setDefaultOptions();
}
register_activation_hook(__FILE__, 'mobilizon_connector_activate');
function mobilizon_connector_initialize() { private function __construct() {
MobilizonConnector\Settings::init(); add_action('init', [$this, 'register_blocks']);
MobilizonConnector\EventsListShortcut::init(); add_action('init', [$this, 'register_settings']);
} add_action('init', [$this, 'register_shortcut']);
add_action('init', 'mobilizon_connector_initialize'); add_action('widgets_init', [$this, 'register_widget']);
add_action('wp_enqueue_scripts', [$this, 'register_scripts']);
register_activation_hook(__FILE__, [$this, 'enable_activation']);
}
function mobilizon_connector_load_scripts() { public static function init() {
wp_enqueue_script(MobilizonConnector\NAME . '-js', plugins_url('front/events-loader.js', __FILE__ )); // Create singleton instance.
} static $instance = false;
add_action('wp_enqueue_scripts', 'mobilizon_connector_load_scripts'); if(!$instance) {
$instance = new self();
}
return $instance;
}
function mobilizon_connector_register_events_list_widget() { public function enable_activation() {
register_widget('MobilizonConnector\EventsListWidget'); MobilizonConnector\Settings::setDefaultOptions();
} }
add_action('widgets_init', 'mobilizon_connector_register_events_list_widget');
function mobilizon_connector_initialize_blocks() { public function register_blocks() {
wp_register_script(MobilizonConnector\NAME . '-block-starter', plugins_url('front/block-events-loader.js', __FILE__ ), [ wp_register_script(MobilizonConnector\NAME . '-block-starter', plugins_url('front/block-events-loader.js', __FILE__ ), [
'wp-blocks', 'wp-blocks',
'wp-components', 'wp-components',
'wp-editor', 'wp-editor',
'wp-i18n' 'wp-i18n'
]);
register_block_type(MobilizonConnector\NAME . '/events-list', [
'editor_script' => MobilizonConnector\NAME . '-block-starter'
]); ]);
register_block_type(MobilizonConnector\NAME . '/events-list', [ }
'editor_script' => MobilizonConnector\NAME . '-block-starter'
]); public function register_settings() {
MobilizonConnector\Settings::init();
}
public function register_scripts() {
wp_enqueue_script(MobilizonConnector\NAME . '-js', plugins_url('front/events-loader.js', __FILE__ ));
}
public function register_shortcut() {
MobilizonConnector\EventsListShortcut::init();
}
public function register_widget() {
register_widget('MobilizonConnector\EventsListWidget');
}
} }
add_action('init', 'mobilizon_connector_initialize_blocks');
function mobilizon_connector_run_plugin() {
return Mobilizon_Connector::init();
}
mobilizon_connector_run_plugin();

View File

@ -11,17 +11,43 @@ export default ({ attributes, setAttributes }) => {
function updateGroupName(event) { function updateGroupName(event) {
setAttributes({ groupName: event.target.value }) setAttributes({ groupName: event.target.value })
} }
return ([ return [
<InspectorControls> <InspectorControls>
<PanelBody title={ __('Events List Settings', '<wordpress-name>') }> <PanelBody title={__('Events List Settings', '<wordpress-name>')}>
<label className="components-base-control__label">{ __('Number of events to show', '<wordpress-name>') }</label> <label
<input className="components-text-control__input" type="number" value={ attributes.eventsCount } onChange={ updateEventsCount } /> className="components-base-control__label"
<label className="components-base-control__label">{ __('Group name (optional)', '<wordpress-name>') }</label> htmlFor="<wordpress-name>_events-count"
<input className="components-text-control__input" type="text" value={ attributes.groupName } onChange={ updateGroupName } /> >
{__('Number of events to show', '<wordpress-name>')}
</label>
<input
className="components-text-control__input"
type="number"
value={attributes.eventsCount}
onChange={updateEventsCount}
id="<wordpress-name>_events-count"
/>
<label
className="components-base-control__label"
htmlFor="<wordpress-name>_group-name"
>
{__('Group name (optional)', '<wordpress-name>')}
</label>
<input
className="components-text-control__input"
type="text"
value={attributes.groupName}
onChange={updateGroupName}
id="<wordpress-name>_group-name"
/>
</PanelBody> </PanelBody>
</InspectorControls>, </InspectorControls>,
<ul> <ul>
{ [...Array(attributes.eventsCount)].map((_, i) => <li className="busterCards" key={ i }>{ __('Event', '<wordpress-name>') } { i }</li>) } {[...Array(attributes.eventsCount)].map((_, i) => (
</ul> <li className="busterCards" key={i}>
]) {__('Event', '<wordpress-name>')} {i}
</li>
))}
</ul>,
]
} }

View File

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

View File

@ -1,67 +1,76 @@
import test from 'ava' import test from 'ava'
import DateTimeWrapper from './date-time-wrapper' import DateTimeWrapper from './date-time-wrapper'
test('#getShortDate usual date', t => { test('#getShortDate usual date', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
t.is(d.getShortDate(), '24/12/2020') t.is(d.getShortDate(), '24/12/2020')
}) })
test('#getShortDate usual date with timezone string', t => { test('#getShortDate usual date with timezone string', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z', timeZone: 'Europe/Rome' }) const d = new DateTimeWrapper({
text: '2020-12-24T16:45:00Z',
timeZone: 'Europe/Rome',
})
t.is(d.getShortDate(), '24/12/2020') t.is(d.getShortDate(), '24/12/2020')
}) })
test('#getShortDate usual date with fixed offset', t => { test('#getShortDate usual date with fixed offset', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z', timeZone: 'UTC+02:00' }) const d = new DateTimeWrapper({
text: '2020-12-24T16:45:00Z',
timeZone: 'UTC+02:00',
})
t.is(d.getShortDate(), '24/12/2020') t.is(d.getShortDate(), '24/12/2020')
}) })
test('#getShortDate usual date with fixed offset without UTC prefix', t => { test('#getShortDate usual date with fixed offset without UTC prefix', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z', timeZone: '+02:00' }) const d = new DateTimeWrapper({
text: '2020-12-24T16:45:00Z',
timeZone: '+02:00',
})
t.is(d.getShortDate(), '24/12/2020') t.is(d.getShortDate(), '24/12/2020')
}) })
test('#getShortDate usual date with empty time zone', t => { test('#getShortDate usual date with empty time zone', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z', timeZone: '' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z', timeZone: '' })
t.is(d.getShortDate(), '24/12/2020') t.is(d.getShortDate(), '24/12/2020')
}) })
test('#get24Time usual time', t => { test('#get24Time usual time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
t.is(d.get24Time(), '16:45') t.is(d.get24Time(), '16:45')
}) })
test('#equalsDate same date, different time', t => { test('#equalsDate same date, different time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
const e = new DateTimeWrapper({ text: '2020-12-24T17:46:01Z' }) const e = new DateTimeWrapper({ text: '2020-12-24T17:46:01Z' })
t.true(d.equalsDate(e)) t.true(d.equalsDate(e))
}) })
test('#equalsDate different date, different time', t => { test('#equalsDate different date, different time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
const e = new DateTimeWrapper({ text: '2021-11-25T17:46:01Z' }) const e = new DateTimeWrapper({ text: '2021-11-25T17:46:01Z' })
t.false(d.equalsDate(e)) t.false(d.equalsDate(e))
}) })
test('#equalsDate different day, different time', t => { test('#equalsDate different day, different time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
const e = new DateTimeWrapper({ text: '2020-12-25T17:46:01Z' }) const e = new DateTimeWrapper({ text: '2020-12-25T17:46:01Z' })
t.false(d.equalsDate(e)) t.false(d.equalsDate(e))
}) })
test('#equalsDate different month, different time', t => { test('#equalsDate different month, different time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
const e = new DateTimeWrapper({ text: '2020-11-24T17:46:01Z' }) const e = new DateTimeWrapper({ text: '2020-11-24T17:46:01Z' })
t.false(d.equalsDate(e)) t.false(d.equalsDate(e))
}) })
test('#equalsDate different year, different time', t => { test('#equalsDate different year, different time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
const e = new DateTimeWrapper({ text: '2021-12-24T17:46:01Z' }) const e = new DateTimeWrapper({ text: '2021-12-24T17:46:01Z' })
t.false(d.equalsDate(e)) t.false(d.equalsDate(e))
}) })
test('#getCurrentDatetimeAsString correct format', t => { test('#getCurrentDatetimeAsString correct format', (t) => {
const d = DateTimeWrapper.getCurrentDatetimeAsString() const d = DateTimeWrapper.getCurrentDatetimeAsString()
t.is(d[4], '-') t.is(d[4], '-')
t.is(d[7], '-') t.is(d[7], '-')
@ -69,10 +78,10 @@ test('#getCurrentDatetimeAsString correct format', t => {
t.is(d[13], ':') t.is(d[13], ':')
t.is(d[16], ':') t.is(d[16], ':')
t.is(d[19], '.') t.is(d[19], '.')
t.is(d[d.length-3], ':') t.is(d[d.length - 3], ':')
}) })
test('#getShortOffsetName usual time', t => { test('#getShortOffsetName usual time', (t) => {
const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' }) const d = new DateTimeWrapper({ text: '2020-12-24T16:45:00Z' })
t.is(d.getShortOffsetName(), 'UTC') t.is(d.getShortOffsetName(), 'UTC')
}) })

View File

@ -1,12 +1,14 @@
import { DateTime } from 'luxon' import { DateTime } from 'luxon'
export default class DateTimeWrapper { export default class DateTimeWrapper {
constructor({ locale = 'en-GB', text, timeZone = 'utc' } = {}) { constructor({ locale = 'en-GB', text, timeZone = 'utc' } = {}) {
if (!timeZone) { if (!timeZone) {
timeZone = 'utc' timeZone = 'utc'
} }
if (timeZone.includes(':') && timeZone.substring(0, 3).toUpperCase() !== 'UTC') { if (
timeZone.includes(':') &&
timeZone.substring(0, 3).toUpperCase() !== 'UTC'
) {
timeZone = 'UTC' + timeZone timeZone = 'UTC' + timeZone
} }
this.dateTime = DateTime.fromISO(text, { locale, zone: timeZone }) this.dateTime = DateTime.fromISO(text, { locale, zone: timeZone })
@ -25,11 +27,13 @@ export default class DateTimeWrapper {
} }
equalsDate(other) { equalsDate(other) {
return this.dateTime && return (
this.dateTime &&
other.dateTime && other.dateTime &&
this.dateTime.day === other.dateTime.day && this.dateTime.day === other.dateTime.day &&
this.dateTime.month === other.dateTime.month && this.dateTime.month === other.dateTime.month &&
this.dateTime.year === other.dateTime.year this.dateTime.year === other.dateTime.year
)
} }
static getCurrentDatetimeAsString() { static getCurrentDatetimeAsString() {

View File

@ -9,7 +9,7 @@ test.before(() => {
document = new JSDOM().window.document document = new JSDOM().window.document
}) })
test.beforeEach(t => { test.beforeEach((t) => {
t.context.list = document.createElement('ul') t.context.list = document.createElement('ul')
t.context.list.setAttribute('data-locale', 'en-GB') t.context.list.setAttribute('data-locale', 'en-GB')
t.context.list.setAttribute('data-maximum', '2') t.context.list.setAttribute('data-maximum', '2')
@ -17,9 +17,12 @@ test.beforeEach(t => {
const listElement = document.createElement('li') const listElement = document.createElement('li')
listElement.setAttribute('style', 'display: none;') listElement.setAttribute('style', 'display: none;')
t.context.list.appendChild(listElement) t.context.list.appendChild(listElement)
const listElement2 = document.createElement('li')
listElement2.setAttribute('style', 'display: none;')
t.context.list.appendChild(listElement2)
}) })
test('#displayEvents one event', t => { test('#displayEvents one event', (t) => {
const list = t.context.list const list = t.context.list
const data = { const data = {
events: { events: {
@ -31,31 +34,48 @@ test('#displayEvents one event', t => {
endsOn: '2021-04-15T15:30:00Z', endsOn: '2021-04-15T15:30:00Z',
physicalAddress: { physicalAddress: {
description: 'c', description: 'c',
locality: 'd' locality: 'd',
} },
} },
] ],
} },
} }
displayEvents({ data, document, list }) displayEvents({ data, document, list })
t.is(list.children.length, 2) t.is(list.children.length, 3)
t.is(list.children[1].childNodes[0].tagName, 'A') t.is(list.children[2].childNodes[0].tagName, 'A')
t.is(list.children[1].childNodes[0].getAttribute('href'), 'b') t.is(list.children[2].childNodes[0].getAttribute('href'), 'b')
t.is(list.children[1].childNodes[0].childNodes[0].nodeValue, 'a') t.is(list.children[2].childNodes[0].childNodes[0].nodeValue, 'a')
t.is(list.children[1].childNodes[1].tagName, 'BR') t.is(list.children[2].childNodes[1].tagName, 'BR')
t.is(list.children[1].childNodes[2].nodeValue, '15/04/2021 10:30 - 15:30') t.is(list.children[2].childNodes[2].nodeValue, '15/04/2021 10:30 - 15:30')
t.is(list.children[1].childNodes[3].tagName, 'BR') t.is(list.children[2].childNodes[3].tagName, 'BR')
t.is(list.children[1].childNodes[4].nodeValue, 'c, d') t.is(list.children[2].childNodes[4].nodeValue, 'c, d')
}) })
test('#displayErrorMessage no children added', t => { test('#displayErrorMessage no children added', (t) => {
const list = t.context.list const list = t.context.list
displayErrorMessage({ data: '', list }) displayErrorMessage({ data: '', list })
t.is(list.children.length, 1) t.is(list.children.length, 2)
}) })
test('#displayErrorMessage error message display', t => { test('#displayErrorMessage error message display', (t) => {
const list = t.context.list const list = t.context.list
displayErrorMessage({ data: '', list }) displayErrorMessage({ data: '', list })
t.is(list.children[0].style.display, 'block') t.is(list.children[0].style.display, 'block')
t.is(list.children[1].style.display, 'none')
})
test('#displayErrorMessage group not found error message display', (t) => {
const list = t.context.list
const data = {
response: {
errors: [
{
code: 'group_not_found',
},
],
},
}
displayErrorMessage({ data, list })
t.is(list.children[0].style.display, 'none')
t.is(list.children[1].style.display, 'block')
}) })

View File

@ -5,13 +5,21 @@ export function displayEvents({ data, document, list }) {
const locale = list.getAttribute('data-locale') const locale = list.getAttribute('data-locale')
const maxEventsCount = list.getAttribute('data-maximum') const maxEventsCount = list.getAttribute('data-maximum')
const timeZone = list.getAttribute('data-time-zone') const timeZone = list.getAttribute('data-time-zone')
const isShortOffsetNameShown = list.hasAttribute('data-is-short-offset-name-shown') const isShortOffsetNameShown = list.hasAttribute(
const events = data.events ? data.events.elements : data.group.organizedEvents.elements 'data-is-short-offset-name-shown'
)
const events = data.events
? data.events.elements
: data.group.organizedEvents.elements
const eventsCount = Math.min(maxEventsCount, events.length) const eventsCount = Math.min(maxEventsCount, events.length)
for (let i = 0; i < eventsCount; i++) { for (let i = 0; i < eventsCount; i++) {
const li = document.createElement('li') const li = document.createElement('li')
const a = createAnchorElement({ document, text: events[i].title, url: events[i].url }) const a = createAnchorElement({
document,
text: events[i].title,
url: events[i].url,
})
li.appendChild(a) li.appendChild(a)
const br = document.createElement('br') const br = document.createElement('br')
@ -30,7 +38,7 @@ export function displayEvents({ data, document, list }) {
if (events[i].physicalAddress) { if (events[i].physicalAddress) {
const location = Formatter.formatLocation({ const location = Formatter.formatLocation({
description: events[i].physicalAddress.description, description: events[i].physicalAddress.description,
locality: events[i].physicalAddress.locality locality: events[i].physicalAddress.locality,
}) })
if (location) { if (location) {
const brBeforeLocation = document.createElement('br') const brBeforeLocation = document.createElement('br')
@ -47,5 +55,15 @@ export function displayEvents({ data, document, list }) {
export function displayErrorMessage({ data, list }) { export function displayErrorMessage({ data, list }) {
console.error(data) console.error(data)
list.children[0].style.display = 'block' if (
Object.prototype.hasOwnProperty.call(data, 'response') &&
Object.prototype.hasOwnProperty.call(data.response, 'errors') &&
data.response.errors.length > 0 &&
Object.prototype.hasOwnProperty.call(data.response.errors[0], 'code') &&
data.response.errors[0].code === 'group_not_found'
) {
list.children[1].style.display = 'block'
} else {
list.children[0].style.display = 'block'
}
} }

View File

@ -5,7 +5,7 @@ const NAME = '<wordpress-name>'
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const eventLists = document.getElementsByClassName(NAME + '_events-list') const eventLists = document.getElementsByClassName(NAME + '_events-list')
for (let list of eventLists) { for (const list of eventLists) {
const url = list.getAttribute('data-url') + '/api' const url = list.getAttribute('data-url') + '/api'
const limit = parseInt(list.getAttribute('data-maximum')) const limit = parseInt(list.getAttribute('data-maximum'))
const groupName = list.getAttribute('data-group-name') const groupName = list.getAttribute('data-group-name')

View File

@ -1,37 +1,51 @@
import test from 'ava' import test from 'ava'
import Formatter from './formatter' import Formatter from './formatter'
test('#formatDate one date', t => { test('#formatDate one date', (t) => {
const date = Formatter.formatDate({ start: '2021-04-15T10:30:00Z', end: '2021-04-15T15:30:00Z' }) const date = Formatter.formatDate({
start: '2021-04-15T10:30:00Z',
end: '2021-04-15T15:30:00Z',
})
t.is(date, '15/04/2021 10:30 - 15:30') t.is(date, '15/04/2021 10:30 - 15:30')
}) })
test('#formatDate one date with short offset name', t => { test('#formatDate one date with short offset name', (t) => {
const date = Formatter.formatDate({ start: '2021-04-15T10:30:00Z', end: '2021-04-15T15:30:00Z', isShortOffsetNameShown: true }) const date = Formatter.formatDate({
start: '2021-04-15T10:30:00Z',
end: '2021-04-15T15:30:00Z',
isShortOffsetNameShown: true,
})
t.is(date, '15/04/2021 10:30 - 15:30 (UTC)') t.is(date, '15/04/2021 10:30 - 15:30 (UTC)')
}) })
test('#formatDate two dates', t => { test('#formatDate two dates', (t) => {
const date = Formatter.formatDate({ start: '2021-04-15T10:30:00Z', end: '2021-04-16T15:30:00Z' }) const date = Formatter.formatDate({
start: '2021-04-15T10:30:00Z',
end: '2021-04-16T15:30:00Z',
})
t.is(date, '15/04/2021 10:30 - 16/04/2021 15:30') t.is(date, '15/04/2021 10:30 - 16/04/2021 15:30')
}) })
test('#formatDate two dates with short offset name', t => { test('#formatDate two dates with short offset name', (t) => {
const date = Formatter.formatDate({ start: '2021-04-15T10:30:00Z', end: '2021-04-16T15:30:00Z', isShortOffsetNameShown: true }) const date = Formatter.formatDate({
start: '2021-04-15T10:30:00Z',
end: '2021-04-16T15:30:00Z',
isShortOffsetNameShown: true,
})
t.is(date, '15/04/2021 10:30 (UTC) - 16/04/2021 15:30 (UTC)') t.is(date, '15/04/2021 10:30 (UTC) - 16/04/2021 15:30 (UTC)')
}) })
test('#formatLocation both parameters', t => { test('#formatLocation both parameters', (t) => {
const date = Formatter.formatLocation({ description: 'a', locality: 'b' }) const date = Formatter.formatLocation({ description: 'a', locality: 'b' })
t.is(date, 'a, b') t.is(date, 'a, b')
}) })
test('#formatLocation description only', t => { test('#formatLocation description only', (t) => {
const date = Formatter.formatLocation({ description: 'a' }) const date = Formatter.formatLocation({ description: 'a' })
t.is(date, 'a') t.is(date, 'a')
}) })
test('#formatLocation locality only', t => { test('#formatLocation locality only', (t) => {
const date = Formatter.formatLocation({ locality: 'a' }) const date = Formatter.formatLocation({ locality: 'a' })
t.is(date, 'a') t.is(date, 'a')
}) })

View File

@ -1,9 +1,12 @@
import DateTimeWrapper from './date-time-wrapper' import DateTimeWrapper from './date-time-wrapper'
export default class Formatter { export default class Formatter {
static formatDate({ locale, timeZone, start, end, isShortOffsetNameShown }) { static formatDate({ locale, timeZone, start, end, isShortOffsetNameShown }) {
const startDateTime = new DateTimeWrapper({ locale, text: start, timeZone }) const startDateTime = new DateTimeWrapper({
locale,
text: start,
timeZone,
})
const endDateTime = new DateTimeWrapper({ locale, text: end, timeZone }) const endDateTime = new DateTimeWrapper({ locale, text: end, timeZone })
let dateText = startDateTime.getShortDate() let dateText = startDateTime.getShortDate()
dateText += ' ' + startDateTime.get24Time() dateText += ' ' + startDateTime.get24Time()

View File

@ -21,14 +21,18 @@ export function getUpcomingEvents({ url, limit }) {
} }
} }
` `
const dataInCache = SessionCache.get(sessionStorage, { url, query, variables: { limit }}) const dataInCache = SessionCache.get(sessionStorage, {
if (dataInCache !== null) url,
query,
variables: { limit },
})
if (dataInCache !== null) {
return Promise.resolve(dataInCache) return Promise.resolve(dataInCache)
return request(url, query, { limit }) }
.then((data) => { return request(url, query, { limit }).then((data) => {
SessionCache.add(sessionStorage, { url, query, variables: { limit }}, data) SessionCache.add(sessionStorage, { url, query, variables: { limit } }, data)
return Promise.resolve(data) return Promise.resolve(data)
}) })
} }
export function getUpcomingEventsByGroupName({ url, limit, groupName }) { export function getUpcomingEventsByGroupName({ url, limit, groupName }) {
@ -53,12 +57,22 @@ export function getUpcomingEventsByGroupName({ url, limit, groupName }) {
} }
` `
const afterDatetime = DateTimeWrapper.getCurrentDatetimeAsString() const afterDatetime = DateTimeWrapper.getCurrentDatetimeAsString()
const dataInCache = SessionCache.get(sessionStorage, { url, query, variables: { afterDatetime, groupName, limit }}) const dataInCache = SessionCache.get(sessionStorage, {
if (dataInCache !== null) url,
query,
variables: { afterDatetime, groupName, limit },
})
if (dataInCache !== null) {
return Promise.resolve(dataInCache) return Promise.resolve(dataInCache)
return request(url, query, { afterDatetime, groupName, limit }) }
.then((data) => { return request(url, query, { afterDatetime, groupName, limit }).then(
SessionCache.add(sessionStorage, { url, query, variables: { afterDatetime, groupName, limit }}, data) (data) => {
SessionCache.add(
sessionStorage,
{ url, query, variables: { afterDatetime, groupName, limit } },
data
)
return Promise.resolve(data) return Promise.resolve(data)
}) }
)
} }

View File

@ -9,7 +9,7 @@ test.beforeEach(() => {
document = new JSDOM().window.document document = new JSDOM().window.document
}) })
test('#createAnchorElement usual parameters', t => { test('#createAnchorElement usual parameters', (t) => {
const a = createAnchorElement({ document, text: 'a', url: 'b' }) const a = createAnchorElement({ document, text: 'a', url: 'b' })
t.is(a.tagName, 'A') t.is(a.tagName, 'A')
t.is(a.innerHTML, 'a') t.is(a.innerHTML, 'a')

View File

@ -1,6 +1,6 @@
import test from 'ava' import test from 'ava'
import hash from './object-hash-wrapper' import hash from './object-hash-wrapper'
test('#hash object', t => { test('#hash object', (t) => {
t.is(hash({foo: 'bar'}), 'a75c05bdca7d704bdfcd761913e5a4e4636e956b') t.is(hash({ foo: 'bar' }), 'a75c05bdca7d704bdfcd761913e5a4e4636e956b')
}) })

View File

@ -2,7 +2,6 @@ import test from 'ava'
import SessionCache from './session-cache' import SessionCache from './session-cache'
const fakeStorage = { const fakeStorage = {
elements: {}, elements: {},
clear() { clear() {
@ -17,18 +16,18 @@ const fakeStorage = {
setItem(key, value) { setItem(key, value) {
this.elements[key] = value this.elements[key] = value
} },
} }
test.afterEach(() => { test.afterEach(() => {
fakeStorage.clear() fakeStorage.clear()
}) })
test('#add & #get', t => { test('#add & #get', (t) => {
SessionCache.add(fakeStorage, { a: 'b' }, { c: 'd' }) SessionCache.add(fakeStorage, { a: 'b' }, { c: 'd' })
t.deepEqual(SessionCache.get(fakeStorage, { a: 'b' }), { c: 'd' }) t.deepEqual(SessionCache.get(fakeStorage, { a: 'b' }), { c: 'd' })
}) })
test('#get no entry', t => { test('#get no entry', (t) => {
t.is(SessionCache.get(fakeStorage, { a: 'bb' }), null) t.is(SessionCache.get(fakeStorage, { a: 'bb' }), null)
}) })

View File

@ -3,7 +3,6 @@ import hash from './object-hash-wrapper'
const MAX_AGE_IN_MS = 120000 const MAX_AGE_IN_MS = 120000
export default class SessionCache { export default class SessionCache {
static add(storage, parameters, data) { static add(storage, parameters, data) {
const key = hash(parameters) const key = hash(parameters)
const timestamp = Date.now() const timestamp = Date.now()
@ -17,7 +16,11 @@ export default class SessionCache {
static get(storage, parameters) { static get(storage, parameters) {
const key = hash(parameters) const key = hash(parameters)
const value = JSON.parse(storage.getItem(key)) const value = JSON.parse(storage.getItem(key))
if (value && value.timestamp && value.timestamp > Date.now() - MAX_AGE_IN_MS) if (
value &&
value.timestamp &&
value.timestamp > Date.now() - MAX_AGE_IN_MS
)
return value.data return value.data
return null return null
} }

View File

@ -12,4 +12,5 @@ if (!defined('ABSPATH')) {
data-time-zone="<?php echo esc_attr($timeZone); ?>" data-time-zone="<?php echo esc_attr($timeZone); ?>"
<?php echo $isShortOffsetNameShown ? 'data-is-short-offset-name-shown' : ''; ?>> <?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 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> </ul>

48
webpack.config.js Normal file
View File

@ -0,0 +1,48 @@
/* eslint-disable no-undef */
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const PACKAGE = require('./package.json')
const FOLDER_SOURCE = './source'
module.exports = {
entry: {
'block-events-loader':
FOLDER_SOURCE + '/' + PACKAGE.name + '/front/block-events-loader.js',
'events-loader':
FOLDER_SOURCE + '/' + PACKAGE.name + '/front/events-loader.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'build/' + PACKAGE.name + '/front'),
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
},
},
],
},
plugins: [
new CopyPlugin({
patterns: [
{
context: FOLDER_SOURCE + '/' + PACKAGE.name,
from: '**/*.php',
to: '../',
},
{
context: FOLDER_SOURCE + '/' + PACKAGE.name,
from: '**/*.txt',
to: '../',
},
],
}),
],
}