Skip to content

Sub alertNew

When someone subscribes, they walk into the coffee shop. Their name sits in a tooltip over their head while the barista pours. The OBS source hears Twitch. The TikTok Live Studio link hears a TikTok sub. Preview loops a sample sub.

"use client";

import { useEffect, useRef, useState } from "react";

import { OverlayRoot } from "@/components/stream/overlay-root";
import { useViewerQueue } from "@/components/stream/use-twitch-alerts";
import { STREAM_COPY } from "@/config/stream-copy";
import type { StreamLayout } from "@/config/stream-components";
import { cn } from "@/lib/utils";

const DEFAULTS = STREAM_COPY["sub-alert"];
const FADE_MS = 700;

type Phase = "idle" | "loading" | "ready" | "leaving" | "gone";

export function SubAlert({
  layout,
  preview = false,
  username,
  alertKey,
  demo = false,
}: {
  layout: StreamLayout;
  preview?: boolean;
  username?: string;
  alertKey?: string;
  demo?: boolean;
}) {
  const mobile = layout === "mobile";
  const frame = useRef<HTMLIFrameElement>(null);
  const { name, cycle, finish, replay } = useViewerQueue({
    preview,
    initialName: preview ? username || DEFAULTS.username || "" : username || "",
    demo,
    kind: "sub",
    alertKey,
    platform: layout === "mobile" ? "tiktok" : "twitch",
  });
  const [phase, setPhase] = useState<Phase>(name ? "loading" : "idle");
  const token = `${cycle}:${name}`;
  const [seen, setSeen] = useState(token);
  if (seen !== token) {
    setSeen(token);
    setPhase(name ? "loading" : "idle");
  }
  useEffect(() => {
    if (phase !== "loading") return;
    const timeout = window.setTimeout(() => setPhase("gone"), 12000);
    return () => window.clearTimeout(timeout);
  }, [phase]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (
        event.origin !== location.origin ||
        event.source !== frame.current?.contentWindow ||
        event.data?.type !== "coffee-scene"
      ) {
        return;
      }
      if (event.data.status === "ready") setPhase("ready");
      if (event.data.status === "complete") setPhase("leaving");
      if (event.data.status === "error") setPhase("gone");
    };
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, []);

  useEffect(() => {
    if (phase !== "leaving") return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const timeout = window.setTimeout(() => setPhase("gone"), reduce ? 150 : FADE_MS);
    return () => window.clearTimeout(timeout);
  }, [phase]);

  useEffect(() => {
    if (phase !== "gone") return;
    const wait = window.setTimeout(() => {
      if (preview) replay();
      else finish();
    }, preview ? 700 : 400);
    return () => window.clearTimeout(wait);
  }, [finish, phase, preview, replay]);

  const src = `/coffee/index.html?alert=1&username=${encodeURIComponent(name)}`;

  return (
    <OverlayRoot>
      {phase === "gone" || phase === "idle" ? null : (
        <div
          className={cn(
            "absolute left-1/2 -translate-x-1/2",
            mobile ? "bottom-[8%] w-[86cqw]" : "bottom-[5%] w-[34cqw]",
          )}
        >
          <iframe
            key={`${cycle}-${name}`}
            ref={frame}
            src={src}
            title={`${name} walks into the coffee shop`}
            tabIndex={-1}
            className={cn(
              "pointer-events-none aspect-[5/4] w-full border-0 bg-transparent transition-opacity duration-700 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:duration-150",
              phase === "ready" ? "opacity-100" : "opacity-0",
            )}
          />
        </div>
      )}
    </OverlayRoot>
  );
}

Props

Layout

Desktop 16:9 for OBS, or mobile 9:16 for TikTok Live Studio.

Installation

Sub alert is a browser-source overlay. Copy the URL for OBS or TikTok Live Studio. The live page has no site chrome and a transparent background.

In OBS, add a Browser source, paste the URL, and set the size to 1920 × 1080. Leave the page background transparent.

Usage

example.tsx

import { SubAlert } from "@/components/stream/sub-alert";

export function Overlay() {
  return <SubAlert layout="desktop" username="sozo_fan" preview />;
}

Browser source

Paste this URL into OBS or TikTok Live Studio. The query params match the props below.

browser-source.tsx

// OBS Browser source, 1920×1080, transparent. Leave it open. Twitch sends each subscriber's name.
const src = "https://chandlerking.dev/live/sub-alert?layout=desktop&username=sozo_fan";

The subscriber walks into the coffee shop. Their name stays in a tooltip over their head while the barista pours. Desktop hears a Twitch sub. The TikTok Live Studio link hears a TikTok sub. Preview loops a sample sub.

Props

