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

Unify handling of loading state #2815

Merged
merged 3 commits into from
Feb 24, 2025
Merged
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
35 changes: 0 additions & 35 deletions src/ElectronBackend/main/__tests__/listeners.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//
// SPDX-License-Identifier: Apache-2.0
import { BrowserWindow, dialog, shell, WebContents } from 'electron';
import fs from 'fs';

import {
AllowedFrontendChannels,
Expand All @@ -16,10 +15,8 @@ import {
ExportSpdxDocumentYamlArgs,
ExportType,
} from '../../../shared/shared-types';
import { writeFile } from '../../../shared/write-file';
import { faker } from '../../../testing/Faker';
import * as errorHandling from '../../errorHandling/errorHandling';
import { loadInputAndOutputFromFilePath } from '../../input/importFromFile';
import { writeCsvToFile } from '../../output/writeCsvToFile';
import { writeSpdxFile } from '../../output/writeSpdxFile';
import { createWindow } from '../createWindow';
Expand All @@ -30,7 +27,6 @@ import {
} from '../dialogs';
import { setGlobalBackendState } from '../globalBackendState';
import {
deleteAndCreateNewAttributionFileListener,
exportFileListener,
importFileListener,
importFileSelectInputListener,
Expand Down Expand Up @@ -108,37 +104,6 @@ jest.mock('../dialogs', () => ({
selectBaseURLDialog: jest.fn(),
}));

describe('getDeleteAndCreateNewAttributionFileListener', () => {
it('deletes attribution file and calls loadInputAndOutputFromFilePath', async () => {
const mainWindow = {
webContents: {
send: jest.fn(),
},
setTitle: jest.fn(),
} as unknown as BrowserWindow;

const fileName = faker.string.uuid();
const resourceFilePath = `${fileName}.json`;
const jsonPath = await writeFile({
content: faker.string.sample(),
path: faker.outputPath(`${fileName}_attribution.json`),
});

setGlobalBackendState({
resourceFilePath,
attributionFilePath: jsonPath,
});

await deleteAndCreateNewAttributionFileListener(mainWindow, () => {})();

expect(fs.existsSync(jsonPath)).toBeFalsy();
expect(loadInputAndOutputFromFilePath).toHaveBeenCalledWith(
expect.anything(),
resourceFilePath,
);
});
});

describe('getSelectBaseURLListener', () => {
it('opens base url dialog and sends selected path to frontend', async () => {
const mockCallback = jest.fn();
Expand Down
50 changes: 12 additions & 38 deletions src/ElectronBackend/main/listeners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,14 @@ export async function handleOpeningFile(
filePath: string,
onOpen: () => void,
): Promise<void> {
setLoadingState(mainWindow.webContents, true);

logger.info('Initializing global backend state');
initializeGlobalBackendState(filePath, true);

await openFile(mainWindow, filePath, onOpen);

setLoadingState(mainWindow.webContents, false);
}

export const importFileListener =
Expand Down Expand Up @@ -175,6 +179,8 @@ export const importFileConvertAndLoadListener =
fileType: FileType,
opossumFilePath: string,
): Promise<boolean> => {
setLoadingState(mainWindow.webContents, true);

try {
if (!resourceFilePath.trim() || !fs.existsSync(resourceFilePath)) {
throw new Error('Input file does not exist');
Expand All @@ -198,12 +204,14 @@ export const importFileConvertAndLoadListener =
logger.info('Updating global backend state');
initializeGlobalBackendState(opossumFilePath, true);

await openFile(mainWindow, opossumFilePath, onOpen, true);
await openFile(mainWindow, opossumFilePath, onOpen);

return true;
} catch (error) {
sendListenerErrorToFrontend(mainWindow, error);
return false;
} finally {
setLoadingState(mainWindow.webContents, false);
}
};

Expand Down Expand Up @@ -234,29 +242,6 @@ function initializeGlobalBackendState(
setGlobalBackendState(newGlobalBackendState);
}

export const deleteAndCreateNewAttributionFileListener =
(mainWindow: BrowserWindow, onOpen: () => void) =>
async (): Promise<void> => {
try {
const globalBackendState = getGlobalBackendState();
const resourceFilePath = globalBackendState.resourceFilePath as string;

logger.info(
`Deleting attribution file and opening input file ${resourceFilePath}`,
);
if (globalBackendState.attributionFilePath) {
fs.unlinkSync(globalBackendState.attributionFilePath);
} else {
throw new Error(
`Failed to delete output file. Attribution file path is incorrect: ${globalBackendState.attributionFilePath}`,
);
}
await openFile(mainWindow, resourceFilePath, onOpen);
} catch (error) {
await showListenerErrorInMessageBox(mainWindow, error);
}
};

export const selectBaseURLListener =
(mainWindow: BrowserWindow) => async (): Promise<void> => {
try {
Expand All @@ -283,21 +268,10 @@ export async function openFile(
mainWindow: BrowserWindow,
filePath: string,
onOpen: () => void,
isImport?: boolean,
): Promise<void> {
if (!isImport) {
setLoadingState(mainWindow.webContents, true);
}

try {
await loadInputAndOutputFromFilePath(mainWindow, filePath);
setTitle(mainWindow, filePath);
onOpen();
} finally {
if (!isImport) {
setLoadingState(mainWindow.webContents, false);
}
}
await loadInputAndOutputFromFilePath(mainWindow, filePath);
setTitle(mainWindow, filePath);
onOpen();
}

function setTitle(mainWindow: BrowserWindow, filePath: string): void {
Expand Down
12 changes: 6 additions & 6 deletions src/ElectronBackend/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
import { dialog, ipcMain, Menu, systemPreferences } from 'electron';
import os from 'os';

import { IpcChannel } from '../../shared/ipc-channels';
import { AllowedFrontendChannels, IpcChannel } from '../../shared/ipc-channels';
import { getMessageBoxContentForErrorsWrapper } from '../errorHandling/errorHandling';
import { createWindow } from './createWindow';
import {
deleteAndCreateNewAttributionFileListener,
exportFileListener,
importFileConvertAndLoadListener,
importFileSelectInputListener,
Expand Down Expand Up @@ -81,11 +80,12 @@ export async function main(): Promise<void> {
importFileConvertAndLoadListener(mainWindow, activateMenuItems),
);
ipcMain.handle(IpcChannel.SaveFile, saveFileListener(mainWindow));
ipcMain.handle(
IpcChannel.DeleteFile,
deleteAndCreateNewAttributionFileListener(mainWindow, activateMenuItems),
);
ipcMain.handle(IpcChannel.ExportFile, exportFileListener(mainWindow));
ipcMain.handle(IpcChannel.StopLoading, () =>
mainWindow.webContents.send(AllowedFrontendChannels.FileLoading, {
isLoading: false,
}),
);
ipcMain.handle(IpcChannel.OpenLink, openLinkListener);
ipcMain.handle(IpcChannel.GetUserSettings, (_, key) =>
UserSettings.get(key),
Expand Down
21 changes: 18 additions & 3 deletions src/ElectronBackend/main/menu/fileMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import {
import { isFileLoaded } from '../../utils/getLoadedFile';
import { getGlobalBackendState } from '../globalBackendState';
import { getIconBasedOnTheme } from '../iconHelpers';
import { importFileListener, selectBaseURLListener } from '../listeners';
import {
importFileListener,
selectBaseURLListener,
setLoadingState,
} from '../listeners';
import logger from '../logger';
import { INITIALLY_DISABLED_ITEMS_INFO } from './initiallyDisabledMenuItems';

export const importFileFormats: Array<FileFormatInfo> = [
Expand Down Expand Up @@ -141,6 +146,8 @@ function getExportFollowUp(webContents: Electron.WebContents) {
'icons/follow-up-black.png',
),
click: () => {
setLoadingState(webContents, true);
logger.info('Preparing data for follow-up export');
webContents.send(
AllowedFrontendChannels.ExportFileRequest,
ExportType.FollowUp,
Expand All @@ -159,6 +166,8 @@ function getExportCompactBom(webContents: Electron.WebContents) {
),
label: INITIALLY_DISABLED_ITEMS_INFO.compactComponentList.label,
click: () => {
setLoadingState(webContents, true);
logger.info('Preparing data for compact component list export');
webContents.send(
AllowedFrontendChannels.ExportFileRequest,
ExportType.CompactBom,
Expand All @@ -177,6 +186,8 @@ function getExportDetailedBom(webContents: Electron.WebContents) {
),
label: INITIALLY_DISABLED_ITEMS_INFO.detailedComponentList.label,
click: () => {
setLoadingState(webContents, true);
logger.info('Preparing data for detailed component list export');
webContents.send(
AllowedFrontendChannels.ExportFileRequest,
ExportType.DetailedBom,
Expand All @@ -192,6 +203,8 @@ function getExportSpdxYaml(webContents: Electron.WebContents) {
icon: getIconBasedOnTheme('icons/yaml-white.png', 'icons/yaml-black.png'),
label: INITIALLY_DISABLED_ITEMS_INFO.spdxYAML.label,
click: () => {
setLoadingState(webContents, true);
logger.info('Preparing data for SPDX (yaml) export');
webContents.send(
AllowedFrontendChannels.ExportFileRequest,
ExportType.SpdxDocumentYaml,
Expand All @@ -202,11 +215,13 @@ function getExportSpdxYaml(webContents: Electron.WebContents) {
};
}

function getExportSpdsJson(webContents: Electron.WebContents) {
function getExportSpdxJson(webContents: Electron.WebContents) {
return {
icon: getIconBasedOnTheme('icons/json-white.png', 'icons/json-black.png'),
label: INITIALLY_DISABLED_ITEMS_INFO.spdxJSON.label,
click: () => {
setLoadingState(webContents, true);
logger.info('Preparing data for SPDX (json) export');
webContents.send(
AllowedFrontendChannels.ExportFileRequest,
ExportType.SpdxDocumentJson,
Expand All @@ -229,7 +244,7 @@ function getExportSubMenu(webContents: Electron.WebContents) {
getExportCompactBom(webContents),
getExportDetailedBom(webContents),
getExportSpdxYaml(webContents),
getExportSpdsJson(webContents),
getExportSpdxJson(webContents),
],
};
}
Expand Down
1 change: 1 addition & 0 deletions src/ElectronBackend/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const electronAPI: ElectronAPI = {
exportFile: (args) => ipcRenderer.invoke(IpcChannel.ExportFile, args),
saveFile: (saveFileArgs) =>
ipcRenderer.invoke(IpcChannel.SaveFile, saveFileArgs),
stopLoading: () => ipcRenderer.invoke(IpcChannel.StopLoading),
on: (channel, listener) => {
ipcRenderer.on(channel, listener);
return () => ipcRenderer.removeListener(channel, listener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,11 @@ import {
setBaseUrlsForSources,
} from '../../state/actions/resource-actions/all-views-simple-actions';
import { loadFromFile } from '../../state/actions/resource-actions/load-actions';
import {
openPopup,
setLoading,
} from '../../state/actions/view-actions/view-actions';
import { openPopup } from '../../state/actions/view-actions/view-actions';
import { useAppDispatch, useAppSelector } from '../../state/hooks';
import { getBaseUrlsForSources } from '../../state/selectors/resource-selectors';
import {
ExportFileRequestListener,
IsLoadingListener,
LoggingListener,
ShowImportDialogListener,
useIpcRenderer,
Expand Down Expand Up @@ -99,14 +95,6 @@ export const BackendCommunication: React.FC = () => {
);
}
}

useIpcRenderer<IsLoadingListener>(
AllowedFrontendChannels.FileLoading,
(_, { isLoading }) => {
dispatch(setLoading(isLoading));
},
[dispatch],
);
useIpcRenderer(AllowedFrontendChannels.FileLoaded, fileLoadedListener, [
dispatch,
]);
Expand Down
18 changes: 12 additions & 6 deletions src/Frontend/Components/ImportDialog/ImportDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ import { text } from '../../../shared/text';
import { getDotOpossumFilePath } from '../../../shared/write-file';
import { closePopup } from '../../state/actions/view-actions/view-actions';
import { useAppDispatch } from '../../state/hooks';
import { LoggingListener, useIpcRenderer } from '../../util/use-ipc-renderer';
import {
IsLoadingListener,
LoggingListener,
useIpcRenderer,
} from '../../util/use-ipc-renderer';
import { FilePathInput } from '../FilePathInput/FilePathInput';
import { LogDisplay } from '../LogDisplay/LogDisplay';
import { NotificationPopup } from '../NotificationPopup/NotificationPopup';
Expand All @@ -27,7 +31,13 @@ export const ImportDialog: React.FC<ImportDialogProps> = ({ fileFormat }) => {
const [inputFilePath, setInputFilePath] = useState<string>('');
const [opossumFilePath, setOpossumFilePath] = useState<string>('');

const [isLoading, setIsLoading] = useState<boolean>(false);
const [isLoading, setIsLoading] = useState(false);

useIpcRenderer<IsLoadingListener>(
AllowedFrontendChannels.FileLoading,
(_, { isLoading }) => setIsLoading(isLoading),
[],
);

const [logToDisplay, setLogToDisplay] = useState<Log | null>(null);

Expand Down Expand Up @@ -82,8 +92,6 @@ export const ImportDialog: React.FC<ImportDialogProps> = ({ fileFormat }) => {
}

async function onConfirm(): Promise<void> {
setIsLoading(true);

const success = await window.electronAPI.importFileConvertAndLoad(
inputFilePath,
fileFormat.fileType,
Expand All @@ -93,8 +101,6 @@ export const ImportDialog: React.FC<ImportDialogProps> = ({ fileFormat }) => {
if (success) {
dispatch(closePopup());
}

setIsLoading(false);
}

return (
Expand Down
Loading
Loading