### Basic Systray Example Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/README.md A quick example demonstrating how to create a systray icon with a menu and handle click events. Ensure you use the correct icon format (.png for macOS/Linux, .ico for Windows). ```typescript import SysTray from 'systray'; const systray = new SysTray({ menu: { // you should using .png icon in macOS/Linux, but .ico format in windows icon: '', title: '标题', tooltip: 'Tips', items: [ { title: 'aa', tooltip: 'bb', // checked is implement by plain text in linux checked: true, enabled: true, }, { title: 'aa2', tooltip: 'bb', checked: false, enabled: true, }, { title: 'Exit', tooltip: 'bb', checked: false, enabled: true, }, ], }, debug: false, copyDir: true, // copy go tray binary to outside directory, useful for packing tool like pkg. }); systray.onClick((action) => { if (action.seq_id === 0) { systray.sendAction({ type: 'update-item', item: { ...action.item, checked: !action.item.checked, }, seq_id: action.seq_id, }); } else if (action.seq_id === 1) { // open the url console.log('open the url', action); } else if (action.seq_id === 2) { systray.kill(); } }); ``` -------------------------------- ### Install node-systray-v2 Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/README.md Install the library using npm or Yarn. This command adds the package to your project dependencies. ```sh npm install --save https://github.com/Edgar-P-yan/node-systray-v2 # For Yarn, use the command below. yarn add https://github.com/Edgar-P-yan/node-systray-v2 ``` -------------------------------- ### Register onReady event handler Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Executes logic once the system tray is fully initialized. This is the recommended place to start background tasks or application state monitoring. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Ready Demo', tooltip: 'Demonstrates onReady', items: [ { title: 'Item 1', tooltip: 'First item', checked: false, enabled: true }, ], }, }); systray.onReady(() => { console.log('System tray is ready!'); // Initialize application state const startTime = Date.now(); // Set up periodic updates setInterval(() => { const elapsed = Math.floor((Date.now() - startTime) / 1000); console.log(`Running for ${elapsed} seconds`); }, 1000); }); ``` -------------------------------- ### Handle Ready Events - SysTray Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function to be called once the systray application is ready and initialized. This is typically used for setup tasks that depend on the systray being active. ```typescript systray.onReady(() => { console.log('Systray is ready!'); }); ``` -------------------------------- ### getMaxListeners Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Gets the maximum number of listeners allowed for an emitter or event target. ```APIDOC ## getMaxListeners ### Description Returns the currently set max amount of listeners. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning. ### Method `Static` ### Endpoint N/A (Function within a module) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; // For EventEmitter { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } // For EventTarget { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 } ``` ### Response #### Success Response (200) `number` - The maximum number of listeners. #### Response Example N/A (Returns a number, not a JSON response) ``` -------------------------------- ### Manage max listener limits Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Gets or sets the maximum number of listeners allowed for an EventEmitter or EventTarget. ```js import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); console.log(getMaxListeners(ee)); // 10 setMaxListeners(11, ee); console.log(getMaxListeners(ee)); // 11 } { const et = new EventTarget(); console.log(getMaxListeners(et)); // 10 setMaxListeners(11, et); console.log(getMaxListeners(et)); // 11 } ``` -------------------------------- ### Implement a full system tray application in TypeScript Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Demonstrates initializing the tray, handling lifecycle events, and performing dynamic menu updates based on user interaction. ```typescript import SysTray, { ClickEvent } from 'node-systray-v2'; import * as fs from 'fs'; // Load icon based on platform const iconPath = process.platform === 'win32' ? './icon.ico' : './icon.png'; const iconBase64 = fs.readFileSync(iconPath).toString('base64'); const systray = new SysTray({ menu: { icon: iconBase64, title: 'My App', tooltip: 'My Application v1.0', items: [ { title: 'Running: 00:00:00', tooltip: 'Uptime', checked: false, enabled: false }, { title: 'Notifications: ON', tooltip: 'Toggle notifications', checked: true, enabled: true }, { title: 'Clicks: 0', tooltip: 'Click counter', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Quit application', checked: false, enabled: true }, ], }, debug: process.env.NODE_ENV === 'development', copyDir: true, }); // Error handling systray.onError((err) => { console.error('Tray error:', err.message); process.exit(1); }); // Exit handling systray.onExit((code, signal) => { console.log(`Exited: code=${code}, signal=${signal}`); process.exit(0); }); // Main application logic systray.onReady(() => { console.log(`Tray ready, using binary: ${systray.binPath}`); const startTime = Date.now(); let clicks = 0; let notificationsEnabled = true; // Update uptime every second const timerInterval = setInterval(() => { const elapsed = Math.floor((Date.now() - startTime) / 1000); const hours = String(Math.floor(elapsed / 3600)).padStart(2, '0'); const minutes = String(Math.floor((elapsed % 3600) / 60)).padStart(2, '0'); const seconds = String(elapsed % 60).padStart(2, '0'); systray.sendAction({ type: 'update-item', item: { title: `Running: ${hours}:${minutes}:${seconds}`, tooltip: 'Uptime', checked: false, enabled: false, }, seq_id: 0, }); }, 1000); // Handle clicks systray.onClick((event: ClickEvent) => { switch (event.seq_id) { case 1: // Notifications toggle notificationsEnabled = !notificationsEnabled; systray.sendAction({ type: 'update-item', item: { ...event.item, title: `Notifications: ${notificationsEnabled ? 'ON' : 'OFF'}`, checked: notificationsEnabled, }, seq_id: event.seq_id, }); break; case 2: // Click counter clicks++; systray.sendAction({ type: 'update-item', item: { ...event.item, title: `Clicks: ${clicks}`, }, seq_id: event.seq_id, }); break; case 3: // Exit clearInterval(timerInterval); systray.kill(); break; } }); }); ``` -------------------------------- ### Initialize SysTray instance Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Configures the system tray menu structure, including icons, titles, and item states. Use base64 strings for icons and enable copyDir for compatibility with packaging tools like pkg. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { // Use .png for macOS/Linux, .ico for Windows (base64 encoded) icon: '', title: 'My Application', tooltip: 'Application tooltip text', items: [ { title: 'Status: Active', tooltip: 'Current application status', checked: false, enabled: false, // Disabled items appear grayed out }, { title: 'Enable Feature', tooltip: 'Toggle this feature on/off', checked: true, // Shows checkmark on Linux via text suffix enabled: true, }, { title: 'Exit', tooltip: 'Close the application', checked: false, enabled: true, }, ], }, debug: false, // Enable debug logging via 'debug' module copyDir: true, // Copy binary to external dir (useful for pkg packaging) }); ``` -------------------------------- ### Constructor - new SysTray Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Initializes a new instance of the SysTray class with the provided configuration. ```APIDOC ## new SysTray(conf) ### Description Creates a new SysTray instance to manage the system tray application. ### Parameters #### Request Body - **conf** (Conf) - Required - The configuration object for the system tray. ``` -------------------------------- ### Event Handling: onReady Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function to be called when the system tray is ready. This is typically called after the system tray icon has been initialized. Returns a reference to the SysTray instance for chaining. ```APIDOC ## onReady ### Description Registers a listener function to be called when the system tray is ready. ### Method `onReady(listener)` ### Parameters #### Path Parameters - **listener** (() => void) - Required - The callback function to execute when the system tray is ready. ### Response #### Success Response (200) - **SysTray** (SysTray) - A reference to the SysTray instance for chaining. #### Response Example ```json { "example": "SysTray instance" } ``` ### Defined in [src/index.ts:103](https://github.com/Edgar-P-yan/node-systray-v2/blob/0098e9b/src/index.ts#L103) ``` -------------------------------- ### Emit Events with Listeners Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Demonstrates registering multiple listeners for an event and triggering them using emit, passing arguments to the handlers. ```javascript const EventEmitter = require('events'); const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``` -------------------------------- ### sendAction Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Sends an action to the system tray. ```APIDOC ## sendAction ### Description Sends a specific action to the system tray instance. ### Parameters #### Request Body - **action** (Action) - Required - The action object to be sent. ### Response - **SysTray** (Object) - Returns a reference to the SysTray instance for chaining. ``` -------------------------------- ### writeLine Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Writes a line to the system tray process. ```APIDOC ## writeLine ### Description Writes a string line to the system tray interface. ### Parameters #### Request Body - **line** (string) - Required - The string content to write. ### Response - **SysTray** (Object) - Returns a reference to the SysTray instance for chaining. ``` -------------------------------- ### Add One-Time Listener to Beginning - Node.js Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Adds a one-time listener function to the beginning of the listeners array for a given event name. This is an alternative to 'prependOnceListener'. ```javascript const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``` -------------------------------- ### Properties - killed and binPath Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt The SysTray instance exposes read-only properties: `killed` indicates whether the tray process has been terminated, and `binPath` returns the path to the platform-specific tray binary being used. ```APIDOC ## Properties - killed and binPath ### Description The SysTray instance exposes read-only properties: `killed` indicates whether the tray process has been terminated, and `binPath` returns the path to the platform-specific tray binary being used. ### Properties - **killed** (boolean) - Read-only. `true` if the tray process has been terminated, `false` otherwise. - **binPath** (string) - Read-only. The absolute path to the platform-specific tray binary. ### Request Example ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Properties Demo', tooltip: 'Check properties', items: [ { title: 'Check Status', tooltip: 'Log status', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Exit', checked: false, enabled: true }, ], }, debug: true, }); console.log(`Binary path: ${systray.binPath}`); // Output varies by platform: // Windows: .../traybin/tray_windows.exe // macOS: .../traybin/tray_darwin // Linux: .../traybin/tray_linux console.log(`Initially killed: ${systray.killed}`); // false systray.onReady(() => { systray.onClick((event) => { if (event.seq_id === 0) { console.log(`Process killed: ${systray.killed}`); console.log(`Binary location: ${systray.binPath}`); } else if (event.seq_id === 1) { systray.kill(); console.log(`After kill() - killed: ${systray.killed}`); // true } }); }); ``` ### Response These are read-only properties and do not have a direct request/response structure. Their values can be accessed directly from the `systray` instance. ### Response Example ```json { "killed": false, "binPath": "/path/to/your/app/node_modules/node-systray-v2/traybin/tray_linux" } ``` ``` -------------------------------- ### Add One-Time Listener at Beginning Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Use prependOnceListener to add a listener that will be invoked only once and removed afterward. This listener is added to the beginning of the listeners array. ```javascript server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); ``` -------------------------------- ### Send Action to Systray Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Sends a specific action to the system tray. Ensure the action is of the defined Action type. ```typescript sendAction(action) ``` -------------------------------- ### Event Handling: onClick Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function to be called when the system tray icon is clicked. The listener receives a ClickEvent object as an argument. Returns a reference to the SysTray instance for chaining. ```APIDOC ## onClick ### Description Registers a listener function to be called when the system tray icon is clicked. ### Method `onClick(listener)` ### Parameters #### Path Parameters - **listener** ((action: ClickEvent) => void) - Required - The callback function that will be executed on click events. ### Response #### Success Response (200) - **SysTray** (SysTray) - A reference to the SysTray instance for chaining. #### Response Example ```json { "example": "SysTray instance" } ``` ### Defined in [src/index.ts:114](https://github.com/Edgar-P-yan/node-systray-v2/blob/0098e9b/src/index.ts#L114) ``` -------------------------------- ### addListener Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function for a specific event. ```APIDOC ## addListener ### Description Alias for emitter.on(eventName, listener). ### Parameters #### Path Parameters - **eventName** (string | symbol) - Required - The name of the event. - **listener** (Function) - Required - The callback function to execute. ``` -------------------------------- ### Listen for a Single Event with `once` Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Use `once` to create a Promise that resolves with an array of arguments when the specified event is emitted. It handles 'error' events by rejecting the Promise, unless 'error' is the event being listened for. ```javascript const { once, EventEmitter } = require('events'); async function run() { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.log('error happened', err); } } run(); ``` -------------------------------- ### Add Event Listener to Beginning - Node.js Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Adds a listener function to the beginning of the listeners array for a given event name. This is an alternative to 'prependListener' for adding listeners. ```javascript const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a ``` -------------------------------- ### kill Method Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Terminates the system tray process and cleans up resources. Call this method when shutting down your application or when you need to remove the tray icon. ```APIDOC ## kill Method ### Description Terminates the system tray process and cleans up resources. Call this method when shutting down your application or when you need to remove the tray icon. ### Method `systray.kill()` ### Parameters None ### Request Example ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Kill Demo', tooltip: 'Demonstrates kill()', items: [ { title: 'Exit Now', tooltip: 'Click to exit', checked: false, enabled: true }, ], }, }); systray.onReady(() => { // Auto-exit after 10 seconds const timeout = setTimeout(() => { console.log('Auto-exiting after timeout...'); systray.kill(); }, 10000); systray.onClick((event) => { if (event.seq_id === 0) { clearTimeout(timeout); console.log('Manual exit requested'); systray.kill(); } }); }); // Check killed status console.log(`Tray killed: ${systray.killed}`); // false initially ``` ### Response This method does not return a value directly, but it affects the state of the `systray` instance (setting `killed` to `true`). ### Response Example ```json { "status": "success", "message": "Tray process terminated" } ``` ``` -------------------------------- ### sendAction - update-menu Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Updates the entire menu structure, including the tray icon, title, tooltip, and all menu items. ```APIDOC ## sendAction - update-menu ### Description Refreshes the entire tray menu state. ### Request Body - **type** (string) - Required - Must be 'update-menu' - **menu** (object) - Required - The new menu configuration (icon, title, tooltip, items) - **seq_id** (number) - Required - The sequence identifier ### Request Example { "type": "update-menu", "menu": { "icon": "", "title": "New Menu Title", "items": [] }, "seq_id": 0 } ``` -------------------------------- ### Accessors - binPath and killed Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Accessors to retrieve the binary path or the current process status. ```APIDOC ## GET binPath ### Description Returns the path to the system tray binary. ## GET killed ### Description Returns a boolean indicating whether the system tray process has been killed. ``` -------------------------------- ### Event Handling: prependListener Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Adds the listener function to the beginning of the listeners array for the specified event. No checks are made to see if the listener has already been added. Returns a reference to the SysTray instance for chaining. ```APIDOC ## prependListener ### Description Adds the `listener` function to the _beginning_ of the listeners array for the event named `eventName`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple times. Returns a reference to the `EventEmitter`, so that calls can be chained. ### Method `prependListener(eventName, listener)` ### Parameters #### Path Parameters - **eventName** (string \| symbol) - Required - The name of the event. - **listener** ((...args: any[]) => void) - Required - The callback function ### Request Example ```js server.prependListener('connection', (stream) => { console.log('someone connected!'); }); ``` ### Response #### Success Response (200) - **SysTray** (SysTray) - A reference to the SysTray instance for chaining. #### Response Example ```json { "example": "SysTray instance" } ``` ### Inherited from EventEmitter.prependListener ### Defined in node_modules/@types/node/events.d.ts:759 ``` -------------------------------- ### Manage Process Exit with onExit() Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Use the `onExit()` event handler to execute code when the tray process terminates. It provides the exit code and signal, enabling cleanup operations and restart logic. The handler should typically perform necessary cleanup and then exit the main process. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Exit Demo', tooltip: 'Exit handling', items: [ { title: 'Exit', tooltip: 'Exit app', checked: false, enabled: true }, ], }, }); systray.onExit((code: number | null, signal: string | null) => { console.log(`Tray process exited with code: ${code}, signal: ${signal}`); // Perform cleanup console.log('Cleaning up resources...'); // Exit the main process process.exit(code ?? 0); }); systray.onReady(() => { systray.onClick((event) => { if (event.seq_id === 0) { systray.kill(); } }); }); ``` -------------------------------- ### prependOnceListener Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Adds a one-time listener function to the beginning of the listeners array for a specified event. The listener is invoked and then removed the next time the event is triggered. ```APIDOC ## prependOnceListener ### Description Adds a one-time `listener` function for the event named `eventName` to the beginning of the listeners array. The next time `eventName` is triggered, this listener is removed, and then invoked. ### Method `prependOnceListener(eventName, listener)` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```js server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); ``` ### Response #### Success Response (200) Returns a reference to the `SysTray` object, allowing for chained calls. #### Response Example ```json { "message": "SysTray object reference" } ``` #### Inherited from EventEmitter.prependOnceListener #### Defined in node_modules/@types/node/events.d.ts:775 ``` -------------------------------- ### emit Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Synchronously calls each of the listeners registered for the event named eventName. ```APIDOC ## emit ### Description Synchronously calls each of the listeners registered for the event named eventName, in the order they were registered, passing the supplied arguments to each. ### Parameters #### Path Parameters - **eventName** (string | symbol) - Required - The name of the event. - **...args** (any[]) - Optional - Arguments to pass to the listeners. ### Response - **Returns** (boolean) - Returns true if the event had listeners, false otherwise. ``` -------------------------------- ### Update Entire Menu Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Use 'update-menu' to refresh the entire systray menu, including the icon, title, tooltip, and all items. This is useful for a complete state reset. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Status: Normal', tooltip: 'Application running normally', items: [ { title: 'Trigger Alert', tooltip: 'Change to alert mode', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Close', checked: false, enabled: true }, ], }, }); systray.onReady(() => { let isAlertMode = false; systray.onClick((event) => { if (event.seq_id === 0) { isAlertMode = !isAlertMode; // Update the entire menu to reflect new state systray.sendAction({ type: 'update-menu', menu: { icon: isAlertMode ? '' : '', title: isAlertMode ? 'Status: ALERT!' : 'Status: Normal', tooltip: isAlertMode ? 'Alert condition detected' : 'Application running normally', items: [ { title: isAlertMode ? 'Clear Alert' : 'Trigger Alert', tooltip: isAlertMode ? 'Return to normal mode' : 'Change to alert mode', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Close', checked: false, enabled: true }, ], }, seq_id: 0, }); } else if (event.seq_id === 1) { systray.kill(); } }); }); ``` -------------------------------- ### Register onClick event handler Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Handles user interactions with menu items using the item's sequence ID. Use the kill method to terminate the tray process when exiting. ```typescript import SysTray, { ClickEvent } from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Click Demo', tooltip: 'Click handling example', items: [ { title: 'Toggle Option', tooltip: 'Click to toggle', checked: false, enabled: true }, { title: 'Counter: 0', tooltip: 'Click to increment', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Exit application', checked: false, enabled: true }, ], }, }); systray.onReady(() => { let clickCount = 0; systray.onClick((event: ClickEvent) => { console.log(`Clicked item at index ${event.seq_id}: ${event.item.title}`); switch (event.seq_id) { case 0: // Toggle checkbox state console.log(`Current checked state: ${event.item.checked}`); break; case 1: // Increment counter clickCount++; console.log(`Counter incremented to: ${clickCount}`); break; case 2: // Exit console.log('Exiting...'); systray.kill(); break; } }); }); ``` -------------------------------- ### onExit Event Handler Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Registers a callback that fires when the tray process exits. Receives the exit code and signal, useful for cleanup and restart logic. ```APIDOC ## onExit Event Handler ### Description Registers a callback that fires when the tray process exits. Receives the exit code and signal, useful for cleanup and restart logic. ### Method `systray.onExit(callback)` ### Parameters - **callback** (function) - Required - A function that will be called when the tray process exits. It receives two arguments: `code` (number | null) and `signal` (string | null). ### Request Example ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Exit Demo', tooltip: 'Exit handling', items: [ { title: 'Exit', tooltip: 'Exit app', checked: false, enabled: true }, ], }, }); systray.onExit((code: number | null, signal: string | null) => { console.log(`Tray process exited with code: ${code}, signal: ${signal}`); // Perform cleanup console.log('Cleaning up resources...'); // Exit the main process process.exit(code ?? 0); }); systray.onReady(() => { systray.onClick((event) => { if (event.seq_id === 0) { systray.kill(); } }); }); ``` ### Response This method does not return a value. It registers an event handler. ### Response Example No direct response, but the callback function will be invoked with exit code and signal upon process exit. ``` -------------------------------- ### Static once Method Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md The `once` method creates a Promise that resolves with an array of event arguments when the specified event is emitted. It can also be rejected if an 'error' event occurs. This method is compatible with both Node.js EventEmitter and web EventTarget interfaces. An AbortSignal can be used to cancel the promise. ```APIDOC ## Static once Method ### Description Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given event or that is rejected if the `EventEmitter` emits `'error'` while waiting. The `Promise` will resolve with an array of all the arguments emitted to the given event. This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special `'error'` event semantics and does not listen to the `'error'` event. An `AbortSignal` can be used to cancel waiting for the event. ### Method `Static once(emitter, eventName, options?)` ### Parameters #### Path Parameters - **emitter** (`_NodeEventTarget` or `_DOMEventTarget`) - The event emitter or EventTarget to listen on. - **eventName** (`string` | `symbol`) - The name of the event being listened for. - **options?** (`StaticEventEmitterOptions`) - Optional configuration, can include an `AbortSignal`. ### Request Example ```javascript const { once, EventEmitter } = require('events'); async function run() { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); } run(); ``` ### Response #### Success Response (Promise) - **event arguments** (`any[]`) - An array of arguments emitted with the event. #### Response Example ```json [42] ``` ### Defined in `node_modules/@types/node/events.d.ts:199` (for Node.js EventTarget) `node_modules/@types/node/events.d.ts:204` (for DOM EventTarget) ``` -------------------------------- ### Event Handling: onExit Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function to be called when the application is exiting. The listener receives the exit code and signal as arguments. This method returns void. ```APIDOC ## onExit ### Description Registers a listener function to be called when the application is exiting. ### Method `onExit(listener)` ### Parameters #### Path Parameters - **listener** ((code: null \| number, signal: null \| string) => void) - Required - The callback function that will be executed on exit. ### Response #### Success Response (200) - **void** - This method does not return a value. #### Response Example ```json { "example": "void" } ``` ### Defined in [src/index.ts:155](https://github.com/Edgar-P-yan/node-systray-v2/blob/0098e9b/src/index.ts#L155) ``` -------------------------------- ### Terminate System Tray Process with kill() Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Call the kill() method to terminate the system tray process and release resources. This is typically used during application shutdown or when removing the tray icon. The `killed` property indicates the termination status. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Kill Demo', tooltip: 'Demonstrates kill()', items: [ { title: 'Exit Now', tooltip: 'Click to exit', checked: false, enabled: true }, ], }, }); systray.onReady(() => { // Auto-exit after 10 seconds const timeout = setTimeout(() => { console.log('Auto-exiting after timeout...'); systray.kill(); }, 10000); systray.onClick((event) => { if (event.seq_id === 0) { clearTimeout(timeout); console.log('Manual exit requested'); systray.kill(); } }); }); // Check killed status console.log(`Tray killed: ${systray.killed}`); // false initially ``` -------------------------------- ### Static on Method Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md The `on` method returns an AsyncIterator that iterates over events emitted by an EventEmitter. It handles event arguments as an array and removes listeners upon exiting the loop. An AbortSignal can be used to cancel the iteration. ```APIDOC ## Static on Method ### Description Returns an `AsyncIterator` that iterates `eventName` events. It will throw if the `EventEmitter` emits `'error'`. It removes all listeners when exiting the loop. The `value` returned by each iteration is an array composed of the emitted event arguments. An `AbortSignal` can be used to cancel waiting on events. ### Method `Static on(emitter, eventName, options?)` ### Parameters #### Path Parameters - **emitter** (`EventEmitter`) - The event emitter to listen on. - **eventName** (`string`) - The name of the event being listened for. - **options?** (`StaticEventEmitterOptions`) - Optional configuration, can include an `AbortSignal`. ### Request Example ```javascript const { on, EventEmitter } = require('events'); (async () => { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo')) { console.log(event); } })(); ``` ### Response #### Success Response (AsyncIterator) - **event arguments** (`any[]`) - An array of arguments emitted with the event. #### Response Example ```json ["bar"] [42] ``` ### Defined in `node_modules/@types/node/events.d.ts:263` ``` -------------------------------- ### Access Tray Properties: killed and binPath Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Read-only properties `killed` and `binPath` provide status on the tray process. `killed` is a boolean indicating termination, while `binPath` shows the location of the platform-specific tray binary. These are useful for monitoring and debugging. ```typescript import SysTray from 'node-systray-v2'; const systray = new SysTray({ menu: { icon: '', title: 'Properties Demo', tooltip: 'Check properties', items: [ { title: 'Check Status', tooltip: 'Log status', checked: false, enabled: true }, { title: 'Exit', tooltip: 'Exit', checked: false, enabled: true }, ], }, debug: true, }); console.log(`Binary path: ${systray.binPath}`); // Output varies by platform: // Windows: .../traybin/tray_windows.exe // macOS: .../traybin/tray_darwin // Linux: .../traybin/tray_linux console.log(`Initially killed: ${systray.killed}`); // false systray.onReady(() => { systray.onClick((event) => { if (event.seq_id === 0) { console.log(`Process killed: ${systray.killed}`); console.log(`Binary location: ${systray.binPath}`); } else if (event.seq_id === 1) { systray.kill(); console.log(`After kill() - killed: ${systray.killed}`); // true } }); }); ``` -------------------------------- ### sendAction - update-menu-and-item Source: https://context7.com/edgar-p-yan/node-systray-v2/llms.txt Performs an atomic update of both the entire menu structure and a specific item simultaneously. ```APIDOC ## sendAction - update-menu-and-item ### Description Updates both the menu and a specific item in one operation. ### Request Body - **type** (string) - Required - Must be 'update-menu-and-item' - **menu** (object) - Required - The new menu configuration - **item** (object) - Required - The updated item properties - **seq_id** (number) - Required - The sequence identifier ### Request Example { "type": "update-menu-and-item", "menu": { ... }, "item": { ... }, "seq_id": 0 } ``` -------------------------------- ### kill Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Terminates the SysTray process. ```APIDOC ## kill ### Description Terminates the current SysTray instance. ### Response - **Returns** (void) ``` -------------------------------- ### Write Line to Systray Output Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Writes a single line of text to the system tray's output. ```typescript writeLine(line) ``` -------------------------------- ### Cancel Event Listening with `on` and `AbortSignal` Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Cancel an ongoing `on` iteration by providing an `AbortSignal` in the options. The loop will terminate when the signal is aborted. ```javascript const { on, EventEmitter } = require('events'); const ac = new AbortController(); (async () => { const ee = new EventEmitter(); // Emit later on process.nextTick(() => { ee.emit('foo', 'bar'); ee.emit('foo', 42); }); for await (const event of on(ee, 'foo', { signal: ac.signal })) { // The execution of this inner block is synchronous and it // processes one event at a time (even with await). Do not use // if concurrent execution is required. console.log(event); // prints ['bar'] [42] } // Unreachable here })(); process.nextTick(() => ac.abort()); ``` -------------------------------- ### addAbortListener Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Safely listens to the 'abort' event on an AbortSignal, returning a disposable resource to manage the listener. ```APIDOC ## addAbortListener ### Description Listens once to the `abort` event on the provided `signal`. This API allows safely using `AbortSignal`s in Node.js APIs by solving potential issues with `stopImmediatePropagation` and listener cleanup. ### Method `Static` ### Endpoint N/A (Function within a module) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { addAbortListener } from 'node:events'; function example(signal) { let disposable; try { signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); disposable = addAbortListener(signal, (e) => { // Do something when signal is aborted. }); } finally { disposable?.[Symbol.dispose](); } } ``` ### Response #### Success Response (200) `Disposable` - Disposable that removes the `abort` listener. #### Response Example N/A (Returns a disposable object, not a JSON response) ``` -------------------------------- ### Event Handling: on Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Adds a listener function to the end of the listeners array for a specified event. Multiple calls with the same event and listener will result in the listener being called multiple times. Returns a reference to the SysTray instance for chaining. ```APIDOC ## on ### Description Adds the `listener` function to the end of the listeners array for the event named `eventName`. No checks are made to see if the `listener` has already been added. Multiple calls passing the same combination of `eventName` and `listener` will result in the `listener` being added, and called, multiple times. Returns a reference to the `EventEmitter`, so that calls can be chained. By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the event listener to the beginning of the listeners array. ### Method `on(eventName, listener)` ### Parameters #### Path Parameters - **eventName** (string \| symbol) - Required - The name of the event. - **listener** ((...args: any[]) => void) - Required - The callback function ### Request Example ```js server.on('connection', (stream) => { console.log('someone connected!'); }); ``` ### Response #### Success Response (200) - **SysTray** (SysTray) - A reference to the SysTray instance for chaining. #### Response Example ```json { "example": "SysTray instance" } ``` ### Inherited from EventEmitter.on ### Defined in node_modules/@types/node/events.d.ts:506 ``` -------------------------------- ### Retrieve All Event Listeners Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md The rawListeners method returns a copy of the array of listeners for a given event. This includes any wrappers, such as those created by .once(). Be aware that invoking the wrapper directly can lead to unexpected behavior regarding listener removal. ```javascript const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // Logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // Logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // Will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // Logs "log persistently" twice newListeners[0](); emitter.emit('log'); ``` -------------------------------- ### Handle 'error' Event with `once` Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md When `once` is used to listen specifically for the 'error' event, it is treated like any other event and does not have special rejection semantics. ```javascript const { EventEmitter, once } = require('events'); const ee = new EventEmitter(); once(ee, 'error') .then(([err]) => console.log('ok', err.message)) .catch((err) => console.log('error', err.message)); ee.emit('error', new Error('boom')); // Prints: ok boom ``` -------------------------------- ### Handle Click Events - SysTray Source: https://github.com/edgar-p-yan/node-systray-v2/blob/main/docs/classes/SysTray.md Registers a listener function to be called when a click event occurs on the systray icon. The listener receives a ClickEvent object. ```typescript systray.onClick((action: ClickEvent) => { console.log('Clicked on:', action); }); ```