Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

10.1 KB
Raw Blame
import { useEffect, useMemo, useRef, useState } from "react";
import {
  byeSettingsHost,
  callSettingsHost,
  helloSettingsHost,
  onSettingsWindowBye,
  onSettingsWindowCall,
  onSettingsWindowHello,
  onSettingsWindowReply,
  onSettingsWindowState,
  publishSettingsWindowState,
  replySettingsWindowCall,
  type SettingsWindowCallDto,
} from "../../lib/bridge";
import type { SettingsSheetProps } from "./SettingsSheet";

/**
 * The link between the popover's Settings and the full Settings window.
 *
 * Home owns every setting the sheet shows (recording options, devices, app
 * preferences) and the handlers that change them. The window renders the
 * same `SettingsSheet` from a copy of that data, and each control it uses
 * becomes a call to the matching handler in Home (`useSettingsWindowHost`),
 * which runs it exactly as the popover's sheet would. Home then sends the
 * new data back, so a change made in either place shows in both.
 */

/** Every handler the sheet calls with plain, serializable arguments. */
export const SETTINGS_HANDLERS = [
  "onCameraLook",
  "onResolution",
  "onUpgrade",
  "onUpgradePlan",
  "onCountdown",
  "onMirror",
  "onWebcamLayout",
  "onWebcamShape",
  "onWebcamSize",
  "onPersistWebcamPosition",
  "onAudioOptions",
  "onWebcamDevice",
  "onRefreshDevices",
  "onWindowCapture",
  "onShowRecordingControls",
  "onHotkeyChange",
  "onShowInDock",
  "onOpenLocalArec",
  "onScreenshotEditor",
  "onOpenRecordings",
  "onSetupGuide",
  "onCheckForUpdates",
  "onInstallUpdate",
  "onSignOut",
  "onSignIn",
] as const satisfies ReadonlyArray<keyof SettingsSheetProps>;

type HandlerName = (typeof SETTINGS_HANDLERS)[number];
/** Props each side sets for itself: never sent between the two. */
type LocalProp = "initialTab" | "tab" | "onTabChange";

export type SettingsSheetHandlers = Pick<SettingsSheetProps, HandlerName>;
export type SettingsSheetData = Omit<SettingsSheetProps, HandlerName | LocalProp>;
/** What Home builds once for both places: data plus handlers. */
export type SettingsHostProps = SettingsSheetData & SettingsSheetHandlers;

// A handler added to the sheet must be listed above (or be a local prop),
// or the window would render it as undefined. This fails to compile then.
type FunctionProp = {
  [K in keyof SettingsSheetProps]-?: NonNullable<SettingsSheetProps[K]> extends (...args: never[]) => unknown ? K : never;
}[keyof SettingsSheetProps];
const everyHandlerIsListed: [Exclude<FunctionProp, HandlerName | LocalProp>] extends [never] ? true : false = true;
void everyHandlerIsListed;

/**
 * Handlers that change what Home saves as recording settings (resolution,
 * window capture, countdown, audio, camera layout and device). In the
 * popover they are saved when the picker closes or a recording starts; a
 * change from the window reaches neither, so Home saves it as it arrives
 * (`onRecordingSettingChanged`). Every other handler saves through its own
 * command.
 */
export const RECORDING_SETTING_HANDLERS: ReadonlySet<string> = new Set<HandlerName>([
  "onResolution",
  "onWindowCapture",
  "onCountdown",
  "onAudioOptions",
  "onWebcamLayout",
  "onWebcamShape",
  "onWebcamSize",
  "onWebcamDevice",
]);

const LOCAL_PROPS: ReadonlySet<string> = new Set<LocalProp>(["initialTab", "tab", "onTabChange"]);
const HANDLER_NAMES: ReadonlySet<string> = new Set<string>(SETTINGS_HANDLERS);

/** The sheet's data props: everything but handlers and local props. */
export function settingsSheetData(props: SettingsHostProps): SettingsSheetData {
  const data: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(props)) {
    if (typeof value === "function" || LOCAL_PROPS.has(key)) continue;
    data[key] = value;
  }
  return data as unknown as SettingsSheetData;
}

export interface SettingsHostEvents {
  /** The window opened (or came back into focus): Home can read again
   *  anything another window may have changed, as opening the sheet does. */
  onHello?: () => void;
  /** A change from the window to a recording setting
   *  (`RECORDING_SETTING_HANDLERS`) went through; Home saves it. */
  onRecordingSettingChanged?: () => void;
  /** The window is closing: Home saves what it holds. */
  onClose?: () => void;
}

/**
 * Home's side. `props` is what the popover's sheet would get (null until
 * Home has loaded them).
 */
