Skip to content

Commit

Permalink
refactor: only allow loading of electron module on desktop platforms
Browse files Browse the repository at this point in the history
The electron module is only available on desktop platforms. This change dynamically loads the electron module via the 'window' object on desktop platforms thereby preventing attempts to load the module on mobile platform where it's not available.
  • Loading branch information
darlal committed Nov 30, 2024
1 parent 455883a commit 60d3b3b
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 43 deletions.
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const { compilerOptions } = require('./tsconfig');
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
globals: {
window: {},
},
moduleFileExtensions: ['ts', 'js', 'jsx', 'tsx', 'json', 'node'],
roots: ['<rootDir>/src/', 'node_modules'],
modulePaths: ['<rootDir>', 'node_modules'],
Expand Down
99 changes: 73 additions & 26 deletions src/Handlers/__tests__/vaultHandler.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
jest.mock('electron', () => {
return {
ipcRenderer: {
sendSync: jest.fn(),
},
};
});

import { ipcRenderer } from 'electron';
import { IpcRenderer } from 'electron';
import { Mode, SuggestionType, MatchType, SearchQuery } from 'src/types';
import { InputInfo } from 'src/switcherPlus';
import { Handler, VaultHandler, VaultData } from 'src/Handlers';
Expand All @@ -18,14 +10,14 @@ import {
vaultTrigger,
makeVaultSuggestion,
} from '@fixtures';
import { mock, MockProxy } from 'jest-mock-extended';
import { mock, mockFn, MockProxy } from 'jest-mock-extended';
import { Searcher } from 'src/search';

