Skip to content

Commit

Permalink
TECH-740: Addressed code smells (#1220)
Browse files Browse the repository at this point in the history
  • Loading branch information
r3dm1ke authored May 23, 2024
1 parent f812abb commit 387972e
Show file tree
Hide file tree
Showing 57 changed files with 330 additions and 226 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const editPanelRefetches = {};

let triggerRefetch = key => {
let refetch = editPanelRefetches[key];
const triggerRefetch = key => {
const refetch = editPanelRefetches[key];
if (!refetch) {
return;
}
Expand All @@ -13,20 +13,20 @@ let triggerRefetch = key => {
}
};

let setPreviewRefetcher = refetcherData => {
const setPreviewRefetcher = refetcherData => {
// In content editor only the path and the language can change for the preview query, so just this parameters to build a key
// ideally the key of a refetcher should be all it's queryParams.
editPanelRefetches[buildPreviewRefetcherKey(refetcherData.queryParams.path, refetcherData.queryParams.language)] = refetcherData;
};

let invalidateRefetch = queryParams => delete editPanelRefetches[buildPreviewRefetcherKey(queryParams.path, queryParams.language)];
const invalidateRefetch = queryParams => delete editPanelRefetches[buildPreviewRefetcherKey(queryParams.path, queryParams.language)];

let refetchPreview = (path, language) => {
const refetchPreview = (path, language) => {
triggerRefetch(buildPreviewRefetcherKey(path, language));
};

let buildPreviewRefetcherKey = (path, language) => {
return path + '_' + language;
const buildPreviewRefetcherKey = (path, language) => {
return `${path}_${language}`;
};

export {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@
margin: var(--spacing-small) 0;
}

.languageSwitcher {
margin: var(--spacing-small) 0;
}

.saveActions {
position: relative;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,14 @@ export const EditPanelCompact = ({title, createAnother}) => {
<div className="flexRow">
<Typography variant="heading">{truncate(title, 40)}</Typography>
<div className="flexFluid"/>
{mode !== Constants.routes.baseCreateRoute && showAdvancedMode && <Button className={styles.uppercase} label={t('label.contentEditor.create.advanced')} icon={<Edit/>} data-sel-role="advancedMode" onClick={setFullscreen}/>}
{mode !== Constants.routes.baseCreateRoute && showAdvancedMode &&
<Button
className={styles.uppercase}
label={t('label.contentEditor.create.advanced')}
icon={<Edit/>}
data-sel-role="advancedMode"
onClick={setFullscreen}
/>}
<DisplayAction actionKey="content-editor/header/3dots" render={DotsButtonRenderer}/>
</div>
<div className={clsx('flexRow', 'alignCenter', styles.languageSwitcher)}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,19 @@ export const ContentPath = ({path}) => {
const dirty = isDirty(formik, i18nContext);

const doRedirect = itemPath => {
let mode = 'pages';
let _mode = 'pages';
let app = 'jcontent';
if (itemPath.startsWith('/sites/systemsite/categories/') || itemPath === '/sites/systemsite/categories') {
mode = 'category';
_mode = 'category';
app = 'category-manager';
} else if (/^\/sites\/[^/]+\/files(\/.*)?$/.test(itemPath)) {
mode = 'media';
_mode = 'media';
} else if (/^\/sites\/[^/]+\/contents(\/.*)?$/.test(itemPath)) {
mode = 'content-folders';
_mode = 'content-folders';
}

const onExited = () => {
dispatch(cmGoto({app, mode, path: itemPath, params: {sub: false}}));
dispatch(cmGoto({app, mode: _mode, path: itemPath, params: {sub: false}}));
};

updateEditorConfig({closed: true, onExited});
Expand All @@ -103,7 +103,7 @@ export const ContentPath = ({path}) => {
const node = data?.jcr?.node;
const items = useMemo(() => getItems(mode, node), [mode, node]);

let onCloseDialog = useCallback(() => setDialogState({open: false}), [setDialogState]);
const onCloseDialog = useCallback(() => setDialogState({open: false}), [setDialogState]);
if (error) {
return <>{error.message}</>;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,15 @@ export const EditPanelLanguageSwitcher = () => {
const labelPrefix = 'jcontent:label.contentEditor.header.languageSwitcher';

function getLanguageOptions() {
let langLabel; // Current dropdown selection
let _langLabel; // Current dropdown selection
const translatedOption = {groupLabel: t(`${labelPrefix}.switchLanguage`), options: []};
const notTranslatedOption = {groupLabel: t(`${labelPrefix}.addTranslation.${mode}`), options: []};
const translatedLangs = nodeData?.translationLanguages || [];

siteInfo.languages.forEach(item => {
// Const label = item.displayName === item.uiLanguageDisplayName ? getCapitalized(item.displayName) : `${getCapitalized(item.displayName)} (${getCapitalized(item.uiLanguageDisplayName)})`;
const label = getCapitalized(item.uiLanguageDisplayName);
if (item.language === currentLanguage) {
langLabel = label;
_langLabel = label;
}

// Group language options depending on whether node has been translated to this language already or not
Expand All @@ -37,8 +36,8 @@ export const EditPanelLanguageSwitcher = () => {
});
});

const langOptions = [translatedOption, notTranslatedOption].filter(o => o.options.length); // Do not display group if empty
return {langLabel, langOptions};
const _langOptions = [translatedOption, notTranslatedOption].filter(o => o.options.length); // Do not display group if empty
return {langLabel: _langLabel, langOptions: _langOptions};
}

const {langLabel, langOptions} = getLanguageOptions();
Expand Down
30 changes: 16 additions & 14 deletions src/javascript/ContentEditor/ContentEditorApi/ContentEditorApi.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ function decode(hash) {
return values;
}

let getEncodedLocations = function (location, editorConfigs) {
const getEncodedLocations = function (location, editorConfigs) {
const {contentEditor, ...others} = decode(location.hash);

const valid = editorConfigs.every(config => Object.values(config).every(o => typeof o !== 'function'));

const cleanedHash = Object.keys(others).length > 0 ? rison.encode_uri(others) : '';
const locationWithoutEditors = rison.encode({search: location.search, hash: cleanedHash});
const locationFromState = (valid && editorConfigs.length > 0) ?
rison.encode({search: location.search, hash: '#' + rison.encode_uri({...others, contentEditor: JSON.parse(JSON.stringify(editorConfigs.map((({closed, ...obj}) => obj))))})}) :
locationWithoutEditors;
rison.encode({
search: location.search,
hash: '#' + rison.encode_uri({...others, contentEditor: JSON.parse(JSON.stringify(editorConfigs.map((({closed, ...obj}) => obj))))})
}) : locationWithoutEditors;

return {
locationFromState,
Expand Down Expand Up @@ -58,33 +60,33 @@ export const ContentEditorApi = () => {
setEditorConfigs(editorConfigs.map(e => ({...e, closed: true, onExited: () => {}})));
};

let newEditorConfig = editorConfig => {
const newEditorConfig = editorConfig => {
if (!editorConfig.formKey) {
editorConfig.formKey = 'modal_' + editorConfigs.length;
}

setEditorConfigs([...editorConfigs, editorConfig]);
};

let updateEditorConfig = (editorConfig, index) => {
let copy = Array.from(editorConfigs);
const updateEditorConfig = (editorConfig, index) => {
const copy = Array.from(editorConfigs);
copy[index] = {...copy[index], ...editorConfig};
setEditorConfigs(copy);
};

let onExited = index => {
const onExited = index => {
const copy = Array.from(editorConfigs);
const spliced = copy.splice(index, 1);
const onExited = spliced[0].onExited;
const onExitedCallback = spliced[0].onExited;

setEditorConfigs(copy);

if (onExited) {
onExited();
if (onExitedCallback) {
onExitedCallback();
} else if (spliced[0]?.isFullscreen) {
if (copy.length > 0) {
const {locationFromState} = getEncodedLocations(location, copy);
history.replace(rison.decode(locationFromState));
const {locationFromState: _locationFromState} = getEncodedLocations(location, copy);
history.replace(rison.decode(_locationFromState));
} else if (history.location.state?.wasPushed) {
history.go(-1);
} else {
Expand All @@ -93,7 +95,7 @@ export const ContentEditorApi = () => {
}
};

let context = useContentEditorApiContext();
const context = useContentEditorApiContext();
context.edit = useEdit(newEditorConfig);
context.create = useCreate(newEditorConfig, setContentTypeSelectorConfig);

Expand Down Expand Up @@ -192,7 +194,7 @@ export const ContentEditorApi = () => {
{editorConfigs.map((editorConfig, index) => {
return (
<ContentEditorModal
key={editorConfig.mode + '_' + editorConfig.uuid}
key={`${editorConfig.mode}_${editorConfig.uuid}`}
editorConfig={editorConfig}
updateEditorConfig={updatedEditorConfig => {
updateEditorConfig(updatedEditorConfig, index);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,9 @@ export const ContentEditorModal = ({editorConfig, updateEditorConfig, onExited})
updateEditorConfig({closed: true});
} else {
client.cache.flushNodeEntryByPath(originalNode.path);
Promise.all(window.contentModificationEventHandlers.map(handler => handler(updatedNode.uuid, originalNode.path, updatedNode.path.split('/').pop(), 'update'))).then(() => {
Promise.all(window.contentModificationEventHandlers.map(handler =>
handler(updatedNode.uuid, originalNode.path, updatedNode.path.split('/').pop(), 'update'))
).then(() => {
// Otherwise refresh and close
updateEditorConfig({closed: true});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import {AddCircle, toIconComponent} from '@jahia/moonstone';

let getIconStart = function (node) {
const getIconStart = function (node) {
return (node.iconURL && !node.iconURL.endsWith('/nt_base.png') && toIconComponent(node.iconURL)) || <AddCircle/>;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const DatePickerCmp = ({
const selectedHour = selectedDateTime ? dayjs(selectedDateTime).format('HH:mm') : '00:00';

return (
<div className={classes.container + ' ' + (isDateTime ? classes.containerDateTime : '')}>
<div className={`${classes.container} ${isDateTime ? classes.containerDateTime : ''}`}>
<DayPicker
locale={lang}
disabledDays={disabledDays}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ const formatDateTime = (datetime, lang, variant, displayDateFormat) => {
};

export const getMaskOptions = (displayDateMask, isDateTime) => {
const mask = displayDateMask ? displayDateMask : (isDateTime ? '__/__/____ __:__' : '__/__/____');
const defaultDateMask = isDateTime ? '__/__/____ __:__' : '__/__/____';
const mask = displayDateMask ? displayDateMask : defaultDateMask;
return {
mask: mask.replace(/_/g, '#'),
empty: mask
Expand Down Expand Up @@ -141,10 +142,10 @@ export const DatePickerInput = ({
variant={variant}
lang={lang}
selectedDateTime={datetime}
onSelectDateTime={datetime => {
setDatetime(datetime);
onSelectDateTime={_datetime => {
setDatetime(_datetime);
setDatetimeString(
formatDateTime(datetime, lang, variant, displayDateFormat)
formatDateTime(_datetime, lang, variant, displayDateFormat)
);
}}
{...dayPickerProps}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export const CheckboxChoiceList = ({field, value = [], id, inputContext, onChang

const items = field.valueConstraints;
if (!items) {
return;
return null;
}

const isInverted = field.selectorOptions?.some(option => option.name === 'isInvertedSelection');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ export const DateTimePicker = ({id, field, value, editorContext, onChange, onBlu

const userNavigatorLocale = editorContext.browserLang;

let dateFormat = userNavigatorLocale in specificDateFormat ? specificDateFormat[userNavigatorLocale] : 'DD/MM/YYYY';
let displayDateFormat = isDateTime ? (dateFormat + ' HH:mm') : dateFormat;
const dateFormat = userNavigatorLocale in specificDateFormat ? specificDateFormat[userNavigatorLocale] : 'DD/MM/YYYY';
const displayDateFormat = isDateTime ? (dateFormat + ' HH:mm') : dateFormat;

let maskLocale = String(dateFormat).replace(/[^\W]+?/g, '_');
const maskLocale = String(dateFormat).replace(/[^\W]+?/g, '_');

const displayDateMask = isDateTime ? maskLocale + ' __:__' : maskLocale;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,28 @@ const _buildDisableDay = ({type, boundary, disableBoundary, datetime, offset}) =

return disabledDays;
}

return undefined;
};

export function fillDisabledDaysFromJCRConstraints(field, datetime) {
if (field.valueConstraints && field.valueConstraints.length > 0) {
const disableDays = [];
const {lowerBoundary, disableLowerBoundary, upperBoundary, disableUpperBoundary} = extractRangeConstraints(field.valueConstraints[0].value.string);
// Add one day / minute to the disabled dates if the lower boundary is not include, ex : "(2019-06-01,.."
let lowerDisabledDays = _buildDisableDay({type: 'before', boundary: lowerBoundary, disableBoundary: disableLowerBoundary, datetime, offset: 1});
const lowerDisabledDays = _buildDisableDay({type: 'before', boundary: lowerBoundary, disableBoundary: disableLowerBoundary, datetime, offset: 1});
if (lowerDisabledDays) {
disableDays.push(lowerDisabledDays);
}

// Remove one day / minute to the disabled dates if the upper boundary is not include, ex : "..,2019-06-01)"
let upperDisabledDays = _buildDisableDay({type: 'after', boundary: upperBoundary, disableBoundary: disableUpperBoundary, datetime, offset: -1});
const upperDisabledDays = _buildDisableDay({type: 'after', boundary: upperBoundary, disableBoundary: disableUpperBoundary, datetime, offset: -1});
if (upperDisabledDays) {
disableDays.push(upperDisabledDays);
}

return disableDays;
}

return undefined;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,17 @@ export const CopyLanguageDialog = ({
}) => {
const client = useApolloClient();

const getDataFromSelectedLanguage = async language => {
let variables = {
uilang: language,
const getDataFromSelectedLanguage = async _language => {
const variables = {
uilang: _language,
formik,
language: language,
language: _language,
uuid: uuid,
writePermission: `jcr:modifyProperties_default_${language}`,
writePermission: `jcr:modifyProperties_default_${_language}`,
childrenFilterTypes: Constants.childrenFilterTypes
};

let formAndData = await client.query({query: EditFormQuery, variables: variables});
const formAndData = await client.query({query: EditFormQuery, variables: variables});

return getI18nFieldAndValues(formAndData);
};
Expand All @@ -54,14 +54,14 @@ export const CopyLanguageDialog = ({
const handleApply = () => {
getDataFromSelectedLanguage(currentOption.value).then(data => {
data.forEach(value => {
formik.setFieldValue(value.definition.declaringNodeType.name + '_' + value.name, value.multiple ? value.values : value.value);
formik.setFieldValue(`${value.definition.declaringNodeType.name}_${value.name}`, value.multiple ? value.values : value.value);
});
});

onCloseDialog();
};

let isApplyDisabled = defaultOption.value === currentOption.value;
const isApplyDisabled = defaultOption.value === currentOption.value;

return (
<Dialog fullWidth
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const ApolloCacheFlushOnGWTSave = () => {
useEffect(() => {
// Register flush on GWT save
window.contentModificationEventHandlers = window.contentModificationEventHandlers || [];
let handler = nodeUuid => {
const handler = nodeUuid => {
client.cache.flushNodeEntryById(nodeUuid);
refetchFormData();
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const useContentEditorContext = () => useContext(ContentEditorContext);

const renderError = (siteInfoResult, t, notificationContext) => {
console.error('Error when fetching data: ' + siteInfoResult.error);
let message = t('label.contentEditor.error.queryingContent', {details: (siteInfoResult.error.message ? siteInfoResult.error.message : '')});
const message = t('label.contentEditor.error.queryingContent', {details: (siteInfoResult.error.message ? siteInfoResult.error.message : '')});
notificationContext.notify(message, ['closeButton', 'noAutomaticClose']);
return null;
};
Expand Down Expand Up @@ -87,7 +87,12 @@ export const ContentEditorContextProvider = ({useFormDefinition, children}) => {
uiLanguage: uiLanguage
});

const ranAllHooks = useOnBeforeContextHooks(!loading && !siteInfoResult.loading && !error && !siteInfoResult.error ? {nodeData, siteInfo: siteInfoResult.data.jcr.result} : undefined);
const ranAllHooks = useOnBeforeContextHooks(
!loading &&
!siteInfoResult.loading &&
!error &&
!siteInfoResult.error ? {nodeData, siteInfo: siteInfoResult.data.jcr.result} : undefined
);

if (error) {
// Check for ItemNotFound exception
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const Renderer = ({activeOption, setActiveOption, buttonLabel, onClick, tabs}) =
}

if (tab === 'channels') {
return;
return null;
}

return (
Expand Down
Loading

0 comments on commit 387972e

Please sign in to comment.