Files
upstream-affine/packages/frontend/apps/electron/src/main/tray/index.ts
upstream-mirror 50f788e799
Some checks failed
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 4s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Analyze (javascript, affine) (push) Failing after 3s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
snapshot of https://github.com/toeverything/AFFiNE.git (canary, 2026-09-16; blobs > 131072B omitted)
2026-09-16 00:31:07 +05:00

396 lines
10 KiB
TypeScript

import {
app,
Menu,
MenuItem,
type MenuItemConstructorOptions,
type NativeImage,
nativeImage,
Tray,
} from 'electron';
import { map, shareReplay } from 'rxjs';
import { isMacOS } from '../../shared/utils';
import { applicationMenuSubjects } from '../application-menu';
import { beforeAppQuit } from '../cleanup';
import { logger } from '../logger';
import {
appGroups$,
checkCanRecordMeeting,
checkRecordingAvailable,
getCurrentRecordingStatus,
MeetingsSettingsState,
startRecording,
stopRecording,
updateApplicationsPing$,
} from '../recording/feature';
import { MenubarStateKey, MenubarStateSchema } from '../shared-state-schema';
import { globalStateStorage } from '../shared-storage/storage';
import { showMainWindow } from '../windows-manager';
import { icons } from './icons';
export interface TrayMenuConfigItem {
label: string;
click?: () => void;
icon?: NativeImage | string | Buffer;
disabled?: boolean;
submenu?: TrayMenuConfig;
}
export type TrayMenuConfig = Array<TrayMenuConfigItem | 'separator'>;
// each provider has a unique key and provides a menu config (a group of menu items)
interface TrayMenuProvider {
key: string;
getConfig(): TrayMenuConfig;
}
function activateMainWindow() {
void showMainWindow().catch(err => {
logger.error('Failed to show main window:', err);
});
}
function buildMenuConfig(config: TrayMenuConfig): MenuItemConstructorOptions[] {
const menuConfig: MenuItemConstructorOptions[] = [];
config.forEach(item => {
if (item === 'separator') {
menuConfig.push({ type: 'separator' });
} else {
const { icon, disabled, submenu, ...rest } = item;
let nativeIcon: NativeImage | undefined;
if (typeof icon === 'string') {
nativeIcon = nativeImage.createFromPath(icon);
} else if (Buffer.isBuffer(icon)) {
nativeIcon = nativeImage.createFromBuffer(icon);
}
if (nativeIcon) {
nativeIcon = nativeIcon.resize({ width: 20, height: 20 });
// string icon should be template image
if (typeof icon === 'string') {
nativeIcon.setTemplateImage(true);
}
}
const submenuConfig = submenu ? buildMenuConfig(submenu) : undefined;
menuConfig.push({
...rest,
enabled: !disabled,
icon: nativeIcon,
submenu: submenuConfig,
});
}
});
return menuConfig;
}
class TrayState implements Disposable {
tray: Tray | null = null;
// tray's icon
icon: NativeImage = nativeImage
.createFromPath(icons.tray)
.resize({ width: 18, height: 18 });
// tray's tooltip
tooltip: string = 'AFFiNE';
constructor() {
this.icon.setTemplateImage(true);
this.init();
}
// sorry, no idea on better naming
getPrimaryMenuProvider(): TrayMenuProvider {
return {
key: 'primary',
getConfig: () => [
{
label: 'Open Journal',
icon: icons.journal,
click: () => {
logger.info('User action: Open Journal');
activateMainWindow();
applicationMenuSubjects.openJournal$.next();
},
},
{
label: 'New Page',
icon: icons.page,
click: () => {
logger.info('User action: New Page');
activateMainWindow();
applicationMenuSubjects.newPageAction$.next('page');
},
},
{
label: 'New Edgeless',
icon: icons.edgeless,
click: () => {
logger.info('User action: New Edgeless');
activateMainWindow();
applicationMenuSubjects.newPageAction$.next('edgeless');
},
},
],
};
}
getRecordingMenuProvider(): TrayMenuProvider | null {
if (!checkRecordingAvailable()) {
return null;
}
const getConfig = () => {
const items: TrayMenuConfig = [];
if (!MeetingsSettingsState.value.enabled) {
items.push({
label: 'Meetings are disabled',
disabled: true,
});
} else if (!checkCanRecordMeeting()) {
items.push({
label: 'Required permissions not granted',
disabled: true,
});
} else {
const appGroups = appGroups$.value;
const runningAppGroups = appGroups.filter(
appGroup => appGroup.isRunning
);
const recordingStatus = getCurrentRecordingStatus();
if (
!recordingStatus ||
(recordingStatus.status !== 'starting' &&
recordingStatus.status !== 'recording' &&
recordingStatus.status !== 'finalizing')
) {
const appMenuItems = runningAppGroups.map(appGroup => ({
label: appGroup.name,
icon: appGroup.icon || undefined,
click: () => {
logger.info(
`User action: Start Recording Meeting (${appGroup.name})`
);
startRecording(appGroup).catch(err => {
logger.error('Failed to start recording:', err);
});
},
}));
items.push(
{
label: 'Start Recording Meeting',
icon: icons.record,
submenu: [
{
label: 'System audio (all audio will be recorded)',
icon: icons.monitor,
click: () => {
logger.info(
'User action: Start Recording Meeting (System audio)'
);
startRecording().catch(err => {
logger.error('Failed to start recording:', err);
});
},
},
...appMenuItems,
],
},
...appMenuItems
);
} else {
const recordingLabel = recordingStatus.appName
? `Recording (${recordingStatus.appName})`
: 'Recording';
// recording is active
items.push(
{
label: recordingLabel,
icon: icons.recording,
disabled: true,
},
{
label: 'Stop',
disabled: recordingStatus.status !== 'recording',
click: () => {
logger.info('User action: Stop Recording');
if (recordingStatus.status === 'recording') {
stopRecording(recordingStatus.id).catch(err => {
logger.error('Failed to stop recording:', err);
});
}
},
}
);
}
}
if (checkRecordingAvailable()) {
items.push({
label: `Meetings Settings...`,
click: () => {
activateMainWindow();
applicationMenuSubjects.openInSettingModal$.next({
activeTab: 'meetings',
});
},
});
}
return items;
};
return {
key: 'recording',
getConfig,
};
}
getSecondaryMenuProvider(): TrayMenuProvider {
return {
key: 'secondary',
getConfig: () => [
{
label: 'Open AFFiNE',
click: () => {
logger.info('User action: Open AFFiNE');
activateMainWindow();
},
},
{
label: 'Menubar settings...',
click: () => {
activateMainWindow();
applicationMenuSubjects.openInSettingModal$.next({
activeTab: 'appearance',
scrollAnchor: 'menubar',
});
},
},
{
label: `About ${app.getName()}`,
click: () => {
activateMainWindow();
applicationMenuSubjects.openInSettingModal$.next({
activeTab: 'about',
});
},
},
'separator',
{
label: 'Quit AFFiNE Completely...',
click: () => {
logger.info('User action: Quit AFFiNE Completely');
app.quit();
},
},
],
};
}
buildMenu(providers: TrayMenuProvider[]) {
const menu = new Menu();
providers.forEach((provider, index) => {
const config = provider.getConfig();
buildMenuConfig(config).forEach(item => {
menu.append(new MenuItem(item));
});
if (index !== providers.length - 1) {
menu.append(new MenuItem({ type: 'separator' }));
}
});
return menu;
}
disposables: (() => void)[] = [];
[Symbol.dispose]() {
this.disposables.forEach(d => d());
}
update() {
if (!this.tray) {
this.tray = new Tray(this.icon);
this.tray.setToolTip(this.tooltip);
const clickHandler = () => {
logger.debug('User clicked on tray icon');
this.update();
if (!isMacOS()) {
if (
TraySettingsState.value.enabled &&
TraySettingsState.value.openOnLeftClick
) {
activateMainWindow();
} else {
this.tray?.popUpContextMenu();
}
}
updateApplicationsPing$.next(Date.now());
};
this.tray.on('click', clickHandler);
const appGroupsSubscription = appGroups$.subscribe(() => {
logger.debug('App groups updated, refreshing tray menu');
this.update();
});
this.disposables.push(() => {
this.tray?.off('click', clickHandler);
this.tray?.destroy();
appGroupsSubscription.unsubscribe();
});
}
const providers = [
this.getPrimaryMenuProvider(),
this.getRecordingMenuProvider(),
this.getSecondaryMenuProvider(),
].filter(p => p !== null);
const menu = this.buildMenu(providers);
this.tray.setContextMenu(menu);
}
init() {
logger.info('Initializing tray');
this.update();
}
}
const TraySettingsState = {
$: globalStateStorage.watch<MenubarStateSchema>(MenubarStateKey).pipe(
map(v => MenubarStateSchema.parse(v ?? {})),
shareReplay(1)
),
get value() {
return MenubarStateSchema.parse(
globalStateStorage.get(MenubarStateKey) ?? {}
);
},
};
export const setupTrayState = () => {
let _trayState: TrayState | undefined;
if (TraySettingsState.value.enabled) {
_trayState = new TrayState();
}
const updateTrayState = (state: MenubarStateSchema) => {
if (state.enabled) {
if (!_trayState) {
_trayState = new TrayState();
}
} else {
_trayState?.[Symbol.dispose]();
_trayState = undefined;
}
};
const subscription = TraySettingsState.$.subscribe(updateTrayState);
beforeAppQuit(() => {
subscription.unsubscribe();
});
};