describe('vaultHandler', () => {
let settings: SwitcherPlusSettings;
let mockApp: MockProxy<App>;
let sut: VaultHandler;
const mockedIpcRenderer = jest.mocked<typeof ipcRenderer>(ipcRenderer);
const mockIpcRenderer = mock<IpcRenderer>();
const mockPlatform = jest.mocked<typeof Platform>(Platform);

const vaultData: VaultData = {
Expand All @@ -37,11 +29,20 @@ describe('vaultHandler', () => {
settings = new SwitcherPlusSettings(null);
jest.spyOn(settings, 'vaultListCommand', 'get').mockReturnValue(vaultTrigger);

// Used when the electron module is dynamically loaded on desktop platforms
window.require = mockFn<(typeof window)['require']>().mockReturnValue({
ipcRenderer: mockIpcRenderer,
});

mockApp = mock<App>();

sut = new VaultHandler(mockApp, settings);
});

afterAll(() => {
delete window['require'];
});

describe('getCommandString', () => {
it('should return vaultListCommand trigger', () => {
expect(sut.getCommandString()).toBe(vaultTrigger);
Expand Down Expand Up @@ -71,8 +72,8 @@ describe('vaultHandler', () => {
});

describe('getSuggestions', () => {
afterEach(() => {
mockedIpcRenderer.sendSync.mockClear();
beforeEach(() => {
mockIpcRenderer.sendSync.mockClear();
});

test('with falsy input, it should return an empty array', () => {
Expand All @@ -83,22 +84,39 @@ describe('vaultHandler', () => {
expect(results).toHaveLength(0);
});

test('.getItems() should log errors to the console', () => {
test('.getVaultListDataOnDesktop() should log errors to the console', () => {
mockPlatform.isDesktop = true;
const consoleLogSpy = jest.spyOn(console, 'log').mockReturnValueOnce();

const error = new Error('getItems unit test error');
mockedIpcRenderer.sendSync.mockImplementationOnce(() => {
const error = new Error('vaultHandler.getVaultListDataOnDesktop unit test error');
mockIpcRenderer.sendSync.mockImplementationOnce(() => {
throw error;
});

sut.getVaultListDataOnDesktop();

expect(consoleLogSpy).toHaveBeenCalledWith(expect.any(String), error);

consoleLogSpy.mockRestore();
});

test('.getItems() should log errors to the console', () => {
const consoleLogSpy = jest.spyOn(console, 'log').mockReturnValueOnce();

const error = new Error('vaultHandler.getItems unit test error');
const getVaultListDataSpy = jest
.spyOn(sut, 'getVaultListDataOnDesktop')
.mockImplementationOnce(() => {
throw error;
});

sut.getItems();

expect(consoleLogSpy).toHaveBeenCalledWith(
'Switcher++: error retrieving list of available vaults. ',
error,
);
expect(getVaultListDataSpy).toHaveBeenCalled();
expect(consoleLogSpy).toHaveBeenCalledWith(expect.any(String), error);

consoleLogSpy.mockRestore();
getVaultListDataSpy.mockRestore();
});

test('on mobile platforms, it should return the open vault chooser marker', () => {
Expand All @@ -113,8 +131,9 @@ describe('vaultHandler', () => {
});

test('with default settings, it should return suggestions for vault list mode', () => {
mockPlatform.isDesktop = true;
const inputInfo = new InputInfo(vaultTrigger);
mockedIpcRenderer.sendSync.mockReturnValueOnce(vaultData);
mockIpcRenderer.sendSync.mockReturnValueOnce(vaultData);

const results = sut.getSuggestions(inputInfo);

Expand All @@ -127,10 +146,11 @@ describe('vaultHandler', () => {
expect(results).toHaveLength(2);
expect(areAllFound).toBe(true);
expect(results.every((sugg) => sugg.type === SuggestionType.VaultList)).toBe(true);
expect(mockedIpcRenderer.sendSync).toHaveBeenCalledWith('vault-list');
expect(mockIpcRenderer.sendSync).toHaveBeenCalledWith('vault-list');
});

test('with filter search term, it should return only matching suggestions for vault list mode', () => {
mockPlatform.isDesktop = true;
const inputInfo = new InputInfo(null, Mode.VaultList);
const parsedInputQuerySpy = jest
.spyOn(inputInfo, 'parsedInputQuery', 'get')
Expand All @@ -147,12 +167,12 @@ describe('vaultHandler', () => {
return text.endsWith(filterText) ? makeFuzzyMatch() : null;
});

mockedIpcRenderer.sendSync.mockReturnValueOnce(vaultData);
mockIpcRenderer.sendSync.mockReturnValueOnce(vaultData);

const results = sut.getSuggestions(inputInfo);
expect(results).toHaveLength(1);
expect(results[0].pathSegments.path).toBe(expectedItem.path);
expect(mockedIpcRenderer.sendSync).toHaveBeenCalledWith('vault-list');
expect(mockIpcRenderer.sendSync).toHaveBeenCalledWith('vault-list');

searchSpy.mockRestore();
parsedInputQuerySpy.mockRestore();
Expand Down Expand Up @@ -227,20 +247,47 @@ describe('vaultHandler', () => {
expect(() => sut.onChooseSuggestion(null, null)).not.toThrow();
});

test('.openVaultOnDesktop() should do nothing on non-desktop platforms', () => {
mockPlatform.isDesktop = false;
mockIpcRenderer.sendSync.mockClear();

sut.openVaultOnDesktop(null);

expect(mockIpcRenderer.sendSync).not.toHaveBeenCalled();

mockPlatform.isDesktop = true;
});

test('.openVaultOnDesktop() should log errors to the console', () => {
mockPlatform.isDesktop = true;
const consoleLogSpy = jest.spyOn(console, 'log').mockReturnValueOnce();

const error = new Error('vaultHandler.openVaultOnDesktop unit test error');
mockIpcRenderer.sendSync.mockImplementationOnce(() => {
throw error;
});

sut.openVaultOnDesktop(null);

expect(consoleLogSpy).toHaveBeenCalledWith(expect.any(String), error);

consoleLogSpy.mockRestore();
});

it('should open the vault on desktop platforms', () => {
mockPlatform.isDesktop = true;
const sugg = makeVaultSuggestion();

sut.onChooseSuggestion(sugg, null);

expect(mockedIpcRenderer.sendSync).toHaveBeenCalledWith(
expect(mockIpcRenderer.sendSync).toHaveBeenCalledWith(
'vault-open',
sugg.pathSegments.path,
false,
);

mockPlatform.isDesktop = false;
mockedIpcRenderer.sendSync.mockClear();
mockIpcRenderer.sendSync.mockClear();
});

it('should launch the vault chooser on mobile platforms', () => {
Expand Down
73 changes: 56 additions & 17 deletions src/Handlers/vaultHandler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { ipcRenderer } from 'electron';
import { filenameFromPath } from 'src/utils';
import {
AnySuggestion,
Expand Down Expand Up @@ -57,9 +56,7 @@ export class VaultHandler extends Handler<VaultSuggestion> {
if (inputInfo) {
const { query, hasSearchTerm } = inputInfo.parsedInputQuery;
const searcher = Searcher.create(query);
const items = Platform.isDesktop
? this.getItems()
: [this.mobileVaultChooserMarker];
const items = this.getItems();

items.forEach((item) => {
let shouldPush = true;
Expand Down Expand Up @@ -126,12 +123,8 @@ export class VaultHandler extends Handler<VaultSuggestion> {
let handled = false;
if (sugg) {
if (Platform.isDesktop) {
// 12/8/23: "vault-open" is the Obsidian defined channel for open a vault
handled = ipcRenderer.sendSync(
'vault-open',
sugg.pathSegments?.path,
false, // true to create if it doesn't exist
) as boolean;
this.openVaultOnDesktop(sugg.pathSegments?.path);
handled = true;
} else if (sugg === this.mobileVaultChooserMarker) {
// It's the mobile app context, show the vault chooser
this.app.openVaultChooser();
Expand All @@ -145,12 +138,10 @@ export class VaultHandler extends Handler<VaultSuggestion> {
getItems(): VaultSuggestion[] {
const items: VaultSuggestion[] = [];

try {
// 12/8/23: "vault-list" is the Obsidian defined channel for retrieving
// the vault list
const vaultData = ipcRenderer.sendSync('vault-list') as VaultData;
if (Platform.isDesktop) {
try {
const vaultData = this.getVaultListDataOnDesktop();

if (vaultData) {
for (const [id, { path, open }] of Object.entries(vaultData)) {
const basename = filenameFromPath(path);
const sugg: VaultSuggestion = {
Expand All @@ -163,13 +154,61 @@ export class VaultHandler extends Handler<VaultSuggestion> {

items.push(sugg);
}
} catch (err) {
console.log('Switcher++: error parsing vault data. ', err);
}
} catch (err) {
console.log('Switcher++: error retrieving list of available vaults. ', err);
} else {
items.push(this.mobileVaultChooserMarker);
}

return items.sort((a, b) =>
a.pathSegments.basename.localeCompare(b.pathSegments.basename),
);
}

/**
* Instructs Obsidian to open the vault at vaultPath. This should only be called
* Desktop Platforms.
*
* @param {string} vaultPath
*/
openVaultOnDesktop(vaultPath: string): void {
if (!Platform.isDesktop) {
return;
}

try {
const ipcRenderer = window.require('electron').ipcRenderer;

// 12/8/23: "vault-open" is the Obsidian defined channel for opening a vault
ipcRenderer.sendSync(
'vault-open',
vaultPath,
false, // true to create if it doesn't exist
);
} catch (error) {
console.log(`Switcher++: error opening vault with path: ${vaultPath} `, error);
}
}

/**
* Retrieves the list of available vaults that can be opened. This should only be
* called on Desktop Platforms.
*
* @returns {VaultData}
*/
getVaultListDataOnDesktop(): VaultData {
let data: VaultData = null;

if (Platform.isDesktop) {
try {
const ipcRenderer = window.require('electron').ipcRenderer;
data = ipcRenderer.sendSync('vault-list') as VaultData;
} catch (error) {
console.log('Switcher++: error retrieving list of available vaults. ', error);
}
}

return data;
}
}

0 comments on commit 60d3b3b

Please sign in to comment.