initial
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import {
|
||||
isPermissionGranted,
|
||||
requestPermission,
|
||||
sendNotification,
|
||||
} from '@tauri-apps/plugin-notification';
|
||||
|
||||
// Tracks whether permission has already been requested this session so we
|
||||
// don't spam the OS prompt. Actual permission state lives in the OS.
|
||||
let permissionChecked = false;
|
||||
let permissionGranted = false;
|
||||
|
||||
export async function ensureNotificationPermission(): Promise<boolean> {
|
||||
if (permissionChecked) return permissionGranted;
|
||||
permissionChecked = true;
|
||||
try {
|
||||
let granted = await isPermissionGranted();
|
||||
if (!granted) {
|
||||
const result = await requestPermission();
|
||||
granted = result === 'granted';
|
||||
}
|
||||
permissionGranted = granted;
|
||||
} catch (err: unknown) {
|
||||
// Not running under Tauri (e.g. web preview) — fall back silently.
|
||||
permissionGranted = false;
|
||||
console.warn('notification permission check failed', err);
|
||||
}
|
||||
return permissionGranted;
|
||||
}
|
||||
|
||||
export function isAppFocused(): boolean {
|
||||
return typeof document !== 'undefined' && !document.hidden && document.hasFocus();
|
||||
}
|
||||
|
||||
interface NotifyOpts {
|
||||
title: string;
|
||||
body?: string;
|
||||
// Force notification even when app is focused. Default: suppress if focused.
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export async function notify({ title, body, force = false }: NotifyOpts): Promise<void> {
|
||||
if (!force && isAppFocused()) return;
|
||||
const granted = await ensureNotificationPermission();
|
||||
if (!granted) return;
|
||||
try {
|
||||
sendNotification({ title, ...(body ? { body } : {}) });
|
||||
} catch (err: unknown) {
|
||||
console.error('sendNotification failed', err);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user