Skip to content

refactor:added alert box for refresh and refactored the issue of cont… #724

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

Open
wants to merge 1 commit into
base: pre-stage
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,5 @@ export interface ModifiedField {
backupFieldType: string;
parentId: string;
uid: string;
_canSelect?: boolean;
}
43 changes: 27 additions & 16 deletions ui/src/components/ContentMapper/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R

const [searchContentType, setSearchContentType] = useState('');

const [rowIds, setRowIds] = useState({});
const [rowIds, setRowIds] = useState<Record<string, boolean>>({});
const [selectedEntries, setSelectedEntries] = useState<FieldMapType[]>([]);
const [contentTypeSchema, setContentTypeSchema] = useState<ContentTypesSchema[] | undefined>([]);
const [showFilter, setShowFilter] = useState<boolean>(false);
Expand All @@ -292,7 +292,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
const [isCsCTypeUpdated, setsCsCTypeUpdated] = useState<boolean>(false);
const [isLoadingSaveButton, setisLoadingSaveButton] = useState<boolean>(false);
const [activeFilter, setActiveFilter] = useState<string>('');

const [isAllCheck, setIsAllCheck] = useState<boolean>(false);

/** ALL HOOKS Here */
const { projectId = '' } = useParams();
Expand Down Expand Up @@ -361,6 +361,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R


