diff --git a/__tests__/__main__/user-preferences.mjs b/__tests__/__main__/user-preferences.mjs index 2765156f..2ac92927 100644 --- a/__tests__/__main__/user-preferences.mjs +++ b/__tests__/__main__/user-preferences.mjs @@ -11,7 +11,6 @@ import { getPreferencesFilePath, getUserLanguage, getUserPreferences, - getUserPreferencesPromise, notificationIsEnabled, repetitionIsEnabled, resetPreferences, @@ -29,14 +28,6 @@ function setNewPreference(preference, value) savePreferences(preferences); } -function mockGetPreferencesFilePathPromise(path) -{ - return new Promise((resolve) => - { - resolve(path); - }); -} - describe('Preferences Main', () => { // Remove preferences file to guarantee equal execution of tests @@ -443,34 +434,6 @@ describe('Preferences Main', () => } }); - describe('getUserPreferencesPromise()', () => - { - before(() => - { - fs.writeFileSync('./dummy_file.txt', 'This should be tried to be parsed and fail'); - }); - - it('Should return a promise', () => - { - assert.strictEqual(getUserPreferencesPromise() instanceof Promise, true); - }); - - it('Should resolve promise to empty if file is broken', async() => - { - assert.deepStrictEqual(await getUserPreferencesPromise(mockGetPreferencesFilePathPromise('./')), {}); - }); - - it('Should resolve promise to default preferences if file is unparseable', async() => - { - assert.deepStrictEqual(await getUserPreferencesPromise(mockGetPreferencesFilePathPromise('./dummy_file.txt')), getDefaultPreferences()); - }); - - after(() => - { - fs.unlinkSync('./dummy_file.txt', () => {}); - }); - }); - describe('App config languages', () => { it('getLanguageMap() should have language code keys', () => diff --git a/__tests__/__renderer__/classes/BaseCalendar.mjs b/__tests__/__renderer__/classes/BaseCalendar.mjs index 442cac5f..8ffd78f0 100644 --- a/__tests__/__renderer__/classes/BaseCalendar.mjs +++ b/__tests__/__renderer__/classes/BaseCalendar.mjs @@ -12,6 +12,7 @@ import { getUserPreferences, resetPreferences, savePreferences, + showDay, switchCalendarView } from '../../../js/user-preferences.mjs'; import TimeBalance from '../../../js/time-balance.mjs'; @@ -45,33 +46,34 @@ describe('BaseCalendar.js', () => ExtendedClass.prototype._getTargetDayForAllTimeBalance = () => {}; // Mocked APIs from the preload script of the calendar window - window.mainApi = calendarApi; + window.calendarApi = calendarApi; + window.rendererApi = {}; - window.mainApi.computeAllTimeBalanceUntilPromise = (targetDate) => + window.calendarApi.computeAllTimeBalanceUntilPromise = (targetDate) => { return TimeBalance.computeAllTimeBalanceUntilAsync(targetDate); }; - window.mainApi.switchView = () => + window.calendarApi.switchView = () => { switchCalendarView(); }; - window.mainApi.getStoreContents = () => + window.calendarApi.getStoreContents = () => { return new Promise((resolve) => { resolve(calendarStore.store); }); }; - window.mainApi.getWaiverStoreContents = () => + window.rendererApi.getWaiverStoreContents = () => { return new Promise((resolve) => { resolve(waivedWorkdays.store); }); }; - window.mainApi.setStoreData = (key, contents) => + window.calendarApi.setStoreData = (key, contents) => { calendarStore.set(key, contents); return new Promise((resolve) => @@ -79,6 +81,7 @@ describe('BaseCalendar.js', () => resolve(true); }); }; + window.rendererApi.showDay = showDay; }); describe('constructor', () => diff --git a/__tests__/__renderer__/classes/CalendarFactory.mjs b/__tests__/__renderer__/classes/CalendarFactory.mjs index 19d3a0f7..96a63b31 100644 --- a/__tests__/__renderer__/classes/CalendarFactory.mjs +++ b/__tests__/__renderer__/classes/CalendarFactory.mjs @@ -18,9 +18,9 @@ describe('CalendarFactory', () => before(() => { // Mocked APIs from the preload script of the calendar window - window.mainApi = calendarApi; + window.calendarApi = calendarApi; - window.mainApi.resizeMainWindow = stub(); + window.calendarApi.resizeMainWindow = stub(); Object.setPrototypeOf(DayCalendar, stub()); Object.setPrototypeOf(MonthCalendar, stub()); @@ -61,7 +61,7 @@ describe('CalendarFactory', () => it('Should return new calendar with resizing if passing in an instance that is not a DayCalendar', async() => { - window.mainApi.resizeMainWindow.resetHistory(); + window.calendarApi.resizeMainWindow.resetHistory(); let calls = 0; const testCalendar = { constructor: { @@ -76,17 +76,17 @@ describe('CalendarFactory', () => }, {}, testCalendar); assert.strictEqual(calendar instanceof DayCalendar, true); assert.strictEqual(calls, 0); - assert.strictEqual(window.mainApi.resizeMainWindow.calledOnce, true); + assert.strictEqual(window.calendarApi.resizeMainWindow.calledOnce, true); }); it('Should return new calendar without resizing if passing in an undefined instance', async() => { - window.mainApi.resizeMainWindow.resetHistory(); + window.calendarApi.resizeMainWindow.resetHistory(); const calendar = await CalendarFactory.getInstance({ view: 'day', }, {}, undefined); assert.strictEqual(calendar instanceof DayCalendar, true); - assert.strictEqual(window.mainApi.resizeMainWindow.notCalled, true); + assert.strictEqual(window.calendarApi.resizeMainWindow.notCalled, true); }); }); @@ -112,17 +112,17 @@ describe('CalendarFactory', () => it('Should return new calendar without resizing if passing in an undefined instance', async() => { - window.mainApi.resizeMainWindow.resetHistory(); + window.calendarApi.resizeMainWindow.resetHistory(); const calendar = await CalendarFactory.getInstance({ view: 'month', }, {}, undefined); assert.strictEqual(calendar instanceof MonthCalendar, true); - assert.strictEqual(window.mainApi.resizeMainWindow.notCalled, true); + assert.strictEqual(window.calendarApi.resizeMainWindow.notCalled, true); }); it('Should return new calendar with resizing if passing in an instance that is not a MonthCalendar', async() => { - window.mainApi.resizeMainWindow.resetHistory(); + window.calendarApi.resizeMainWindow.resetHistory(); let calls = 0; const testCalendar = { constructor: { @@ -137,7 +137,7 @@ describe('CalendarFactory', () => }, {}, testCalendar); assert.strictEqual(calendar instanceof MonthCalendar, true); assert.strictEqual(calls, 0); - assert.strictEqual(window.mainApi.resizeMainWindow.calledOnce, true); + assert.strictEqual(window.calendarApi.resizeMainWindow.calledOnce, true); }); }); diff --git a/__tests__/__renderer__/classes/DayCalendar.mjs b/__tests__/__renderer__/classes/DayCalendar.mjs index 379a3888..bd374713 100644 --- a/__tests__/__renderer__/classes/DayCalendar.mjs +++ b/__tests__/__renderer__/classes/DayCalendar.mjs @@ -46,17 +46,18 @@ describe('DayCalendar class Tests', () => waivedWorkdays.set(waivedEntries); // APIs from the preload script of the calendar window - window.mainApi = calendarApi; + window.calendarApi = calendarApi; + window.rendererApi = {}; // Stubbing methods that don't need the actual implementation for the tests - window.mainApi.toggleTrayPunchTime = () => {}; - window.mainApi.resizeMainWindow = () => {}; + window.calendarApi.toggleTrayPunchTime = () => {}; + window.calendarApi.resizeMainWindow = () => {}; BaseCalendar.prototype._getTranslation = () => {}; BaseCalendar.prototype.redraw = () => {}; - window.mainApi.getStoreContents = () => { return new Promise((resolve) => { resolve(entryStore.store); }); }; - window.mainApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waivedWorkdays.store)); }; - window.mainApi.setStoreData = (key, contents) => + window.calendarApi.getStoreContents = () => { return new Promise((resolve) => { resolve(entryStore.store); }); }; + window.rendererApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waivedWorkdays.store)); }; + window.calendarApi.setStoreData = (key, contents) => { return new Promise((resolve) => { @@ -64,7 +65,7 @@ describe('DayCalendar class Tests', () => resolve(true); }); }; - window.mainApi.deleteStoreData = (key) => + window.calendarApi.deleteStoreData = (key) => { return new Promise((resolve) => { @@ -72,7 +73,7 @@ describe('DayCalendar class Tests', () => resolve(true); }); }; - window.mainApi.computeAllTimeBalanceUntilPromise = (targetDate) => + window.calendarApi.computeAllTimeBalanceUntilPromise = (targetDate) => { return new Promise((resolve) => { diff --git a/__tests__/__renderer__/classes/MonthCalendar.mjs b/__tests__/__renderer__/classes/MonthCalendar.mjs index 9e9a0813..4f071272 100644 --- a/__tests__/__renderer__/classes/MonthCalendar.mjs +++ b/__tests__/__renderer__/classes/MonthCalendar.mjs @@ -46,16 +46,17 @@ describe('MonthCalendar class Tests', () => waivedWorkdays.set(waivedEntries); // APIs from the preload script of the calendar window - window.mainApi = calendarApi; + window.calendarApi = calendarApi; + window.rendererApi = {}; // Stubbing methods that don't need the actual implementation for the tests - // window.mainApi.toggleTrayPunchTime = () => {}; - window.mainApi.resizeMainWindow = () => {}; + // window.calendarApi.toggleTrayPunchTime = () => {}; + window.calendarApi.resizeMainWindow = () => {}; BaseCalendar.prototype._getTranslation = () => {}; BaseCalendar.prototype.redraw = () => {}; - window.mainApi.getStoreContents = () => { return new Promise((resolve) => { resolve(entryStore.store); }); }; - window.mainApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waivedWorkdays.store)); }; - window.mainApi.setStoreData = (key, contents) => + window.calendarApi.getStoreContents = () => { return new Promise((resolve) => { resolve(entryStore.store); }); }; + window.rendererApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waivedWorkdays.store)); }; + window.calendarApi.setStoreData = (key, contents) => { return new Promise((resolve) => { @@ -63,7 +64,7 @@ describe('MonthCalendar class Tests', () => resolve(true); }); }; - window.mainApi.deleteStoreData = (key) => + window.calendarApi.deleteStoreData = (key) => { return new Promise((resolve) => { @@ -71,7 +72,7 @@ describe('MonthCalendar class Tests', () => resolve(true); }); }; - window.mainApi.computeAllTimeBalanceUntilPromise = (targetDate) => + window.calendarApi.computeAllTimeBalanceUntilPromise = (targetDate) => { return new Promise((resolve) => { diff --git a/__tests__/__renderer__/preferences.mjs b/__tests__/__renderer__/preferences.mjs index 576788c2..f851c7ba 100644 --- a/__tests__/__renderer__/preferences.mjs +++ b/__tests__/__renderer__/preferences.mjs @@ -12,7 +12,6 @@ import { rootDir } from '../../js/app-config.mjs'; import { getDefaultPreferences, getPreferencesFilePath, - getUserPreferences, savePreferences, } from '../../js/user-preferences.mjs'; import { preferencesApi } from '../../renderer/preload-scripts/preferences-api.mjs'; @@ -83,7 +82,6 @@ const testPreferences = Object.assign({}, getDefaultPreferences()); let convertTimeFormat; let listenerLanguage; let populateLanguages; -let refreshContent; let renderPreferencesWindow; let setupListeners; let resetContent; @@ -95,22 +93,23 @@ describe('Test Preferences Window', () => stub(i18nTranslator, 'getTranslationInLanguageData').returnsThis(); // APIs from the preload script of the preferences window - window.mainApi = preferencesApi; + window.preferencesApi = preferencesApi; - // Mocking with the actual access that main would have - window.mainApi.getUserPreferencesPromise = () => { return new Promise((resolve) => resolve(getUserPreferences())); }; + // Mocking with the actual value + window.rendererApi = { + getLanguageDataPromise: () => + { + return new Promise((resolve) => resolve({ + 'language': 'en', + 'data': {} + })); + }, + getOriginalUserPreferences: () => { return testPreferences; }, + showDialogSync: () => { return new Promise((resolve) => resolve({ response: 0 })); } + }; // Stub methods - window.mainApi.notifyNewPreferences = () => {}; - window.mainApi.showDialogSync = () => { return new Promise((resolve) => resolve({ response: 0 })); }; - - window.mainApi.getLanguageDataPromise = () => - { - return new Promise((resolve) => resolve({ - 'language': 'en', - 'data': {} - })); - }; + window.preferencesApi.notifyNewPreferences = () => {}; resetPreferenceFile(); @@ -120,7 +119,6 @@ describe('Test Preferences Window', () => convertTimeFormat = file.convertTimeFormat; listenerLanguage = file.listenerLanguage; populateLanguages = file.populateLanguages; - refreshContent = file.refreshContent; renderPreferencesWindow = file.renderPreferencesWindow; setupListeners = file.setupListeners; resetContent = file.resetContent; @@ -131,7 +129,6 @@ describe('Test Preferences Window', () => beforeEach(async function() { await prepareMockup(); - await refreshContent(); renderPreferencesWindow(); populateLanguages(); listenerLanguage(); diff --git a/__tests__/__renderer__/workday-waiver.mjs b/__tests__/__renderer__/workday-waiver.mjs index 6b9b69f2..9efaf804 100644 --- a/__tests__/__renderer__/workday-waiver.mjs +++ b/__tests__/__renderer__/workday-waiver.mjs @@ -1,4 +1,3 @@ -/* eslint-disable no-undef */ 'use strict'; import '../../__mocks__/jquery.mjs'; @@ -20,18 +19,16 @@ import { } from '../../main/workday-waiver-aux.mjs'; import { getDefaultPreferences, - getUserPreferencesPromise, + getUserPreferences, savePreferences, + showDay, } from '../../js/user-preferences.mjs'; import i18nTranslator from '../../renderer/i18n-translator.js'; - const waiverStore = new Store({name: 'waived-workdays'}); const document = window.document; -const languageData = {'language': 'en', 'data': {'dummy_string': 'dummy_string_translated'}}; - let htmlDoc = undefined; // Functions from workday-waiver.js that will be imported dynamically @@ -53,7 +50,6 @@ let clearHolidayTable; let clearWaiverList; let loadHolidaysTable; let initializeHolidayInfo; -let refreshDataForTest; async function prepareMockup() { @@ -65,7 +61,6 @@ async function prepareMockup() } window.document.documentElement.innerHTML = htmlDoc.window.document.documentElement.innerHTML; await populateList(); - refreshDataForTest(languageData); } async function addTestWaiver(day, reason) @@ -78,7 +73,7 @@ async function addTestWaiver(day, reason) async function testWaiverCount(expected) { - const waivedWorkdays = await window.mainApi.getWaiverStoreContents(); + const waivedWorkdays = await window.rendererApi.getWaiverStoreContents(); assert.strictEqual(waivedWorkdays.size, expected); assert.strictEqual($('#waiver-list-table tbody')[0].rows.length, expected); } @@ -111,14 +106,14 @@ describe('Test Workday Waiver Window', function() clearWaiverList = file.clearWaiverList; loadHolidaysTable = file.loadHolidaysTable; initializeHolidayInfo = file.initializeHolidayInfo; - refreshDataForTest = file.refreshDataForTest; // APIs from the preload script of the workday waiver window - global.window.mainApi = workdayWaiverApi; + window.workdayWaiverApi = workdayWaiverApi; + window.rendererApi = {}; // Mocking with the actual access to store that main would have - window.mainApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waiverStore.store)); }; - window.mainApi.setWaiver = (key, contents) => + window.rendererApi.getWaiverStoreContents = () => { return new Promise((resolve) => resolve(waiverStore.store)); }; + window.workdayWaiverApi.setWaiver = (key, contents) => { return new Promise((resolve) => { @@ -126,8 +121,8 @@ describe('Test Workday Waiver Window', function() resolve(true); }); }; - window.mainApi.hasWaiver = (key) => { return new Promise((resolve) => resolve(waiverStore.has(key))); }; - window.mainApi.deleteWaiver = (key) => + window.workdayWaiverApi.hasWaiver = (key) => { return new Promise((resolve) => resolve(waiverStore.has(key))); }; + window.workdayWaiverApi.deleteWaiver = (key) => { return new Promise((resolve) => { @@ -135,8 +130,15 @@ describe('Test Workday Waiver Window', function() resolve(true); }); }; + window.workdayWaiverApi.getWaiverDay = () => + { + return new Promise((resolve) => + { + resolve(global.waiverDay); + }); + }; - window.mainApi.getHolidays = (country, state, city, year) => + window.workdayWaiverApi.getHolidays = (country, state, city, year) => { return new Promise((resolve) => { @@ -144,7 +146,7 @@ describe('Test Workday Waiver Window', function() }); }; - window.mainApi.getCountries = () => + window.workdayWaiverApi.getCountries = () => { return new Promise((resolve) => { @@ -152,7 +154,7 @@ describe('Test Workday Waiver Window', function() }); }; - window.mainApi.getStates = (country) => + window.workdayWaiverApi.getStates = (country) => { return new Promise((resolve) => { @@ -160,7 +162,7 @@ describe('Test Workday Waiver Window', function() }); }; - window.mainApi.getRegions = (country, state) => + window.workdayWaiverApi.getRegions = (country, state) => { return new Promise((resolve) => { @@ -168,25 +170,27 @@ describe('Test Workday Waiver Window', function() }); }; - window.mainApi.showDialogSync = () => + window.rendererApi.getLanguageDataPromise = () => + { + return new Promise((resolve) => resolve({ + 'language': 'en', + 'data': {} + })); + }; + window.rendererApi.showDialogSync = () => { return new Promise((resolve) => { resolve({ response: 0 }); }); }; - - window.mainApi.getUserPreferences = () => + window.rendererApi.getOriginalUserPreferences = () => { - const preferencesFilePathPromise = new Promise((resolve) => - { - const userDataPath = app.getPath('userData'); - resolve(path.join(userDataPath, 'preferences.json')); - }); - return getUserPreferencesPromise(preferencesFilePathPromise); + return getUserPreferences(); }; + window.rendererApi.showDay = showDay; - window.mainApi.showAlert = () => {}; + window.workdayWaiverApi.showAlert = () => {}; // Making sure the preferences are the default so the tests work as expected savePreferences(getDefaultPreferences()); diff --git a/js/main-window.mjs b/js/main-window.mjs index 26de5abd..b8da6519 100644 --- a/js/main-window.mjs +++ b/js/main-window.mjs @@ -70,6 +70,7 @@ function createWindow() { // Create the browser window. const widthHeight = getDefaultWidthHeight(); + const userPreferences = getUserPreferences(); mainWindow = new BrowserWindow({ width: widthHeight.width, height: widthHeight.height, @@ -82,7 +83,10 @@ function createWindow() webPreferences: { nodeIntegration: true, preload: path.join(rootDir, '/renderer/preload-scripts/calendar-bridge.mjs'), - contextIsolation: true + contextIsolation: true, + additionalArguments: [ + `--preferences=${JSON.stringify(userPreferences)}`, + ], } }); diff --git a/js/menus.mjs b/js/menus.mjs index a5f439c9..4f5fb405 100644 --- a/js/menus.mjs +++ b/js/menus.mjs @@ -10,7 +10,7 @@ import ImportExport from './import-export.mjs'; import Notification from './notification.mjs'; import { getSavedPreferences } from './saved-preferences.mjs'; import UpdateManager from './update-manager.mjs'; -import { savePreferences } from './user-preferences.mjs'; +import { getUserPreferences, savePreferences } from './user-preferences.mjs'; import Windows from './windows.mjs'; import i18NextConfig from '../src/configs/i18next.config.mjs'; @@ -130,6 +130,7 @@ function getEditMenuTemplate(mainWindow) const htmlPath = path.join('file://', rootDir, 'src/preferences.html'); const dialogCoordinates = Windows.getDialogCoordinates(550, 620, mainWindow); + const userPreferences = getUserPreferences(); global.prefWindow = new BrowserWindow({ width: 550, height: 620, minWidth: 480, @@ -141,7 +142,10 @@ function getEditMenuTemplate(mainWindow) webPreferences: { nodeIntegration: true, preload: path.join(rootDir, '/renderer/preload-scripts/preferences-bridge.mjs'), - contextIsolation: true + contextIsolation: true, + additionalArguments: [ + `--preferences=${JSON.stringify(userPreferences)}`, + ], } }); global.prefWindow.setMenu(null); global.prefWindow.loadURL(htmlPath); diff --git a/js/user-preferences.mjs b/js/user-preferences.mjs index d571897f..9de4497b 100644 --- a/js/user-preferences.mjs +++ b/js/user-preferences.mjs @@ -3,8 +3,6 @@ import { createRequire } from 'module'; const require = createRequire(import.meta.url); -const { ipcRenderer } = require('electron'); - import TimeMath from './time-math.mjs'; import { isValidTheme } from '../renderer/themes.js'; import { getLanguagesCodes } from '../src/configs/app.config.mjs'; @@ -91,22 +89,10 @@ function getPreferencesFilePath() { const path = require('path'); const electron = require('electron'); - const userDataPath = (electron.app || require('@electron/remote').app).getPath('userData'); + const userDataPath = electron.app.getPath('userData'); return path.join(userDataPath, 'preferences.json'); } -function getPreferencesFilePathPromise() -{ - return new Promise((resolve) => - { - ipcRenderer.invoke('USER_DATA_PATH').then(userDataPath => - { - const path = require('path'); - resolve(path.join(userDataPath, 'preferences.json')); - }); - }); -} - /* * Saves preferences to file, returns an error on failure. */ @@ -235,23 +221,6 @@ function getLoadedOrDerivedUserPreferences() return readPreferences(); } -/** - * Returns a promise to the user preferences. - * @param preferencesFilePathPromise Optionally allows one to pass in a promise that resolves to the preferences file path - * @return {Promise} - */ -function getUserPreferencesPromise(preferencesFilePathPromise = getPreferencesFilePathPromise()) -{ - return new Promise((resolve) => - { - preferencesFilePathPromise.then((filePath) => - { - initPreferencesFileIfNotExistsOrInvalid(filePath); - resolve(readPreferences(filePath)); - }); - }); -} - /** * Returns the default user preferences. */ @@ -372,7 +341,6 @@ export { getNotificationsInterval, getPreferencesFilePath, getUserLanguage, - getUserPreferencesPromise, getDefaultPreferences, isNotBoolean, isNotificationInterval, diff --git a/js/windows.mjs b/js/windows.mjs index e00580e5..9762aa89 100644 --- a/js/windows.mjs +++ b/js/windows.mjs @@ -5,6 +5,7 @@ import path from 'path'; import { appConfig, rootDir } from './app-config.mjs'; import { getDateStr } from './date-aux.mjs'; +import { getUserPreferences } from './user-preferences.mjs'; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. @@ -30,6 +31,7 @@ class Windows } const htmlPath = path.join('file://', rootDir, '/src/workday-waiver.html'); const dialogCoordinates = Windows.getDialogCoordinates(600, 500, mainWindow); + const userPreferences = getUserPreferences(); global.waiverWindow = new BrowserWindow({ width: 600, height: 500, x: dialogCoordinates.x, @@ -40,7 +42,10 @@ class Windows webPreferences: { nodeIntegration: true, preload: path.join(rootDir, '/renderer/preload-scripts/workday-waiver-bridge.mjs'), - contextIsolation: true + contextIsolation: true, + additionalArguments: [ + `--preferences=${JSON.stringify(userPreferences)}`, + ], } }); global.waiverWindow.setMenu(null); global.waiverWindow.loadURL(htmlPath); diff --git a/renderer/classes/BaseCalendar.js b/renderer/classes/BaseCalendar.js index 8145b4a4..7330c090 100644 --- a/renderer/classes/BaseCalendar.js +++ b/renderer/classes/BaseCalendar.js @@ -62,7 +62,7 @@ class BaseCalendar _updateAllTimeBalance() { const targetDate = this._getTargetDayForAllTimeBalance(); - window.mainApi.computeAllTimeBalanceUntilPromise(targetDate) + window.calendarApi.computeAllTimeBalanceUntilPromise(targetDate) .then(balance => { const balanceElement = $('#overall-balance'); @@ -391,7 +391,7 @@ class BaseCalendar { this._internalStore = {}; - const calendarStore = await window.mainApi.getStoreContents(); + const calendarStore = await window.calendarApi.getStoreContents(); for (const entry of Object.entries(calendarStore)) { const key = entry[0]; @@ -408,7 +408,7 @@ class BaseCalendar { this._internalWaiverStore = {}; - const waivedWorkdays = await window.mainApi.getWaiverStoreContents(); + const waivedWorkdays = await window.rendererApi.getWaiverStoreContents(); for (const entry of Object.entries(waivedWorkdays)) { const date = entry[0]; @@ -436,7 +436,7 @@ class BaseCalendar _setStore(key, newValues) { this._internalStore[key] = { values: newValues }; - window.mainApi.setStoreData(key, this._internalStore[key]); + window.calendarApi.setStoreData(key, this._internalStore[key]); } /* @@ -445,7 +445,7 @@ class BaseCalendar _removeStore(key) { this._internalStore[key] = undefined; - window.mainApi.deleteStoreData(key); + window.calendarApi.deleteStoreData(key); } /** @@ -457,7 +457,7 @@ class BaseCalendar */ _showDay(year, month, day) { - return window.mainApi.showDay(year, month, day, this._preferences); + return window.rendererApi.showDay(year, month, day, this._preferences); } /** @@ -703,7 +703,7 @@ class BaseCalendar _togglePunchButton(enable) { $('#punch-button').prop('disabled', !enable); - window.mainApi.toggleTrayPunchTime(enable); + window.calendarApi.toggleTrayPunchTime(enable); } /** @@ -711,7 +711,7 @@ class BaseCalendar */ _switchView() { - window.mainApi.switchView(); + window.calendarApi.switchView(); } } diff --git a/renderer/classes/CalendarFactory.js b/renderer/classes/CalendarFactory.js index c6d8893a..c9f04009 100644 --- a/renderer/classes/CalendarFactory.js +++ b/renderer/classes/CalendarFactory.js @@ -19,7 +19,7 @@ class CalendarFactory { if (calendar !== undefined && calendar.constructor.name !== constructorName) { - window.mainApi.resizeMainWindow(); + window.calendarApi.resizeMainWindow(); } calendar = new CalendarClass(preferences, languageData); await calendar.reload(); diff --git a/renderer/classes/DayCalendar.js b/renderer/classes/DayCalendar.js index f3d082b9..89578b2c 100644 --- a/renderer/classes/DayCalendar.js +++ b/renderer/classes/DayCalendar.js @@ -321,7 +321,7 @@ class DayCalendar extends BaseCalendar const len = getInputs.length; if (getInputs.get(len-1).value !== '' || getInputs.get(len-2).value !== '') { - window.mainApi.showDialogSync(removeEntriesDialogOptions).then((result) => + window.rendererApi.showDialogSync(removeEntriesDialogOptions).then((result) => { const buttonId = result.response; if (buttonId === 1) diff --git a/renderer/classes/MonthCalendar.js b/renderer/classes/MonthCalendar.js index 2ae3ecb7..68f4c11f 100644 --- a/renderer/classes/MonthCalendar.js +++ b/renderer/classes/MonthCalendar.js @@ -412,7 +412,7 @@ class MonthCalendar extends BaseCalendar const len = getInputs.length; if (getInputs.get(len-1).value !== '' || getInputs.get(len-2).value !== '') { - window.mainApi.showDialogSync(removeEntriesDialogOptions).then((result) => + window.rendererApi.showDialogSync(removeEntriesDialogOptions).then((result) => { const buttonId = result.response; if (buttonId === 1) diff --git a/renderer/preload-scripts/calendar-api.mjs b/renderer/preload-scripts/calendar-api.mjs index 495f8466..dc1bdefc 100644 --- a/renderer/preload-scripts/calendar-api.mjs +++ b/renderer/preload-scripts/calendar-api.mjs @@ -5,14 +5,6 @@ const require = createRequire(import.meta.url); const { ipcRenderer } = require('electron'); -import * as config from '../../src/configs/app.config.mjs'; -import { getUserPreferencesPromise, showDay } from '../../js/user-preferences.mjs'; - -function getLanguageDataPromise() -{ - return ipcRenderer.invoke('GET_LANGUAGE_DATA'); -} - function resizeMainWindow() { ipcRenderer.send('RESIZE_MAIN_WINDOW'); @@ -28,26 +20,11 @@ function toggleTrayPunchTime(enable) ipcRenderer.send('TOGGLE_TRAY_PUNCH_TIME', enable); } -function showDayByPreferences(year, month, day, preferences) -{ - return showDay(year, month, day, preferences); -} - function displayWaiverWindow(waiverDay) { ipcRenderer.send('SET_WAIVER_DAY', waiverDay); } -function showDialogSync(dialogOptions) -{ - return ipcRenderer.invoke('SHOW_DIALOG', dialogOptions); -} - -function getWaiverStoreContents() -{ - return ipcRenderer.invoke('GET_WAIVER_STORE_CONTENTS'); -} - function getStoreContents() { return ipcRenderer.invoke('GET_STORE_CONTENTS'); @@ -69,9 +46,6 @@ function computeAllTimeBalanceUntilPromise(targetDate) } const calendarApi = { - getLanguageMap: () => config.getLanguageMap(), - getUserPreferencesPromise: () => getUserPreferencesPromise(), - getLanguageDataPromise: () => getLanguageDataPromise(), handleRefreshOnDayChange: (callback) => ipcRenderer.on('REFRESH_ON_DAY_CHANGE', callback), handlePreferencesSaved: (callback) => ipcRenderer.on('PREFERENCES_SAVED', callback), handleWaiverSaved: (callback) => ipcRenderer.on('WAIVER_SAVED', callback), @@ -82,10 +56,7 @@ const calendarApi = { resizeMainWindow: () => resizeMainWindow(), switchView: () => switchView(), toggleTrayPunchTime: (enable) => toggleTrayPunchTime(enable), - showDay: (year, month, day, userPreferences) => showDayByPreferences(year, month, day, userPreferences), displayWaiverWindow: (waiverDay) => displayWaiverWindow(waiverDay), - showDialogSync: (dialogOptions) => showDialogSync(dialogOptions), - getWaiverStoreContents: () => getWaiverStoreContents(), getStoreContents: () => getStoreContents(), setStoreData: (key, contents) => setStoreData(key, contents), deleteStoreData: (key) => deleteStoreData(key), diff --git a/renderer/preload-scripts/calendar-bridge.mjs b/renderer/preload-scripts/calendar-bridge.mjs index 9f3e88fc..752e1617 100644 --- a/renderer/preload-scripts/calendar-bridge.mjs +++ b/renderer/preload-scripts/calendar-bridge.mjs @@ -2,7 +2,12 @@ import { contextBridge } from 'electron'; import { calendarApi } from './calendar-api.mjs'; +import { rendererApi } from './renderer-api.mjs'; contextBridge.exposeInMainWorld( - 'mainApi', calendarApi + 'calendarApi', calendarApi +); + +contextBridge.exposeInMainWorld( + 'rendererApi', rendererApi ); diff --git a/renderer/preload-scripts/preferences-api.mjs b/renderer/preload-scripts/preferences-api.mjs index 2a49f1a7..a5d9056b 100644 --- a/renderer/preload-scripts/preferences-api.mjs +++ b/renderer/preload-scripts/preferences-api.mjs @@ -6,7 +6,7 @@ const require = createRequire(import.meta.url); const { ipcRenderer } = require('electron'); import * as config from '../../src/configs/app.config.mjs'; -import { getUserPreferencesPromise, getDefaultPreferences } from '../../js/user-preferences.mjs'; +import { getDefaultPreferences } from '../../js/user-preferences.mjs'; function notifyNewPreferences(preferences) { @@ -18,24 +18,11 @@ function changeLanguagePromise(language) return ipcRenderer.invoke('CHANGE_LANGUAGE', language); } -function getLanguageDataPromise() -{ - return ipcRenderer.invoke('GET_LANGUAGE_DATA'); -} - -function showDialogSync(dialogOptions) -{ - return ipcRenderer.invoke('SHOW_DIALOG', dialogOptions); -} - const preferencesApi = { notifyNewPreferences: (preferences) => notifyNewPreferences(preferences), getLanguageMap: () => config.getLanguageMap(), - getUserPreferencesPromise: () => getUserPreferencesPromise(), getDefaultPreferences: () => getDefaultPreferences(), - changeLanguagePromise: (language) => changeLanguagePromise(language), - getLanguageDataPromise: () => getLanguageDataPromise(), - showDialogSync: (dialogOptions) => showDialogSync(dialogOptions) + changeLanguagePromise: (language) => changeLanguagePromise(language) }; export { diff --git a/renderer/preload-scripts/preferences-bridge.mjs b/renderer/preload-scripts/preferences-bridge.mjs index 85c56020..d79eb8a2 100644 --- a/renderer/preload-scripts/preferences-bridge.mjs +++ b/renderer/preload-scripts/preferences-bridge.mjs @@ -2,7 +2,12 @@ import { contextBridge } from 'electron'; import { preferencesApi } from './preferences-api.mjs'; +import { rendererApi } from './renderer-api.mjs'; contextBridge.exposeInMainWorld( - 'mainApi', preferencesApi + 'preferencesApi', preferencesApi +); + +contextBridge.exposeInMainWorld( + 'rendererApi', rendererApi ); diff --git a/renderer/preload-scripts/renderer-api.mjs b/renderer/preload-scripts/renderer-api.mjs new file mode 100644 index 00000000..525ac7af --- /dev/null +++ b/renderer/preload-scripts/renderer-api.mjs @@ -0,0 +1,39 @@ +'use strict'; + +import { ipcRenderer } from 'electron'; + +import { showDay } from '../../js/user-preferences.mjs'; + +function getLanguageDataPromise() +{ + return ipcRenderer.invoke('GET_LANGUAGE_DATA'); +} + +function getOriginalUserPreferences() +{ + const preferences = process.argv.filter((arg) => arg.startsWith('--preferences='))[0]?.split('=')?.[1]; + console.log(preferences); + return JSON.parse(preferences || '{}'); +} + +function getWaiverStoreContents() +{ + return ipcRenderer.invoke('GET_WAIVER_STORE_CONTENTS'); +} + +function showDialogSync(dialogOptions) +{ + return ipcRenderer.invoke('SHOW_DIALOG', dialogOptions); +} + +const rendererApi = { + getLanguageDataPromise, + getOriginalUserPreferences, + getWaiverStoreContents, + showDay, + showDialogSync, +}; + +export { + rendererApi +}; diff --git a/renderer/preload-scripts/workday-waiver-api.mjs b/renderer/preload-scripts/workday-waiver-api.mjs index 0b1538eb..5a2079ec 100644 --- a/renderer/preload-scripts/workday-waiver-api.mjs +++ b/renderer/preload-scripts/workday-waiver-api.mjs @@ -5,14 +5,6 @@ const require = createRequire(import.meta.url); const { ipcRenderer } = require('electron'); -import * as config from '../../src/configs/app.config.mjs'; -import { getUserPreferencesPromise, showDay } from '../../js/user-preferences.mjs'; - -function getLanguageData() -{ - return ipcRenderer.invoke('GET_LANGUAGE_DATA'); -} - function getWaiverDay() { return ipcRenderer.invoke('GET_WAIVER_DAY'); @@ -23,21 +15,6 @@ function showAlert(alertMessage) ipcRenderer.send('SHOW_ALERT', alertMessage); } -function showDialogSync(dialogOptions) -{ - return ipcRenderer.invoke('SHOW_DIALOG', dialogOptions); -} - -function showDayByPreferences(year, month, day, preferences) -{ - return showDay(year, month, day, preferences); -} - -function getWaiverStoreContents() -{ - return ipcRenderer.invoke('GET_WAIVER_STORE_CONTENTS'); -} - function setWaiver(key, contents) { return ipcRenderer.invoke('SET_WAIVER', key, contents); @@ -74,18 +51,12 @@ function getRegions(country, state) } const workdayWaiverApi = { - getLanguageMap: () => config.getLanguageMap(), - getUserPreferences: () => getUserPreferencesPromise(), - getLanguageData: () => getLanguageData(), getWaiverDay: () => getWaiverDay(), showAlert: (alertMessage) => showAlert(alertMessage), - showDialogSync: (dialogOptions) => showDialogSync(dialogOptions), - showDay: (year, month, day, userPreferences) => showDayByPreferences(year, month, day, userPreferences), getHolidays: (country, state, city, year) => getHolidays(country, state, city, year), getCountries: () => getCountries(), getStates: (country) => getStates(country), getRegions: (country, state) => getRegions(country, state), - getWaiverStoreContents: () => getWaiverStoreContents(), setWaiver: (key, contents) => setWaiver(key, contents), hasWaiver: (key) => hasWaiver(key), deleteWaiver: (key) => deleteWaiver(key) diff --git a/renderer/preload-scripts/workday-waiver-bridge.mjs b/renderer/preload-scripts/workday-waiver-bridge.mjs index 4c96b230..364c7656 100644 --- a/renderer/preload-scripts/workday-waiver-bridge.mjs +++ b/renderer/preload-scripts/workday-waiver-bridge.mjs @@ -2,7 +2,13 @@ import { contextBridge } from 'electron'; import { workdayWaiverApi } from './workday-waiver-api.mjs'; +import { rendererApi } from './renderer-api.mjs'; contextBridge.exposeInMainWorld( - 'mainApi', workdayWaiverApi + 'workdayWaiverApi', workdayWaiverApi ); + +contextBridge.exposeInMainWorld( + 'rendererApi', rendererApi +); + diff --git a/src/calendar.js b/src/calendar.js index aad7671b..e4f32f7d 100644 --- a/src/calendar.js +++ b/src/calendar.js @@ -9,7 +9,7 @@ let calendar = undefined; function setupCalendar(preferences) { - window.mainApi.getLanguageDataPromise().then(async languageData => + window.rendererApi.getLanguageDataPromise().then(async languageData => { calendar = await CalendarFactory.getInstance(preferences, languageData, calendar); applyTheme(preferences.theme); @@ -19,7 +19,7 @@ function setupCalendar(preferences) /* * Reload the calendar upon request from main */ -window.mainApi.handleCalendarReload(async() => +window.calendarApi.handleCalendarReload(async() => { await calendar.reload(); }); @@ -27,7 +27,7 @@ window.mainApi.handleCalendarReload(async() => /* * Update the calendar after a day has passed */ -window.mainApi.handleRefreshOnDayChange((event, oldDate, oldMonth, oldYear) => +window.calendarApi.handleRefreshOnDayChange((event, oldDate, oldMonth, oldYear) => { calendar.refreshOnDayChange(oldDate, oldMonth, oldYear); }); @@ -35,7 +35,7 @@ window.mainApi.handleRefreshOnDayChange((event, oldDate, oldMonth, oldYear) => /* * Get notified when preferences has been updated. */ -window.mainApi.handlePreferencesSaved((event, prefs) => +window.calendarApi.handlePreferencesSaved((event, prefs) => { setupCalendar(prefs); }); @@ -43,7 +43,7 @@ window.mainApi.handlePreferencesSaved((event, prefs) => /* * Get notified when waivers get updated. */ -window.mainApi.handleWaiverSaved(async() => +window.calendarApi.handleWaiverSaved(async() => { await calendar.loadInternalWaiveStore(); calendar.redraw(); @@ -52,7 +52,7 @@ window.mainApi.handleWaiverSaved(async() => /* * Punch the date and time as requested by user. */ -window.mainApi.handlePunchDate(() => +window.calendarApi.handlePunchDate(() => { calendar.punchDate(); }); @@ -60,7 +60,7 @@ window.mainApi.handlePunchDate(() => /* * Reload theme. */ -window.mainApi.handleThemeChange(async(event, theme) => +window.calendarApi.handleThemeChange(async(event, theme) => { applyTheme(theme); }); @@ -68,11 +68,11 @@ window.mainApi.handleThemeChange(async(event, theme) => /* * Returns value of "leave by" for notifications. */ -window.mainApi.handleLeaveBy(searchLeaveByElement); +window.calendarApi.handleLeaveBy(searchLeaveByElement); // On page load, create the calendar and setup notification -$(async() => +$(() => { - const preferences = await window.mainApi.getUserPreferencesPromise(); + const preferences = window.rendererApi.getOriginalUserPreferences(); setupCalendar(preferences); }); diff --git a/src/preferences.js b/src/preferences.js index 74585cb7..97d2882c 100644 --- a/src/preferences.js +++ b/src/preferences.js @@ -4,14 +4,13 @@ import { applyTheme } from '../renderer/themes.js'; import i18nTranslator from '../renderer/i18n-translator.js'; // Global values for preferences page -let usersStyles; let preferences; function populateLanguages() { const languageOpts = $('#language'); languageOpts.empty(); - $.each(window.mainApi.getLanguageMap(), (key, value) => + $.each(window.preferencesApi.getLanguageMap(), (key, value) => { languageOpts.append( $('').val('--').html('--')); - const countries = await window.mainApi.getCountries(); + const countries = await window.workdayWaiverApi.getCountries(); $.each(countries, function(i, p) { $('#country').append($('').val(i).html(p)); @@ -206,7 +201,7 @@ async function populateCountry() async function populateState(country) { - const states = await window.mainApi.getStates(country); + const states = await window.workdayWaiverApi.getStates(country); if (states) { $('#state').empty(); @@ -227,7 +222,7 @@ async function populateState(country) async function populateCity(country, state) { - const regions = await window.mainApi.getRegions(country, state); + const regions = await window.workdayWaiverApi.getRegions(country, state); if (regions) { $('#city').empty(); @@ -272,7 +267,7 @@ function getHolidays() const state = $('#state').find(':selected') ? $('#state').find(':selected').val() : undefined; const city = $('#city').find(':selected') ? $('#city').find(':selected').val() : undefined; const year = $('#year').find(':selected').val(); - return window.mainApi.getHolidays(country, state, city, year); + return window.workdayWaiverApi.getHolidays(country, state, city, year); } async function iterateOnHolidays(func) @@ -335,7 +330,7 @@ function clearTable(tableObj) { const table = $(tableObj).find('tbody')[0]; // Clear all rows before adding new ones - while (table.rows.length >= 1) + while (table?.rows.length >= 1) { table.rows[0].remove(); } @@ -353,7 +348,7 @@ async function loadHolidaysTable() } // Fill in reasons to check for conflicts - const store = await window.mainApi.getWaiverStoreContents(); + const store = await window.rendererApi.getWaiverStoreContents(); const reasonByDate = {}; for (const elem of Object.entries(store)) { @@ -371,7 +366,7 @@ async function loadHolidaysTable() { const [tempYear, tempMonth, tempDay] = getDateFromISOStr(holidayDate); // Holiday returns month with 1-12 index, but showDay expects 0-11 - const workingDay = window.mainApi.showDay(tempYear, tempMonth - 1, tempDay, userPreferences) ? getTranslation('$WorkdayWaiver.yes') : getTranslation('$WorkdayWaiver.no'); + const workingDay = window.rendererApi.showDay(tempYear, tempMonth - 1, tempDay, userPreferences) ? getTranslation('$WorkdayWaiver.yes') : getTranslation('$WorkdayWaiver.no'); addHolidayToTable(newTable, holidayDate, holidayReason, workingDay, reasonByDate[holidayDate] ?? ''); } @@ -393,7 +388,7 @@ async function addHolidaysAsWaiver() const importHoliday = $(`#import-${holidayDate}`)[0].checked; if (importHoliday) { - await window.mainApi.setWaiver(holidayDate, { 'reason' : holidayReason, 'hours' : '08:00' }); + await window.workdayWaiverApi.setWaiver(holidayDate, { 'reason' : holidayReason, 'hours' : '08:00' }); addRowToListTable(holidayDate, holidayReason, '08:00'); sortTable(); } @@ -402,7 +397,7 @@ async function addHolidaysAsWaiver() //clear data from table and return the configurations to default await initializeHolidayInfo(); - window.mainApi.showAlert(getTranslation('$WorkdayWaiver.loaded-waivers-holidays')); + window.workdayWaiverApi.showAlert(getTranslation('$WorkdayWaiver.loaded-waivers-holidays')); } async function initializeHolidayInfo() @@ -423,11 +418,11 @@ async function initializeHolidayInfo() $(async() => { - userPreferences = await window.mainApi.getUserPreferences(); + userPreferences = window.rendererApi.getOriginalUserPreferences(); applyTheme(userPreferences.theme); - const waiverDay = await window.mainApi.getWaiverDay(); - languageData = await window.mainApi.getLanguageData(); + const waiverDay = await window.workdayWaiverApi.getWaiverDay(); + languageData = await window.rendererApi.getLanguageDataPromise(); setDates(waiverDay); setHours(userPreferences['hours-per-day']); @@ -496,7 +491,6 @@ export { populateList, populateState, populateYear, - refreshDataForTest, setDates, setHours, toggleAddButton,