Skip to content

Open source CapCut alternative.

TypeScript
2.6 KB
Raw Blame
// React bindings for the backend seam, kept out of ./index so the engine
// binary (which compiles lib/types.ts → ./index) never bundles React.
import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";

import { currentEngineUser, subscribeEngineUser } from "../api";
import { listedResidencies, type Residency } from "../residency";
import { fetchCloudUsage, type CloudUsage } from "./cloud";
import { cutMode, getBackend, hasLocalCompute, subscribeCutMode } from "./index";
import type { CutCaps, CutMode } from "./types";

export function useCutMode(): CutMode {
  return useSyncExternalStore(subscribeCutMode, cutMode, () => "local" as const);
}

/** The account every engine read is scoped to, or null before the session has
 * resolved. Null on the server, so a prerendered shell holds its skeleton. */
export function useEngineUser(): string | null {
  return useSyncExternalStore(subscribeEngineUser, currentEngineUser, () => null);
}

/** Whether this Mac's engine is reachable, as a subscription: the gate resolves
 * it after the first paint, so a screen that offers local work has to redraw
 * when the answer lands. */
export function useLocalCompute(): boolean {
  return useSyncExternalStore(subscribeCutMode, hasLocalCompute, () => false);
}

// The shelves the home lists, as a subscription. The array is held between
// reads and replaced only when the set actually changes: useSyncExternalStore
// re-renders forever on a fresh object every call.
const CLOUD_ONLY: Residency[] = ["cloud"];
let listed: Residency[] = CLOUD_ONLY;

function listedSnapshot(): Residency[] {
  const next = listedResidencies();
  if (next.length !== listed.length || next.some((r, i) => r !== listed[i])) listed = next;
  return listed;
}

/** Which residencies the projects home shows — see `listedResidencies`. */
export function useListedResidencies(): Residency[] {
  return useSyncExternalStore(subscribeCutMode, listedSnapshot, () => CLOUD_ONLY);
}

export function useCutCaps(): CutCaps {
  useCutMode();
  return getBackend().caps;
}

export const cloudUsageQueryKey = ["cut", "cloud-usage"] as const;

/** The account's cloud storage usage — cloud-only by construction, so it hits
 * the hosted route directly on the session cookie. `poll` is for the editor's
 * live meter; readers that only need the number once should leave it off. */
export function useCloudUsage(enabled: boolean, opts?: { poll?: boolean }) {
  return useQuery<CloudUsage>({
    enabled,
    queryKey: cloudUsageQueryKey,
    queryFn: fetchCloudUsage,
    ...(opts?.poll ? { refetchInterval: 60_000 } : {}),
  });
}