Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

2.5 KB
Raw Blame
import { Loader2, Square, Volume2 } from "lucide-react";

import { speaker } from "@/lib/tts";
import { useSpeech } from "@/lib/tts/useSpeech";
import type { ConfigStatus } from "@/state/store";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { ACTION_ICON } from "@/components/MessageActions";

type SpeakArgs = {
  text: string;
  botId?: string;
  messageId: string;
  voiceId?: string;
  playbackRate?: number;
  tts: ConfigStatus["tts"];
  localVoice: boolean;
};

/** Whether a message can be read aloud now: this device's own voice, or a set-up voice service with a voice picked. */
export function speakReady(tts: ConfigStatus["tts"], voiceId: string | undefined, localVoice: boolean): boolean {
  return localVoice || (Boolean(tts?.configured) && Boolean(voiceId || tts?.voice));
}

export function useSpeakAction({ text, botId, messageId, voiceId, playbackRate, tts, localVoice }: SpeakArgs) {
  const speech = useSpeech();
  const configured = localVoice || Boolean(tts?.configured);
  const ready = speakReady(tts, voiceId, localVoice);
  const mine = speech.messageId === messageId && speech.status !== "idle";
  const preparing = mine && speech.status === "preparing";
  const label = !configured
    ? t((tts?.provider ?? "elevenlabs") === "elevenlabs" ? "chat.speak.needsKey" : "chat.speak.needsSetup")
    : !ready
      ? t("chat.speak.needsVoice")
    : mine
      ? t("chat.speak.stop")
      : t("chat.speak.read");
  const toggle = () => {
    if (mine) return speaker.stop();
    void speaker.speak(text, { botId, messageId, voiceId, playbackRate });
  };
  return { ready, mine, preparing, label, toggle };
}

export function SpeakButton({ className, ...args }: SpeakArgs & { className?: string }) {
  const { ready, mine, preparing, label, toggle } = useSpeakAction(args);
  return (
    <button
      onClick={toggle}
      disabled={!ready}
      aria-label={label}
      title={label}
      className={cn(
        "rounded-md p-1.5 text-ink-secondary transition-opacity hover:bg-raised hover:text-ink disabled:cursor-not-allowed disabled:hover:bg-transparent disabled:hover:text-ink-secondary",
        mine ? "text-accent opacity-100" : "opacity-0 focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100 touch:opacity-100",
        className,
      )}
    >
      {preparing ? <Loader2 {...ACTION_ICON} className="animate-spin" /> : mine ? <Square {...ACTION_ICON} className="fill-current" /> : <Volume2 {...ACTION_ICON} />}
    </button>
  );
}