electron
Electron patterns for building cross-platform desktop applications. Trigger: When building desktop apps, working with Electron main/renderer processes, IPC communication, or native integrations.
What this skill does
## When to Use
Load this skill when:
- Building cross-platform desktop applications
- Working with Electron's main and renderer processes
- Implementing IPC (Inter-Process Communication)
- Integrating native OS features (menus, notifications, file system)
- Setting up Electron with React, Vue, or other frameworks
- Configuring auto-updates and app distribution
## Critical Patterns
### Pattern 1: Project Structure
```
src/
├── main/ # Main process (Node.js)
│ ├── index.ts # Entry point
│ ├── ipc/ # IPC handlers
│ │ ├── handlers.ts
│ │ └── channels.ts # Type-safe channel names
│ ├── services/ # Native services
│ │ ├── store.ts # electron-store
│ │ └── updater.ts # auto-updater
│ └── windows/ # Window management
│ └── main-window.ts
├── renderer/ # Renderer process (browser)
│ ├── src/
│ │ ├── App.tsx
│ │ ├── components/
│ │ └── hooks/
│ │ └── useIPC.ts # IPC hooks
│ └── index.html
├── preload/ # Preload scripts
│ └── index.ts # Expose safe APIs
└── shared/ # Shared types
└── types.ts
```
### Pattern 2: Secure IPC Communication
Always use contextBridge for secure communication:
```typescript
// preload/index.ts
import { contextBridge, ipcRenderer } from 'electron';
import type { IpcChannels } from '../shared/types';
// Type-safe exposed API
const electronAPI = {
// One-way: renderer -> main
send: <T extends keyof IpcChannels>(
channel: T,
data: IpcChannels[T]['request']
) => {
ipcRenderer.send(channel, data);
},
// Two-way: renderer -> main -> renderer
invoke: <T extends keyof IpcChannels>(
channel: T,
data: IpcChannels[T]['request']
): Promise<IpcChannels[T]['response']> => {
return ipcRenderer.invoke(channel, data);
},
// Listen: main -> renderer
on: <T extends keyof IpcChannels>(
channel: T,
callback: (data: IpcChannels[T]['response']) => void
) => {
const subscription = (_: Electron.IpcRendererEvent, data: IpcChannels[T]['response']) => {
callback(data);
};
ipcRenderer.on(channel, subscription);
return () => ipcRenderer.removeListener(channel, subscription);
},
};
contextBridge.exposeInMainWorld('electron', electronAPI);
```
### Pattern 3: Type-Safe IPC Channels
Define all channels with request/response types:
```typescript
// shared/types.ts
export interface IpcChannels {
'app:get-version': {
request: void;
response: string;
};
'file:read': {
request: { path: string };
response: { content: string } | { error: string };
};
'file:write': {
request: { path: string; content: string };
response: { success: boolean };
};
'dialog:open-file': {
request: { filters?: Electron.FileFilter[] };
response: string | null;
};
'store:get': {
request: { key: string };
response: unknown;
};
'store:set': {
request: { key: string; value: unknown };
response: void;
};
}
// Extend Window interface for renderer
declare global {
interface Window {
electron: typeof electronAPI;
}
}
```
## Code Examples
### Example 1: Main Process Setup
```typescript
// main/index.ts
import { app, BrowserWindow, ipcMain } from 'electron';
import path from 'path';
import { registerIpcHandlers } from './ipc/handlers';
let mainWindow: BrowserWindow | null = null;
async function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true, // Required for security
nodeIntegration: false, // Required for security
sandbox: true, // Extra security
},
titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
trafficLightPosition: { x: 15, y: 10 },
});
// Register IPC handlers
registerIpcHandlers();
// Load the app
if (process.env.NODE_ENV === 'development') {
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
}
mainWindow.on('closed', () => {
mainWindow = null;
});
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
```
### Example 2: IPC Handlers
```typescript
// main/ipc/handlers.ts
import { ipcMain, dialog, app } from 'electron';
import fs from 'fs/promises';
import Store from 'electron-store';
const store = new Store();
export function registerIpcHandlers() {
// Get app version
ipcMain.handle('app:get-version', () => {
return app.getVersion();
});
// File operations
ipcMain.handle('file:read', async (_, { path }) => {
try {
const content = await fs.readFile(path, 'utf-8');
return { content };
} catch (error) {
return { error: (error as Error).message };
}
});
ipcMain.handle('file:write', async (_, { path, content }) => {
try {
await fs.writeFile(path, content, 'utf-8');
return { success: true };
} catch {
return { success: false };
}
});
// Native dialogs
ipcMain.handle('dialog:open-file', async (_, { filters }) => {
const result = await dialog.showOpenDialog({
properties: ['openFile'],
filters: filters || [{ name: 'All Files', extensions: ['*'] }],
});
return result.canceled ? null : result.filePaths[0];
});
// Persistent storage
ipcMain.handle('store:get', (_, { key }) => {
return store.get(key);
});
ipcMain.handle('store:set', (_, { key, value }) => {
store.set(key, value);
});
}
```
### Example 3: React Hook for IPC
```typescript
// renderer/src/hooks/useIPC.ts
import { useCallback, useEffect, useState } from 'react';
export function useIPC<T>(
channel: string,
initialValue: T
): [T, boolean, Error | null] {
const [data, setData] = useState<T>(initialValue);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
let mounted = true;
window.electron
.invoke(channel, undefined)
.then((result) => {
if (mounted) {
setData(result as T);
setLoading(false);
}
})
.catch((err) => {
if (mounted) {
setError(err);
setLoading(false);
}
});
return () => {
mounted = false;
};
}, [channel]);
return [data, loading, error];
}
// Hook for IPC subscriptions
export function useIPCListener<T>(
channel: string,
callback: (data: T) => void
) {
useEffect(() => {
const unsubscribe = window.electron.on(channel, callback);
return unsubscribe;
}, [channel, callback]);
}
// Hook for IPC mutations
export function useIPCMutation<TRequest, TResponse>(channel: string) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const mutate = useCallback(
async (data: TRequest): Promise<TResponse | null> => {
setLoading(true);
setError(null);
try {
const result = await window.electron.invoke(channel, data);
return result as TResponse;
} catch (err) {
setError(err as Error);
return null;
} finally {
setLoading(false);
}
},
[channel]
);
return { mutate, loading, error };
}
```
### Example 4: Auto-Updater Setup
```typescript
// main/services/updater.ts
import { autoUpdater } from 'electron-updater';
import { BrowserWindow } from 'electron';
import log from 'electron-log';
export function setupAutoUpdater(mainWindow: BrowserWindow) {
autoUpdater.logger = log;
autoUpdater.autoDownload = fRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.