PropTypeDefaultNotes
usernamestring"sozo_fan"The name in the tooltip over their head. A `username` query plays that name once. After that, Twitch sends the name.
layout"desktop" | "mobile"RequiredCanvas orientation. Desktop is 1920×1080 for OBS. Mobile is 1080×1920 for TikTok Live Studio. Query `layout`.
previewbooleanfalseSite-only helpers: a sample webcam fill, a looping alert, and a stinger replay control. Leave it off on the live route.

Notes & Features

  • One play on stream. Leave the source open. On OBS, Twitch sends the subscriber's name. On the TikTok Live Studio link, a TikTok sub sends it. They walk in with that name over their head, and the shop fades out. The next sub waits its turn.
  • Name tooltip. The tooltip is part of the miniature, so it follows the subscriber as they walk up to the counter.
  • Preview loop. `preview` repeats the walk-in so you can watch it on the site. The live route never loops.

Manual installation

Rather than the browser source, copy Sub alert into a project. Install its dependencies, then copy all 2 files into the matching path.

Source files

src/components/stream/sub-alert.tsx

"use client";

import { useEffect, useRef, useState } from "react";

import { OverlayRoot } from "@/components/stream/overlay-root";
import { useViewerQueue } from "@/components/stream/use-twitch-alerts";
import { STREAM_COPY } from "@/config/stream-copy";
import type { StreamLayout } from "@/config/stream-components";
import { cn } from "@/lib/utils";

const DEFAULTS = STREAM_COPY["sub-alert"];
const FADE_MS = 700;

type Phase = "idle" | "loading" | "ready" | "leaving" | "gone";

export function SubAlert({
  layout,
  preview = false,
  username,
  alertKey,
  demo = false,
}: {
  layout: StreamLayout;
  preview?: boolean;
  username?: string;
  alertKey?: string;
  demo?: boolean;
}) {
  const mobile = layout === "mobile";
  const frame = useRef<HTMLIFrameElement>(null);
  const { name, cycle, finish, replay } = useViewerQueue({
    preview,
    initialName: preview ? username || DEFAULTS.username || "" : username || "",
    demo,
    kind: "sub",
    alertKey,
    platform: layout === "mobile" ? "tiktok" : "twitch",
  });
  const [phase, setPhase] = useState<Phase>(name ? "loading" : "idle");
  const token = `${cycle}:${name}`;
  const [seen, setSeen] = useState(token);
  if (seen !== token) {
    setSeen(token);
    setPhase(name ? "loading" : "idle");
  }
  useEffect(() => {
    if (phase !== "loading") return;
    const timeout = window.setTimeout(() => setPhase("gone"), 12000);
    return () => window.clearTimeout(timeout);
  }, [phase]);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (
        event.origin !== location.origin ||
        event.source !== frame.current?.contentWindow ||
        event.data?.type !== "coffee-scene"
      ) {
        return;
      }
      if (event.data.status === "ready") setPhase("ready");
      if (event.data.status === "complete") setPhase("leaving");
      if (event.data.status === "error") setPhase("gone");
    };
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, []);

  useEffect(() => {
    if (phase !== "leaving") return;
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const timeout = window.setTimeout(() => setPhase("gone"), reduce ? 150 : FADE_MS);
    return () => window.clearTimeout(timeout);
  }, [phase]);

  useEffect(() => {
    if (phase !== "gone") return;
    const wait = window.setTimeout(() => {
      if (preview) replay();
      else finish();
    }, preview ? 700 : 400);
    return () => window.clearTimeout(wait);
  }, [finish, phase, preview, replay]);

  const src = `/coffee/index.html?alert=1&username=${encodeURIComponent(name)}`;

  return (
    <OverlayRoot>
      {phase === "gone" || phase === "idle" ? null : (
        <div
          className={cn(
            "absolute left-1/2 -translate-x-1/2",
            mobile ? "bottom-[8%] w-[86cqw]" : "bottom-[5%] w-[34cqw]",
          )}
        >
          <iframe
            key={`${cycle}-${name}`}
            ref={frame}
            src={src}
            title={`${name} walks into the coffee shop`}
            tabIndex={-1}
            className={cn(
              "pointer-events-none aspect-[5/4] w-full border-0 bg-transparent transition-opacity duration-700 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:duration-150",
              phase === "ready" ? "opacity-100" : "opacity-0",
            )}
          />
        </div>
      )}
    </OverlayRoot>
  );
}

src/components/stream/overlay-root.tsx

import type { ReactNode } from "react";

import { cn } from "@/lib/utils";

export function OverlayRoot({
  children,
  className,
}: {
  children: ReactNode;
  className?: string;
}) {
  return (
    <div
      className={cn(
        "@container relative h-full w-full overflow-hidden pointer-events-none",
        className,
      )}
    >
      {children}
    </div>
  );
}

Carve that warmth into me.

Vinland Saga
Chandler King

Building AnglerIQ & The Sozo CRM

Open to software engineering roles

Crafted by Chandler King · Kansas City, MO