mac-system-theme.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Syncs pi theme with macOS system appearance (dark/light mode).
  3. *
  4. * Usage:
  5. * pi -e examples/extensions/mac-system-theme.ts
  6. */
  7. import { exec } from "node:child_process";
  8. import { promisify } from "node:util";
  9. import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
  10. const execAsync = promisify(exec);
  11. async function isDarkMode(): Promise<boolean> {
  12. try {
  13. const { stdout } = await execAsync(
  14. "osascript -e 'tell application \"System Events\" to tell appearance preferences to return dark mode'",
  15. );
  16. return stdout.trim() === "true";
  17. } catch {
  18. return false;
  19. }
  20. }
  21. export default function (pi: ExtensionAPI) {
  22. let intervalId: ReturnType<typeof setInterval> | null = null;
  23. pi.on("session_start", async (_event, ctx) => {
  24. let currentTheme = (await isDarkMode()) ? "dark" : "light";
  25. ctx.ui.setTheme(currentTheme);
  26. intervalId = setInterval(async () => {
  27. const newTheme = (await isDarkMode()) ? "dark" : "light";
  28. if (newTheme !== currentTheme) {
  29. currentTheme = newTheme;
  30. ctx.ui.setTheme(currentTheme);
  31. }
  32. }, 2000);
  33. });
  34. pi.on("session_shutdown", () => {
  35. if (intervalId) {
  36. clearInterval(intervalId);
  37. intervalId = null;
  38. }
  39. });
  40. }