Skip to content

Commit

Permalink
PLANET-7175 Fix timeline block editor error (#2250)
Browse files Browse the repository at this point in the history
Ref. https://jira.greenpeace.org/browse/PLANET-7175

The error was caused by conflicts between the underscore and lodash libraries.
  • Loading branch information
sagarsdeshmukh committed Apr 17, 2024
1 parent daaf80d commit 5d71f31
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
11 changes: 10 additions & 1 deletion assets/src/blocks/Timeline/TimelineEditorScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {Timeline} from './Timeline';
import {languages} from './TimelineLanguages';
import {URLDescriptionHelp} from './URLDescriptionHelp';
import {debounce} from '@wordpress/compose';
import {isLodash} from '../../functions/isLodash';

const {__} = wp.i18n;
const TIMELINE_JS_VERSION = '3.8.12';
Expand All @@ -24,9 +25,17 @@ const positions = [
];

const loadAssets = () => {
const revertLodash = function() {
// Address conflicts between the underscore and lodash libraries.
if (isLodash()) {
// eslint-disable-next-line no-undef
_.noConflict();
}
};
// eslint-disable-next-line no-unused-vars
const [scriptLoaded, scriptError] = useScript(
`https://cdn.knightlab.com/libs/timeline3/${TIMELINE_JS_VERSION}/js/timeline-min.js`
`https://cdn.knightlab.com/libs/timeline3/${TIMELINE_JS_VERSION}/js/timeline-min.js`,
revertLodash
);

// eslint-disable-next-line no-unused-vars
Expand Down
27 changes: 27 additions & 0 deletions assets/src/functions/isLodash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Determines if _ is lodash or not.
export const isLodash = () => {
let isItLodash = false;

// If _ is defined and the function _.forEach exists then we know underscore OR lodash are in place
// eslint-disable-next-line no-undef
if ('undefined' !== typeof (_) && 'function' === typeof (_.forEach)) {
// A small sample of some of the functions that exist in lodash but not underscore
const funcs = ['get', 'set', 'at', 'cloneDeep'];

// Simplest if assume exists to start
isItLodash = true;

funcs.forEach(func => {
// If just one of the functions do not exist, then not lodash
// eslint-disable-next-line no-undef
isItLodash = ('function' !== typeof (_[func])) ? false : isItLodash;
});
}

if (isItLodash) {
// We know that lodash is loaded in the _ variable
return true;
}
// We know that lodash is NOT loaded
return false;
};

0 comments on commit 5d71f31

Please sign in to comment.