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

PLANET-7519: Guestbook block refactoring to block.json #2286

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
28 changes: 0 additions & 28 deletions assets/src/blocks/GuestBook/GuestBookBlock.js

This file was deleted.

3 changes: 0 additions & 3 deletions assets/src/blocks/GuestBook/GuestBookEditorScript.js

This file was deleted.

11 changes: 0 additions & 11 deletions assets/src/blocks/GuestBook/GuestBookScript.js

This file was deleted.

15 changes: 15 additions & 0 deletions assets/src/blocks/guestbook/block.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "planet4-blocks/guestbook",
"title": "50 Years GuestBook",
"icon": "admin-site-alt2",
"supports": {
"html": false,
"multiple": false
},
"viewScript": "file:./viewScript.js",
"editorScript": "file:./index.js",
"style": "",
"editorStyle": ""
}
8 changes: 8 additions & 0 deletions assets/src/blocks/guestbook/deprecated.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import metadata from './block.json';
import {frontendRendered} from '../../functions/frontendRendered';

const v1 = {
save: frontendRendered(metadata.name),
};

export default [v1];
11 changes: 11 additions & 0 deletions assets/src/blocks/guestbook/edit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const {__} = wp.i18n;

const GuestBookEdit = () => {
return (
<p className="EmptyMessage">
{__('This block only renders in the frontend', 'planet4-blocks-backend')}
</p>
);
};

export default GuestBookEdit;
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
export const GuestBookFrontend = () => {
const GuestBook = () => {
const buildURL = () => {
const hostname = window.location.hostname;
const pathname = window.location.pathname.slice(1);
const params = new URLSearchParams(window.location.search);
const storyID = params.get('id');
return `https://maps.greenpeace.org/maps/gpint/50th_guestbook/?origin_host=${hostname}&origin_path=${encodeURIComponent(pathname)}${storyID ? `&id=${storyID}` : ''}`;
};

return (
<p>
<iframe src={buildURL()} width="100%" height={700} title="GuestBook" />
</p>
);
};

export default GuestBook;
20 changes: 20 additions & 0 deletions assets/src/blocks/guestbook/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import metadata from './block.json';
import deprecated from './deprecated';
import edit from './edit';
import save from './save';

const {registerBlockType} = wp.blocks;

registerBlockType(metadata, {
title: '50 Years GuestBook',
icon: 'admin-site-alt2',
category: 'planet4-blocks',
supports: {
html: false, // Disable "Edit as HTML" block option.
multiple: false, // Use the block just once per post.
},
edit,
save,
deprecated,
});
5 changes: 5 additions & 0 deletions assets/src/blocks/guestbook/save.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import GuestBook from './guestbook';

export default function save() {
return <GuestBook />;
}
11 changes: 11 additions & 0 deletions assets/src/blocks/guestbook/viewScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {createRoot} from 'react-dom/client';
import metadata from './block.json';
import GuestBook from './guestbook';

// Fallback for non migrated content. Remove after migration.
document.querySelectorAll(`[data-render="${metadata.name}"]`).forEach(
blockNode => {
const rootElement = createRoot(blockNode);
rootElement.render(<GuestBook />);
}
);
131 changes: 131 additions & 0 deletions assets/src/webpack.blocks.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
const {dirname, extname, join, sep} = require('path');
const {readFileSync} = require('fs');
const {sync: glob} = require('fast-glob');
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const scriptFields = new Set(['viewScript', 'script', 'editorScript']);
const fromProjectRoot = fileName => join(dirname(dirname(__dirname)), fileName);
const srcDir = 'assets/src/';
const blocksDir = 'assets/src/blocks';

/**
* @param {Object} blockJson
* @return {null|Record<string, unknown>} Fields
*/
function getBlockJsonScriptFields(blockJson) {
let result = null;
for (const field of scriptFields) {
if (Object.hasOwn(blockJson, field)) {
if (!result) {
result = {};
}
result[field] = blockJson[field];
}
}
return result;
}

const getBlocksEntries = () => {
const blockMetadataFiles = glob('**/block.json', {
absolute: true,
cwd: fromProjectRoot(blocksDir),
});

if (blockMetadataFiles.length <= 0) {
return {};
}

const srcDirectory = fromProjectRoot(srcDir);
const entryPoints = {};

for (const blockMetadataFile of blockMetadataFiles) {
const fileContents = readFileSync(blockMetadataFile);
let parsedBlockJson;
// wrapping in try/catch in case the file is malformed
// this happens especially when new block.json files are added
// at which point they are completely empty and therefore not valid JSON
try {
parsedBlockJson = JSON.parse(fileContents);
} catch (error) {
console.log( //eslint-disable-line no-console
`Skipping "${blockMetadataFile.replace(
fromProjectRoot(sep), ''
)}" due to malformed JSON.`
); //eslint-disable-line no-console
}

const fields = getBlockJsonScriptFields(parsedBlockJson);

if (!fields) {
continue;
}

for (const value of Object.values(fields).flat()) {
if (!value.startsWith('file:')) {
continue;
}

// Removes the `file:` prefix.
const filepath = join(
dirname(blockMetadataFile),
value.replace('file:', '')
);

// Takes the path without the file extension, and relative to the defined source directory.
if (!filepath.startsWith(srcDirectory)) {
console.log( //eslint-disable-line no-console
`Skipping "${filepath}" listed in "${blockMetadataFile.replace(
fromProjectRoot(sep), ''
)}". File is located outside of the "${srcDirectory}" directory.`
);
return;
}
const entryName = filepath
.replace(extname(filepath), '')
.replace(srcDirectory, '')
.replace(/\\/g, '/');

// Detects the proper file extension used in the defined source directory.
const [entryFilepath] = glob(
`${entryName}.js`,
{
absolute: true,
cwd: srcDirectory,
}
);

if (!entryFilepath) {
console.log( //eslint-disable-line no-console
`Skipping "${entryFilepath}" listed in "${blockMetadataFile.replace(
fromProjectRoot(sep), ''
)}". File does not exist in the "${srcDirectory}" directory.`
);
return;
}
entryPoints[entryName] = entryFilepath;
}
}

if (Object.keys(entryPoints).length > 0) {
console.log(entryPoints); //eslint-disable-line no-console
return entryPoints;
}
};

module.exports = {
...defaultConfig,
entry: getBlocksEntries(),
plugins: [
...defaultConfig.plugins,
new CopyWebpackPlugin({
patterns: [
{
context: srcDir,
from: 'blocks/**/block.json',
noErrorOnMissing: true,
},
],
}),
],
};
Loading