RotNot / src /lib /native /index.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
8.2 kB
/**
* RotNot Native Bridge
*
* Wraps Capacitor native plugins behind feature-detection so that:
* - In a Capacitor app: real native APIs fire (haptics, push notifications, etc.)
* - In a plain browser (web/PWA): graceful no-ops, no import errors
*
* Usage:
* import { nativeHaptics, nativePush } from "@/lib/native";
* await nativeHaptics.xpGain(); // fires haptic if native, else no-op
* await nativePush.requestPermission(); // requests native push if available
*/
// ─── Platform Detection ────────────────────────────────────────────────────
/**
* Returns true when running inside a Capacitor WebView.
* Safe to call during SSR (returns false on server).
*/
export function isNative(): boolean {
if (typeof window === "undefined") return false;
return !!(window as Window & { Capacitor?: { isNativePlatform?: () => boolean } }).Capacitor?.isNativePlatform?.();
}
// ─── Haptics ──────────────────────────────────────────────────────────────
type HapticStyle = "light" | "medium" | "heavy";
async function triggerHaptic(style: HapticStyle = "medium"): Promise<void> {
if (!isNative()) return;
try {
const { Haptics, ImpactStyle } = await import("@capacitor/haptics");
const styleMap: Record<HapticStyle, typeof ImpactStyle[keyof typeof ImpactStyle]> = {
light: ImpactStyle.Light,
medium: ImpactStyle.Medium,
heavy: ImpactStyle.Heavy,
};
await Haptics.impact({ style: styleMap[style] });
} catch {
// Plugin not available β€” silent no-op
}
}
async function triggerNotificationHaptic(): Promise<void> {
if (!isNative()) return;
try {
const { Haptics, NotificationType } = await import("@capacitor/haptics");
await Haptics.notification({ type: NotificationType.Success });
} catch {
// Plugin not available β€” silent no-op
}
}
async function triggerErrorHaptic(): Promise<void> {
if (!isNative()) return;
try {
const { Haptics, NotificationType } = await import("@capacitor/haptics");
await Haptics.notification({ type: NotificationType.Error });
} catch {
// Plugin not available β€” silent no-op
}
}
export const nativeHaptics = {
/** Light tap β€” button presses, selection changes */
tap: () => triggerHaptic("light"),
/** Medium impact β€” XP gained, exercise completed */
xpGain: () => triggerHaptic("medium"),
/** Heavy impact β€” level up, major unlock */
levelUp: () => triggerHaptic("heavy"),
/** Success notification pattern β€” correct answer */
correct: () => triggerNotificationHaptic(),
/** Error notification pattern β€” wrong answer, streak break */
error: () => triggerErrorHaptic(),
};
// ─── Push Notifications ───────────────────────────────────────────────────
export interface PushPermissionResult {
granted: boolean;
token?: string;
}
export const nativePush = {
/**
* Request push notification permission and return the device token.
* Returns { granted: false } in web/PWA context.
*/
async requestPermission(): Promise<PushPermissionResult> {
if (!isNative()) return { granted: false };
try {
const { PushNotifications } = await import("@capacitor/push-notifications");
const permission = await PushNotifications.requestPermissions();
if (permission.receive !== "granted") return { granted: false };
await PushNotifications.register();
return new Promise<PushPermissionResult>((resolve) => {
const timeout = setTimeout(() => resolve({ granted: true }), 5000);
PushNotifications.addListener("registration", (token) => {
clearTimeout(timeout);
resolve({ granted: true, token: token.value });
});
PushNotifications.addListener("registrationError", () => {
clearTimeout(timeout);
resolve({ granted: false });
});
});
} catch {
return { granted: false };
}
},
};
// ─── Local Notifications ──────────────────────────────────────────────────
export interface StreakReminderOptions {
/** Minutes from now to fire the reminder. Default: next day at 9am. */
delayMinutes?: number;
streakDays: number;
}
export const nativeNotifications = {
/**
* Schedule a local notification reminding the user to maintain their streak.
* No-op in web/PWA context.
*/
async scheduleStreakReminder(opts: StreakReminderOptions): Promise<void> {
if (!isNative()) return;
try {
const { LocalNotifications } = await import("@capacitor/local-notifications");
const permission = await LocalNotifications.requestPermissions();
if (permission.display !== "granted") return;
const fireAt = new Date();
if (opts.delayMinutes) {
fireAt.setMinutes(fireAt.getMinutes() + opts.delayMinutes);
} else {
// Default: tomorrow at 9am
fireAt.setDate(fireAt.getDate() + 1);
fireAt.setHours(9, 0, 0, 0);
}
await LocalNotifications.schedule({
notifications: [
{
id: 1001, // Fixed ID β€” overwrites previous streak reminder
title: "πŸ”₯ Keep your streak alive!",
body:
opts.streakDays > 0
? `You're on a ${opts.streakDays}-day streak. Don't break it now!`
: "Complete an exercise today to start a new streak.",
schedule: { at: fireAt },
sound: undefined,
smallIcon: "ic_stat_icon_config_sample",
},
],
});
} catch {
// Plugin not available β€” silent no-op
}
},
/**
* Schedule a local notification for a spaced repetition review due.
* No-op in web/PWA context.
*/
async scheduleReviewReminder(dueCount: number, dueAt: Date): Promise<void> {
if (!isNative()) return;
try {
const { LocalNotifications } = await import("@capacitor/local-notifications");
const permission = await LocalNotifications.requestPermissions();
if (permission.display !== "granted") return;
await LocalNotifications.schedule({
notifications: [
{
id: 1002, // Fixed ID β€” overwrites previous review reminder
title: "🧠 Reviews waiting for you",
body:
dueCount === 1
? "1 Feynman topic is due for review."
: `${dueCount} Feynman topics are due for review.`,
schedule: { at: dueAt },
sound: undefined,
smallIcon: "ic_stat_icon_config_sample",
},
],
});
} catch {
// Plugin not available β€” silent no-op
}
},
/** Cancel all scheduled reminders. */
async cancelAll(): Promise<void> {
if (!isNative()) return;
try {
const { LocalNotifications } = await import("@capacitor/local-notifications");
await LocalNotifications.cancel({ notifications: [{ id: 1001 }, { id: 1002 }] });
} catch {
// Plugin not available β€” silent no-op
}
},
};
// ─── Status Bar ───────────────────────────────────────────────────────────
export const nativeStatusBar = {
/**
* Set the status bar to dark content (light background) or light (dark background).
* RotNot uses a dark theme, so we want light text in the status bar.
*/
async setDark(): Promise<void> {
if (!isNative()) return;
try {
const { StatusBar, Style } = await import("@capacitor/status-bar");
await StatusBar.setStyle({ style: Style.Dark });
// Match the RotNot navy background
await StatusBar.setBackgroundColor({ color: "#0f172a" });
} catch {
// Plugin not available β€” silent no-op
}
},
};