export function useSettingsWindowHost(props: SettingsHostProps | null, events: SettingsHostEvents = {}): void {
  const propsRef = useRef(props);
  propsRef.current = props;
  const eventsRef = useRef(events);
  eventsRef.current = events;
  const json = props ? JSON.stringify(settingsSheetData(props)) : null;
  const jsonRef = useRef(json);
  jsonRef.current = json;

  useEffect(() => {
    void publishSettingsWindowState({ data: json === null ? null : (JSON.parse(json) as Record<string, unknown>) })?.catch?.(() => {});
  }, [json]);

  useEffect(() => {
    let active = true;
    const offs: Array<() => void> = [];
    const keep = (pending: Promise<() => void> | undefined) => {
      void pending?.then((off) => {
        if (active) offs.push(off);
        else off();
      });
    };
    keep(
      onSettingsWindowHello(() => {
        eventsRef.current.onHello?.();
        const current = jsonRef.current;
        void publishSettingsWindowState({ data: current === null ? null : (JSON.parse(current) as Record<string, unknown>) })?.catch?.(() => {});
      }),
    );
    keep(
      onSettingsWindowCall((call: SettingsWindowCallDto) => {
        const handler = HANDLER_NAMES.has(call.name)
          ? (propsRef.current?.[call.name as HandlerName] as ((...args: unknown[]) => unknown) | undefined)
          : undefined;
        const reply = (error: string | null) => void replySettingsWindowCall({ id: call.id, error })?.catch?.(() => {});
        if (!handler) {
          reply("Clipy is not ready to change this yet.");
          return;
        }
        Promise.resolve()
          .then(() => handler(...(Array.isArray(call.args) ? call.args : [])))
          .then(
            () => {
              reply(null);
              if (RECORDING_SETTING_HANDLERS.has(call.name)) eventsRef.current.onRecordingSettingChanged?.();
            },
            (err: unknown) => reply(String(err)),
          );
      }),
    );
    keep(onSettingsWindowBye(() => eventsRef.current.onClose?.()));
    return () => {
      active = false;
      offs.forEach((off) => off());
      // Signed out, or the popover reloaded: the window shows its waiting
      // state rather than settings nobody is listening for.
      void publishSettingsWindowState({ data: null })?.catch?.(() => {});
    };
  }, []);
}

/** How long the window waits for Home before saying how to load settings. */
export const HOST_WAIT_MS = 2500;
/** How long a call may take before the window gives up on its answer. */
const CALL_TIMEOUT_MS = 15_000;

/** The window's side: the data to render and handlers that call Home. */
export function useSettingsHostConnection(): {
  data: SettingsSheetData | null;
  handlers: SettingsSheetHandlers;
  waited: boolean;
} {
  const [data, setData] = useState<SettingsSheetData | null>(null);
  const [waited, setWaited] = useState(false);
  const pending = useRef(new Map<string, { resolve: () => void; reject: (err: Error) => void }>());
  const counter = useRef(0);

  useEffect(() => {
    let active = true;
    const offs: Array<() => void> = [];
    const keep = (listening: Promise<() => void>) =>
      listening.then((off) => {
        if (active) offs.push(off);
        else off();
      });
    const ready = Promise.all([
      keep(onSettingsWindowState((state) => setData((state?.data ?? null) as SettingsSheetData | null))),
      keep(
        onSettingsWindowReply((reply) => {
          const waiting = pending.current.get(reply.id);
          if (!waiting) return;
          pending.current.delete(reply.id);
          if (reply.error) waiting.reject(new Error(reply.error));
          else waiting.resolve();
        }),
      ),
    ]);
    // Listen first, then ask: an answer sent in between would be lost.
    void ready.then(() => helloSettingsHost()).catch(() => {});
    // Coming back to the window reads everything again, in case the
    // popover's sheet changed something meanwhile.
    const onFocus = () => void helloSettingsHost().catch(() => {});
    window.addEventListener("focus", onFocus);
    // Closing the window: Home saves what it holds (best effort; Home also
    // saves each recording setting as it changes).
    const onUnload = () => void byeSettingsHost().catch(() => {});
    window.addEventListener("beforeunload", onUnload);
    const timer = window.setTimeout(() => setWaited(true), HOST_WAIT_MS);
    return () => {
      active = false;
      offs.forEach((off) => off());
      window.removeEventListener("focus", onFocus);
      window.removeEventListener("beforeunload", onUnload);
      window.clearTimeout(timer);
    };
  }, []);

  const handlers = useMemo(() => {
    const call = (name: HandlerName, args: unknown[]): Promise<void> => {
      counter.current += 1;
      const id = `${Date.now().toString(36)}-${counter.current}`;
      const result = new Promise<void>((resolve, reject) => {
        const timer = window.setTimeout(() => {
          pending.current.delete(id);
          reject(new Error("Clipy did not answer. Open Clipy from the menu bar and try again."));
        }, CALL_TIMEOUT_MS);
        pending.current.set(id, {
          resolve: () => {
            window.clearTimeout(timer);
            resolve();
          },
          reject: (err) => {
            window.clearTimeout(timer);
            reject(err);
          },
        });
        callSettingsHost({ id, name, args }).catch((err: unknown) => {
          pending.current.get(id)?.reject(new Error(String(err)));
          pending.current.delete(id);
        });
      });
      // Most controls do not wait for the answer; the ones that do
      // (switches that show an error) still see the rejection.
      result.catch(() => {});
      return result;
    };
    return Object.fromEntries(
      SETTINGS_HANDLERS.map((name) => [name, (...args: unknown[]) => call(name, args)]),
    ) as unknown as SettingsSheetHandlers;
  }, []);

  return { data, handlers, waited };
}