Skip to content

Commit

Permalink
feat: add capability to patch block config at runtime (#246)
Browse files Browse the repository at this point in the history
Introduce a new `window.hlx.patchBlockConfig` array of functions extension point.

The functions get the current `block` as input, and need to return an object with 3 values `{ blockName, cssPath, jsPath }`. These are then used to load the actual JS and CSS for the block.

Co-authored-by: Lars Trieloff <lars@trieloff.net>
  • Loading branch information
ramboz and trieloff authored Aug 25, 2023
1 parent 3b370f3 commit a774acc
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions scripts/lib-franklin.js
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,26 @@ export function buildBlock(blockName, content) {
return (blockEl);
}

/**
* Gets the configuration for the given block, and also passes
* the config through all custom patching helpers added to the project.
*
* @param {Element} block The block element
* @returns {Object} The block config (blockName, cssPath and jsPath)
*/
function getBlockConfig(block) {
const { blockName } = block.dataset;
const cssPath = `${window.hlx.codeBasePath}/blocks/${blockName}/${blockName}.css`;
const jsPath = `${window.hlx.codeBasePath}/blocks/${blockName}/${blockName}.js`;
const original = { blockName, cssPath, jsPath };
return window.hlx.patchBlockConfig
.filter((fn) => typeof fn === 'function')
.reduce(
(config, fn) => fn(config, original),
{ blockName, cssPath, jsPath },
);
}

/**
* Loads JS and CSS for a block.
* @param {Element} block The block element
Expand All @@ -439,13 +459,13 @@ export async function loadBlock(block) {
const status = block.dataset.blockStatus;
if (status !== 'loading' && status !== 'loaded') {
block.dataset.blockStatus = 'loading';
const { blockName } = block.dataset;
const { blockName, cssPath, jsPath } = getBlockConfig(block);
try {
const cssLoaded = loadCSS(`${window.hlx.codeBasePath}/blocks/${blockName}/${blockName}.css`);
const cssLoaded = loadCSS(cssPath);
const decorationComplete = new Promise((resolve) => {
(async () => {
try {
const mod = await import(`../blocks/${blockName}/${blockName}.js`);
const mod = await import(jsPath);
if (mod.default) {
await mod.default(block);
}
Expand Down Expand Up @@ -647,6 +667,7 @@ export function setup() {
window.hlx.RUM_MASK_URL = 'full';
window.hlx.codeBasePath = '';
window.hlx.lighthouse = new URLSearchParams(window.location.search).get('lighthouse') === 'on';
window.hlx.patchBlockConfig = [];

const scriptEl = document.querySelector('script[src$="/scripts/scripts.js"]');
if (scriptEl) {
Expand Down

0 comments on commit a774acc

Please sign in to comment.