if (newMigrationData?.content_mapping?.content_type_mapping?.[selectedContentType?.contentstackUid || ''] === otherContentType?.id) {
setIsAllCheck(false);
tableData?.forEach((row) => {
contentTypeSchema?.forEach((schema) => {

Expand Down Expand Up @@ -432,14 +433,16 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
}, [tableData, otherContentType]);

useEffect(() => {
if (isUpdated) {
if (isUpdated) {
setIsAllCheck(false);
setTableData(updatedRows);
setExistingField(updatedExstingField);
setSelectedOptions(updatedSelectedOptions);
setSelectedEntries(updatedRows);
setIsUpdated(false);
}
else{
setIsAllCheck(false);
setExistingField({});
setSelectedOptions([]);

Expand All @@ -449,15 +452,15 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
// To make all the fields checked
useEffect(() => {
const selectedId = tableData?.reduce<UidMap>((acc, item) => {
if(!item?.isDeleted) {
if(!item?.isDeleted && isAllCheck) {
acc[item?.id] = true;

}
return acc;
}, {});

setRowIds(selectedId);
}, [tableData]);
isAllCheck && setRowIds(selectedId);
}, [tableData, isAllCheck]);

// To fetch existing content types or global fields as per the type
useEffect(() => {
Expand Down Expand Up @@ -542,6 +545,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
},[contentTypeSchema]);
useEffect(() => {
if (existingField && isCsCTypeUpdated) {
setIsAllCheck(false);
const matchedKeys = new Set<string>();

contentTypeSchema?.forEach((item) => {
Expand Down Expand Up @@ -672,7 +676,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
setItemStatusMap({ ...itemStatusMap });

const validTableData = data?.fieldMapping?.filter((field: FieldMapType) => field?.otherCmsType !== undefined);

setIsAllCheck(true);
setTableData(validTableData ?? []);
setSelectedEntries(validTableData ?? []);
setTotalCounts(validTableData?.length);
Expand Down Expand Up @@ -717,7 +721,8 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
// eslint-disable-next-line no-unsafe-optional-chaining
setTableData([...tableData, ...validTableData ?? tableData]);
setTotalCounts([...tableData, ...validTableData ?? tableData]?.length);
setIsLoading(false)
setIsLoading(false);
setIsAllCheck(true);
} catch (error) {
console.error('loadMoreItems -> error', error);
}
Expand Down Expand Up @@ -749,6 +754,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
};

const openContentType = (i: number) => {
setIsAllCheck(true);
setIsFieldDeleted(false);
setActive(i);
const otherTitle = filteredContentTypes?.[i]?.contentstackUid;
Expand Down Expand Up @@ -821,24 +827,26 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R

// add row ids with their data to rowHistoryObj
useEffect(() => {
setIsAllCheck(false);
Object.keys(rowHistoryObj)?.forEach(key => delete rowHistoryObj[key]);
tableData?.forEach(item => {
rowHistoryObj[item?.id] = [{checked: true, at: Date.now(), ...modifiedObj(item)}]
});
}, [tableData]);

const getParentId = (uid: string) => {
return tableData?.find(i => i?.uid?.toLowerCase() === uid?.toLowerCase())?.id ?? ''
const getParentId = (uid: string) => {
return tableData?.find((i) => i?.uid?.toLowerCase() === uid?.toLowerCase() && i?.backupFieldType?.toLowerCase() === 'group')?.id ?? ''
}

const modifiedObj = (obj: FieldMapType) => {
const {backupFieldType, uid, id} = obj ?? {}
const {backupFieldType, uid, id, _canSelect} = obj ?? {}
const excludeArr = ["group"]
return {
id,
backupFieldType,
uid,
parentId : excludeArr?.includes?.(backupFieldType?.toLowerCase()) ? '' : getParentId(uid?.split('.')[0]?.toLowerCase())
parentId : excludeArr?.includes?.(backupFieldType?.toLowerCase()) ? '' : getParentId(uid?.split('.')[0]?.toLowerCase()),
_canSelect,
}
}

Expand Down Expand Up @@ -886,7 +894,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R

const handleSelectedEntries = (singleSelectedRowIds: string[]) => {
const selectedObj: UidMap = {};

setIsAllCheck(false);
singleSelectedRowIds?.forEach((uid: string) => {
const isId = selectedEntries?.some((item) => item?.id === uid);
if (isId) {
Expand Down Expand Up @@ -940,7 +948,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
})
}
}
} else if(latestRow?.parentId && !["title", "url"]?.includes?.(latestRow?.uid?.toLowerCase())){
} else if(latestRow?.parentId && latestRow?._canSelect === true){
// Extract the group UID if item is child of any group
const uidBeforeDot = latestRow?.uid?.split?.('.')?.[0]?.toLowerCase();
const groupItem = tableData?.find((entry) => entry?.uid?.toLowerCase() === uidBeforeDot);
Expand Down Expand Up @@ -972,7 +980,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
}
}

const updatedTableData = tableData?.map?.((tableItem) => {
const updatedTableData = selectedEntries?.map?.((tableItem) => {
// Mark the item as deleted if not found in selectedData
return {
...tableItem,
Expand All @@ -988,6 +996,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
const handleValueChange = (value: FieldTypes, rowIndex: string, rowContentstackFieldUid: string) => {
setIsDropDownChanged(true);
setFieldValue(value);
setIsAllCheck(false);
const updatedRows: FieldMapType[] = selectedEntries?.map?.((row) => {
if (row?.uid === rowIndex && row?.contentstackFieldUid === rowContentstackFieldUid) {
return { ...row, contentstackFieldType: value?.value };
Expand All @@ -1010,7 +1019,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R

const handleDropDownChange = (value: FieldTypes) => {
(value?.id !== otherContentType?.id) && setsCsCTypeUpdated(true);

setIsAllCheck(false);
setOtherContentType(value);
};

Expand Down Expand Up @@ -1503,6 +1512,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R
if (!updatedSelectedOptions?.includes?.(newValue)) {
updatedSelectedOptions.push(newValue);
}
setIsAllCheck(false);
setIsUpdated(true);
}

Expand Down Expand Up @@ -1620,6 +1630,7 @@ const ContentMapper = forwardRef(({handleStepChange}: contentMapperProps, ref: R

const handleSaveContentType = async () => {
setisLoadingSaveButton(true);
setIsAllCheck(false);
const orgId = selectedOrganisation?.uid;
const projectID = projectId;
if (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ const LanguageMapper = ({stack, uid} :{ stack : IDropDown, uid : string}) => {
const [cmsLocaleOptions, setcmsLocaleOptions] = useState<{ label: string; value: string }[]>([]);
const [sourceLocales, setsourceLocales] = useState<{ label: string; value: string }[]>([]);
const [isLoading, setisLoading] = useState<boolean>(false);
const [currentStack, setCurrentStack] = useState<IDropDown>();
const [currentStack, setCurrentStack] = useState<IDropDown>(stack);
const [previousStack, setPreviousStack] = useState<IDropDown>();
const [isStackChanged, setisStackChanged] = useState<boolean>(false);
const [stackValue, setStackValue] = useState<string>(stack?.value)
Expand Down
7 changes: 5 additions & 2 deletions ui/src/components/DestinationStack/Actions/LoadStacks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ const LoadStacks = (props: LoadFileFormatProps) => {
const [placeholder] = useState<string>('Select a stack');
const [localePlaceholder, setlocalePlaceholder ] = useState<string>('Master Locale will be set after stack selection');
const newMigrationDataRef = useRef(newMigrationData);
const [isStackLoading, setIsStackLoading] = useState<boolean>(true);

useEffect(() => {
newMigrationDataRef.current = newMigrationData;
Expand All @@ -111,6 +112,7 @@ const LoadStacks = (props: LoadFileFormatProps) => {
const handleOnSave = async (data: Stack) => {
try {
// Post data to backend
setIsStackLoading(true);
const resp = await createStacksInOrg(selectedOrganisation?.value, {
...data,
master_locale: data?.locale
Expand Down Expand Up @@ -153,6 +155,7 @@ const LoadStacks = (props: LoadFileFormatProps) => {
};

dispatch(updateNewMigrationData(newMigrationDataObj));
setIsStackLoading(false);
// call for Step Change
props.handleStepChange(props?.currentStep, true);

Expand Down Expand Up @@ -357,7 +360,7 @@ const LoadStacks = (props: LoadFileFormatProps) => {
</div>
</div>

{newMigrationData?.destination_stack?.selectedStack?.value && (
{newMigrationData?.destination_stack?.selectedStack?.value && (!isEmptyString(newMigrationData?.destination_stack?.selectedStack?.value) || !isStackLoading) &&(
<div className="language-mapper">
<div className="info-lang">
<div className="stackTitle language-title">Language Mapping</div>
Expand All @@ -375,7 +378,7 @@ const LoadStacks = (props: LoadFileFormatProps) => {
</div>
<LanguageMapper
uid={selectedStack?.uid ?? ''}
stack={selectedStack ?? DEFAULT_DROPDOWN} />
stack={newMigrationData?.destination_stack?.selectedStack ?? DEFAULT_DROPDOWN} />
</div>
)}
</div>
Expand Down
2 changes: 1 addition & 1 deletion ui/src/components/DestinationStack/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const DestinationStackComponent = ({
},[newMigrationData?.isprojectMapped]);

useEffect(()=>{
if(! isEmptyString(newMigrationData?.destination_stack?.selectedStack?.value )
if(!isEmptyString(newMigrationData?.destination_stack?.selectedStack?.value )
){
handleAllStepsComplete(true);
}
Expand Down
10 changes: 5 additions & 5 deletions ui/src/components/LegacyCms/Actions/LoadUploadFile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ interface UploadState {
fileFormat?: string;
isConfigLoading: boolean;
isLoading: boolean;
isValidated: boolean;
isValidated?: boolean;
isDisabled?: boolean;
processing: string;
progressPercentage: number;
Expand Down Expand Up @@ -190,7 +190,7 @@ const LoadUploadFile = (props: LoadUploadFileProps) => {
{
isLoading,
isConfigLoading,
isValidated,
//isValidated,
validationMessgae,
isDisabled,
cmsType,
Expand Down Expand Up @@ -290,7 +290,7 @@ const LoadUploadFile = (props: LoadUploadFileProps) => {
if (savedState) {
setIsLoading(savedState.isLoading);
setIsConfigLoading(savedState.isConfigLoading);
setIsValidated(savedState?.isValidated);
//setIsValidated(savedState?.isValidated);
setValidationMessage(savedState?.validationMessage);
//setIsDisabled(savedState?.isDisabled);
setCmsType(savedState.cmsType);
Expand All @@ -315,7 +315,7 @@ const LoadUploadFile = (props: LoadUploadFileProps) => {
{
isLoading,
isConfigLoading,
isValidated,
//isValidated,
validationMessgae,
//isDisabled,
cmsType,
Expand All @@ -331,7 +331,7 @@ const LoadUploadFile = (props: LoadUploadFileProps) => {
}, [
isLoading,
isConfigLoading,
isValidated,
//isValidated,
validationMessgae,
//isDisabled,
cmsType,
Expand Down
18 changes: 18 additions & 0 deletions ui/src/hooks/useWarnOnrefresh.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from "react";

export function useWarnOnRefresh(isUnsaved : boolean){
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
if (isUnsaved) {
e.preventDefault();
e.returnValue = '';
}
};

window.addEventListener('beforeunload', handleBeforeUnload);

return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [isUnsaved]);
}
31 changes: 30 additions & 1 deletion ui/src/pages/Migration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { cbModal, Notification } from '@contentstack/venus-components';
// Redux files
import { RootState } from '../../store';
import { updateMigrationData, updateNewMigrationData } from '../../store/slice/migrationDataSlice';
import { useWarnOnRefresh } from '../../hooks/useWarnOnrefresh';

// Services
import {
Expand Down Expand Up @@ -100,10 +101,38 @@ const Migration = () => {
const saveRef = useRef<ContentTypeSaveHandles>(null);
const newMigrationDataRef = useRef(newMigrationData);

const [isSaved, setIsSaved] = useState<boolean>(false);

useEffect(() => {
fetchData();
}, [params?.stepId, params?.projectId, selectedOrganisation?.value]);

useWarnOnRefresh(isSaved);

useEffect(()=>{
const hasNonEmptyMapping =
newMigrationData?.destination_stack?.localeMapping &&
Object.entries(newMigrationData?.destination_stack?.localeMapping || {})?.every(
([label, value]: [string, string]) =>
Boolean(label?.trim()) &&
value !== '' &&
value !== null &&
value !== undefined
);
if(legacyCMSRef?.current && !isCompleted && newMigrationData?.project_current_step === 1){
setIsSaved(true);
}
else if ((isCompleted && !isEmptyString(newMigrationData?.destination_stack?.selectedStack?.value) && newMigrationData?.project_current_step === 2)){
setIsSaved(true);
}
else if(newMigrationData?.content_mapping?.isDropDownChanged){
setIsSaved(true);
}
else{
setIsSaved(false);
}
},[isCompleted, newMigrationData])

/**
* Dispatches the isprojectMapped key to redux
*/
Expand Down Expand Up @@ -220,7 +249,7 @@ const Migration = () => {
const newMigrationDataObj = {
name: data?.localPath,
url: data?.localPath,
isValidated: data?.localPath !== newMigrationData?.legacy_cms?.uploadedFile?.file_details?.localPath ? false : newMigrationData?.legacy_cms?.uploadedFile?.isValidated,
isValidated: false,
file_details: {
isLocalPath: data?.isLocalPath,
cmsType: data?.cmsType,
Expand Down