Skip to content

armgit / Piik

Public Imported from GitHub
0

Free, open-source screen sharing for private live streams with friends. Watch together in a browser or self-host Piik. 免费开源的私密屏幕共享,支持游戏直播、一起看电影与自部署。

35.3 KB
Raw Blame
import { useRef, useState } from "react";
import type { VideoFit, VideoRotation } from "../media/video-geometry";
import { BackButton, Btn, Chip, NameTag, Pill, SwitchItem } from "../components/living/primitives";
import { RoomChip, RoomCodePlaceholder, RoomAdmissionBadge } from "../components/living/RoomChip";
import { CaptureSourcePicker, type NativeSourceList } from "../components/living/CaptureSourcePicker";
import { LedStrip } from "../components/living/Header";
import { StageOverlay, StageTv } from "../components/living/Stage";
import { LiveAudioExclusion } from "../components/living/AudioExclusionSelect";
import type { NativeCaptureTarget } from "../native/wire";
import { RoomInteractions } from "../components/living/RoomInteractions";
import { RoomChatOverlay, RoomChatOverlaySettings, RoomChatToggle } from "../components/living/RoomChatOverlay";
import { REACTION_IDS, type ReactionId } from "../../shared/room-interactions";
import { PlaybackControls } from "../components/living/PlaybackControls";
import { BrandMark } from "../components/living/BrandMark";
import { SharingSettings } from "../components/living/SharingSettings";
import { ShareMicrophoneSettings } from "../components/living/ShareMicrophoneSettings";
import { HostShareControls } from "../components/living/HostShareControls";
import { HostRemoteControl } from "../components/living/HostRemoteControl";
import type { RemoteControlMode } from "../remote-control/protocol";
import { LauncherForm, type AppMode } from "../components/living/LauncherForm";
import { AppReleaseNotice } from "../components/living/AppReleaseNotice";
import { useTheaterMode } from "../components/living/use-theater-mode";

import { AudioBitrateControl, PicturePreferenceControl, PictureSettingsSummary, QualityPresets, ResolutionControl, VideoRateControls } from "../components/living/QualityPresets";
import { RoomCodeInput } from "../components/living/RoomCodeInput";
import { MAX_AUDIO_SEND_BITRATE, VIDEO_CAPTURE_LIMITS, QUALITY_PROFILES, captureFramerateCeiling, matchingQualityProfileId, type QualityProfile } from "../media/quality";
import type { loadCameraPreviews } from "../media/camera-previews";
import { Tooltip } from "../components/living/Tooltip";
import { StatusIndicator } from "../components/living/StatusIndicator";
import { deriveParticipantStatus, STATUS_CATALOG } from "../ui/media-status";
import { Glyph } from "../ui/icons";
import { useCopy } from "../ui/copy";
import { PeoplePreview } from "./PeoplePreview";
import { RemoteControlsPreview } from "./RemoteControlsPreview";
import { useRoomVoicePreview } from "./RoomVoicePreview";
import { usePreviewInteractions } from "./use-preview-interactions";
import "./controls-preview.css";

const POSTER = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 360"><rect width="640" height="360" fill="#e8eee6"/><rect x="100" y="60" width="440" height="240" rx="20" fill="#fffdf6"/><path d="M100 100h440" stroke="#c9d7cf" stroke-width="2"/><circle cx="128" cy="81" r="6" fill="#ed9e65"/><circle cx="320" cy="190" r="46" fill="#65b099"/><path d="m310 191 9 9 16-22" fill="none" stroke="#fffdf6" stroke-width="7" stroke-linecap="round" stroke-linejoin="round"/></svg>')}`;
const SOURCES = { kind: "ready", processAudio: true, systemAudio: true, processAudioExclusion: true, captureBorderControl: true, sources: [
  { kind: "window", sourceId: "101", pid: 1, creationTime: "1", title: "Sketchbook" },
  { kind: "window", sourceId: "102", pid: 2, creationTime: "2", title: "A short film" },
  { kind: "window", sourceId: "104", pid: 3, creationTime: "3", title: "Voice call" },
  { kind: "display", sourceId: "103", title: "Display 1" },
] } satisfies NativeSourceList;
const CAMERA_PREVIEWS = [
  { id: "built-in", label: "Built-in camera", preview: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 320"><rect width="180" height="320" fill="#dce9e5"/><rect x="106" y="26" width="58" height="102" rx="7" fill="#fbfcf3"/><path d="M135 26v102M106 76h58" stroke="#b2cbc2" stroke-width="4"/><path d="M36 255q0-100 54-100t54 100" fill="#449986"/><circle cx="90" cy="124" r="29" fill="#449986"/><path d="M81 122v4m18-4v4" stroke="#203c3a" stroke-width="5" stroke-linecap="round"/><path d="M0 259h180v61H0" fill="#d8b898"/><rect x="142" y="241" width="21" height="23" rx="5" fill="#fff7e9"/></svg>')}` },
  { id: "usb", label: "USB Camera", preview: `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 180"><rect width="320" height="180" fill="#e2c5a8"/><path d="M0 25h320M0 157h320" stroke="#cda987" stroke-width="2"/><rect x="53" y="27" width="163" height="124" rx="5" fill="#fffaf0" transform="rotate(-8 135 89)"/><path d="m97 112 30-35 23 25 18-12 18 19" fill="none" stroke="#689b8a" stroke-width="5" stroke-linejoin="round"/><circle cx="166" cy="57" r="11" fill="#ebbd63"/><path d="m245 64 8 77" stroke="#477b73" stroke-width="7" stroke-linecap="round"/><circle cx="266" cy="35" r="19" fill="#f9f5df"/><circle cx="266" cy="35" r="12" fill="#8c6651"/></svg>')}` },
];
const previewCameras: typeof loadCameraPreviews = async (_signal, publish) => publish(CAMERA_PREVIEWS);
const previewSource = async (source: NativeCaptureTarget) => source.sourceId === "101" ? CAMERA_PREVIEWS[1].preview
  : source.sourceId === "102" ? CAMERA_PREVIEWS[0].preview : POSTER;
const previewApplications = async () => SOURCES.sources;

export function ControlsPreview() {
  const { t, lang, vis } = useCopy();
  const en = lang === "en";
  const displayPreview = new URLSearchParams(window.location.search).get("source") === "display";
  const [sound, setSound] = useState(true);
  const [operationNotice, setOperationNotice] = useState(true);
  const [commentary, setCommentary] = useState(false);
  const [commentaryInput, setCommentaryInput] = useState({ deviceId: "", volume: 1, voiceProcessing: true });
  const [excludedAudio, setExcludedAudio] = useState<NativeCaptureTarget | undefined>(SOURCES.sources[2]);
  const [sharingSettings, setSharingSettings] = useState(false);
  const [remoteMode, setRemoteMode] = useState<RemoteControlMode>("off");
  const [quality, setQuality] = useState<QualityProfile>(QUALITY_PROFILES["1080p30"]);
  const [launchMode, setLaunchMode] = useState<AppMode>("link");
  const [majorUpdate, setMajorUpdate] = useState(false);
  const releaseVersion = majorUpdate ? "v3.0.0" : "v2.2.0";
  const releaseURL = `https://github.com/TNTcraftHIM/Piik/releases/tag/${releaseVersion}`;
  const [launchSites, setLaunchSites] = useState(["https://demo.piik.tv"]);
  const [startupSite, setStartupSite] = useState("");
  const [launchPassword, setLaunchPassword] = useState("");
  const [launchLan, setLaunchLan] = useState("192.0.2.10");
  const [policy, setPolicy] = useState<"open" | "private">("open");
  const [roomPassword, setRoomPassword] = useState(false);
  const [inviteAvailable, setInviteAvailable] = useState(true);
  const [includeCredential, setIncludeCredential] = useState(true);
  const roomLink = `https://piik.example/r/9527${includeCredential ? "#v=preview" : ""}`;
  const [paused, setPaused] = useState(false);
  const [passwordVisible, setPasswordVisible] = useState(false);
  const [name, setName] = useState("Piik friend");
  const [invalid, setInvalid] = useState(false);
  const [sourceOpen, setSourceOpen] = useState(displayPreview);
  const [sourceRevision, setSourceRevision] = useState(0);
  const [systemSourcePicker, setSystemSourcePicker] = useState(false);
  const [browserCaptureSupported, setBrowserCaptureSupported] = useState(true);
  const [nativePermissionPreview, setNativePermissionPreview] = useState(false);
  const sourceTargets: NativeCaptureTarget[] = systemSourcePicker
    ? [{ kind: "picker", sourceId: "1", title: "System chooser" }] : SOURCES.sources;
  const [sourceState, setSourceState] = useState<NativeSourceList["kind"] | "refreshing" | "empty">("ready");
  const [captureBorderAvailable, setCaptureBorderAvailable] = useState(true);
  const [showCaptureBorder, setShowCaptureBorder] = useState(false);
  const [roomCode, setRoomCode] = useState("6020");
  const [feedback, setFeedback] = useState("");
  const [dial, setDial] = useState("60");
  const [theater, setTheater] = useTheaterMode();
  const [pictureFit, setPictureFit] = useState<VideoFit>("contain");
  const [pictureRotation, setPictureRotation] = useState<VideoRotation>(0);
  const [viewerRoute, setViewerRoute] = useState<"auto" | "p2p" | "sfu">("auto");
  const video = useRef<HTMLVideoElement>(null);
  const notify = () => setFeedback(en ? "Got it. This is a preview." : "收到,只在预览里演示。" );
  return <>
    <div className="cp-grid" id="control-preview">
      <section id="button-preview" className="cp-card">
        <header><span className="cp-number">01</span><h2>{en ? "Buttons, with a little give" : "按钮,按下去有回应。"}</h2></header>
        <p>{en ? "Hover, press, or use Tab and Enter. The disabled one keeps its explanation." : "悬停、按下,或用 Tab 和回车试试。禁用时也能查看原因。"}</p>
        <div className="cp-tools">
          <BackButton onClick={notify} />
          <Btn icon="cast" tone="primary" title="host.start" cap="host.start" hint="hint-share-start" onClick={notify} />
          <Btn icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />
          <Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
            hint={paused ? "hint-resume" : "hint-pause"} draw="preview-pause" pressed={paused} onClick={() => setPaused(!paused)} />
          <Btn icon="gauge" tone="on" title="host.details.hide" cap="host.details" hint="hint-collapse" pressed onClick={notify} />
          <Btn icon="refresh" title="viewer.reconnect" cap="viewer.reconnect" hint="hint-reconnect" disabled />
          <Btn icon="cast" title="host.starting" cap="host.starting" busy disabled hint="hint-share-start" />
        </div>
        <div className="cp-tools">
          <Btn icon="switchSource" title="host.switchSource" hint="hint-switch-source" onClick={notify} />
          <Btn icon="link" title="host.invite.copy" hint="hint-copy-invite" onClick={notify} />
          <Btn icon="linkOff" title="host.invite.revoke" hint="hint-revoke-invite" onClick={notify} />
          <Btn icon="network" title="host.topology.show" hint="hint-topology" onClick={notify} />
          <Btn icon="sliders" title="host.advanced" hint="hint-advanced" onClick={notify} />
        </div>
        <p>{en ? "The same button family has regular, compact and dense sizes. Quiet actions keep a usable target without a visible frame."
          : "同一按钮族提供常规、紧凑和小尺寸;弱化操作保留点击范围,不强调边框。"}</p>
        <div className="cp-tools">
          {([undefined, "compact", "dense"] as const).map((size, index) => <figure className="cp-control-sample" key={size ?? "regular"}>
            <Btn icon="link" title="host.invite.copy" hint="hint-copy-invite" size={size} onClick={notify} />
            <figcaption>{en ? ["Regular", "Compact", "Dense"][index] : ["常规", "紧凑", "小尺寸"][index]}</figcaption>
          </figure>)}
          <figure className="cp-control-sample">
            <Btn icon="help" title="help.title" hint="hint-help" size="compact" quiet onClick={notify} />
            <figcaption>{en ? "Quiet" : "弱化"}</figcaption>
          </figure>
        </div>
      </section>
      <section id="sharing-preview" className="cp-card cp-sharing-preview">
        <header><h2>{t("host.advanced")}</h2></header>
        <HostShareControls actions={<>
          <Btn icon="switchSource" title="host.switchSource" cap="host.switchSource" hint="hint-switch-source" onClick={notify} />
          </>}
          settings={<Btn icon="sliders" cap="host.settings.button" title={sharingSettings ? "host.advanced.hide" : "host.advanced"}

            hint={sharingSettings ? "hint-collapse" : "hint-advanced"} tone={sharingSettings ? "on" : undefined}
            expanded={sharingSettings} controls="preview-sharing-settings" onClick={() => setSharingSettings(value => !value)} />}
          remote={<HostRemoteControl mode={remoteMode} platform="windows" requests={[]}
            disabled={paused} onPolicy={async mode => setRemoteMode(mode)} onDecide={async () => undefined} />}
          pause={<Btn icon={paused ? "play" : "pause"} title={paused ? "host.resume" : "host.pause"} cap={paused ? "host.resume" : "host.pause"}
            hint={paused ? "hint-resume" : "hint-pause"} onClick={() => setPaused(!paused)} />}
          ending={<Btn id="host-stop-share" icon="stop" tone="danger" title="host.stop" cap="host.stop" hint="hint-share-stop" onClick={notify} />}
        />
        <SharingSettings id="preview-sharing-settings" open={sharingSettings}
          presets={<QualityPresets selected={matchingQualityProfileId(quality)}
            onSelect={id => setQuality(current => ({ ...QUALITY_PROFILES[id], maxAudioBitrate: current.maxAudioBitrate }))} />}
          pictureSummary={<PictureSettingsSummary value={quality} />}
          picture={<><ResolutionControl value={quality.resolution} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
            onChange={resolution => setQuality(current => ({ ...current, resolution,
              maxFramerate: Math.min(current.maxFramerate, captureFramerateCeiling(resolution)),
            }))} />
            <VideoRateControls value={quality} limits={VIDEO_CAPTURE_LIMITS} disabled={false}
              onChange={change => setQuality(current => ({ ...current, ...change }))} />
            <PicturePreferenceControl value={quality.degradationPreference} disabled={false}
              onChange={degradationPreference => setQuality(current => ({ ...current, degradationPreference }))} />
            <div className="lr-door-group">
              <span className="lr-door-glyph"><Glyph name="puzzle" size={19} /><span>{vis ? null : t("host.advanced.codec")}</span></span>
              <div className="lr-row-group" role="group" aria-label={t("host.advanced.codec")}>
                {(["vp8", "auto", "h264"] as const).map(mode => <Chip key={mode} name="videoCodec" value={mode} selected={mode === "auto"} disabled
                  title={mode === "auto" ? t("host.advanced.codec.auto") : mode.toUpperCase()} hint="hint-codec">
                  {mode === "auto" && !vis ? t("host.advanced.codec.auto") : mode.toUpperCase()}
                </Chip>)}
              </div>
            </div>
          </>}
          audio={<>
          <div className="lr-door-group lr-source-audio-settings">
            <SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.systemAudio")}
              hint={sound ? "hint-stop-audio" : "hint-share-audio"} />
            <LiveAudioExclusion load={previewApplications} value={excludedAudio} onChange={setExcludedAudio} disabled={!sound || paused} />
          </div>
          <ShareMicrophoneSettings available enabled={commentary} onEnabled={setCommentary}
            {...commentaryInput} loadDevices={async () => [{ id: "headset", label: "USB Headset" }, { id: "desk", label: "Desk Microphone" }]}
            onVolume={volume => setCommentaryInput(current => ({ ...current, volume }))}
            onDevice={deviceId => setCommentaryInput(current => ({ ...current, deviceId }))}
            onVoiceProcessing={voiceProcessing => setCommentaryInput(current => ({ ...current, voiceProcessing }))} />
          <AudioBitrateControl value={quality.maxAudioBitrate ?? QUALITY_PROFILES["1080p30"].maxAudioBitrate} max={MAX_AUDIO_SEND_BITRATE}
            disabled={false} onChange={maxAudioBitrate => setQuality(current => ({ ...current, maxAudioBitrate }))} />
          </>}
          connection={
            <div className="lr-row-group" role="group" aria-label={t("host.advanced.route")}>
              <SwitchItem checked disabled onChange={notify} label={t("host.advanced.route.topo")}
                note={t("host.advanced.route.topoHint")} hint="hint-topology" />
              <SwitchItem checked={false} disabled onChange={notify} label={t("host.advanced.route.peerOnly")}
                note={t("host.advanced.route.peerOnlyHint")} hint="hint-route-p2p" />
            </div>
          }
        />
      </section>
      <section id="option-preview" className="cp-card">
        <header><span className="cp-number">02</span><h2>{en ? "Pick, toggle, adjust" : "选一个,再拨一下。"}</h2></header>
        <div className="cp-tools">
          <SwitchItem checked={sound} onChange={setSound} label={t("host.sourcePicker.audioOn")} hint="hint-share-audio" />
          <SwitchItem checked disabled locked onChange={() => undefined} label={t("host.advanced.route.peerOnly")}
            note={t("host.advanced.route.peerOnlyRequired")} hint="hint-route-p2p-required" />
          <SwitchItem checked disabled locked onChange={() => undefined} label={t("host.advanced.route.sfuOnly")}
            note={t("host.advanced.route.sfuOnlyHint")} hint="hint-route-sfu" />
        </div>
        <div className="cp-tools lr-row-group" id="admission-preview">
          <span className="lr-toggle" role="group" aria-label={t("host.policy")}>
            {(["open", "private"] as const).map(value => <Tooltip key={value} kind={value === "open" ? "hint-admission-code" : "hint-policy-private"}
              text={vis ? undefined : `${t(`host.policy.${value}`)}\n${t(value === "private" && roomPassword ? "host.policy.privatePasswordHint" : `host.policy.${value}Hint`)}`}>
              <button type="button" className={policy === value ? "is-selected" : undefined} aria-pressed={policy === value}
                aria-label={t(`host.policy.${value}`)} onClick={() => setPolicy(value)}>
                <Glyph name={value === "open" ? "globe" : "lock"} size={19} />{vis ? null : <span className="lr-cap">{t(`host.policy.${value}`)}</span>}
              </button></Tooltip>)}
          </span>
          {!inviteAvailable && <Pill icon="link" tone="off" comic="hint-invite-link"
            label={t(policy === "open" ? "host.invite.emptyOpen" : roomPassword ? "host.invite.emptyPassword" : "host.invite.emptyPrivate")} />}
        </div>
        <div className="cp-tools">
          <SwitchItem checked={roomPassword} onChange={setRoomPassword} label={t("host.password.set")} />
          <SwitchItem checked={inviteAvailable} onChange={setInviteAvailable} label={en ? "Active invitation" : "邀请链接有效"} />
        </div>
        <div className="cp-tools">
          <RoomAdmissionBadge policy="open" passwordEnabled={false} />
          <RoomAdmissionBadge policy="private" passwordEnabled />
          <RoomAdmissionBadge policy="private" passwordEnabled={false} />
        </div>
        {inviteAvailable && <div className="lr-invite-field">
          <Tooltip kind="hint-invite-link" text={roomLink} className="lr-invite-hint">
            <input className="lr-invite-url" readOnly dir="ltr" value={roomLink}
              aria-label={t(includeCredential ? "host.invite" : "host.invite.address")} />
          </Tooltip>
          <span className="lr-row-group"><Glyph name="key" size={17} />
            <SwitchItem checked={includeCredential} onChange={setIncludeCredential}
              label={t("host.invite.includeCredential")} note={t("host.invite.credentialHint")} hint="hint-invite-link" />
          </span>
        </div>}
        {inviteAvailable && !includeCredential && policy === "private" && !roomPassword ? <Pill icon="lock" tone="warn"
          comic="hint-policy-private" label={t("host.invite.credentialRequired")} /> : null}
        <p>{en ? "The website's architecture picker uses the same sliding style with native radio buttons. Arrow keys change the choice."
          : "官网的架构选择也复用滑动样式,使用原生单选项;聚焦后可用方向键切换。"}</p>
        <fieldset className="lr-toggle">
          <legend className="visually-hidden">{en ? "Download architecture" : "下载架构"}</legend>
          <label><input type="radio" name="preview-architecture" value="amd64" defaultChecked /><span>x64</span></label>
          <label><input type="radio" name="preview-architecture" value="arm64" /><span>ARM64</span></label>
        </fieldset>
      </section>
      <section id="input-preview" className="cp-card">
        <header><span className="cp-number">03</span><h2>{en ? "Names, codes and small details" : "名字、房间号,还有小细节。"}</h2></header>
        <div className="cp-tools"><NameTag name={name || "Piik friend"} identity="preview-name" />
          <label className="lr-input"><Glyph name="pencil" size={17} /><input value={name} aria-label={t("host.name")}
            autoComplete="off" onChange={event => setName(event.target.value)} /></label>
        </div>
        <div className="cp-tools">
          <label className="lr-input is-password"><Glyph name="key" size={17} /><input type={passwordVisible ? "text" : "password"}
            placeholder={t("join.password")} aria-label={t("join.password")} aria-invalid={invalid} aria-describedby={invalid ? "preview-input-error" : undefined} autoComplete="off" />
          </label>
          <Btn icon={passwordVisible ? "eyeOff" : "eye"} title={passwordVisible ? "host.password.hide" : "host.password.show"}
            pressed={passwordVisible} hint={passwordVisible ? "hint-password-hide" : "hint-password-show"} onClick={() => setPasswordVisible(!passwordVisible)} />
          <SwitchItem checked={invalid} onChange={setInvalid} label={en ? "Show error" : "看看错误态"} />
        </div>
        {invalid ? <p id="preview-input-error" className="cp-input-error" role="alert">{en ? "That password did not match. Try again." : "密码没对上,再试一次。"}</p> : null}
        <div className="cp-tools"><RoomCodePlaceholder /><RoomCodePlaceholder onCreate={notify} />
          <RoomCodePlaceholder onCreate={notify} disabled busy />
          <RoomChip roomId={roomCode} onReplace={() => setRoomCode(code => code === "6020" ? "2048" : "6020")} /></div>
        <RoomCodeInput value={dial} onChange={setDial} />
      </section>
      <section id="feedback-preview" className="cp-card">
        <header><span className="cp-number">04</span><h2>{en ? "Clear feedback" : "每种反馈,都说清楚。"}</h2></header>
        <div className="cp-tools">
          <LedStrip state="live" label={t("state.signal.connected")} comic="signal-connected" />
          <LedStrip state="busy" label={t("state.signal.connecting")} comic="signal-connecting" />
          <LedStrip state="warn" label={t("state.signal.reconnecting")} comic="signal-recovering" />
          <LedStrip state="off" label={t("state.signal.offline")} comic="signal-offline" />
        </div>
        <div className="cp-tools"><Pill icon="check" tone="live" label={t("common.copied")} comic="hint-copy-code" />
          <Pill icon="lock" label={t("host.advanced.route.peerOnlyRequired")} comic="hint-route-p2p-required" />
          <Pill icon="alert" tone="bad" label={t("common.copyFailed")} comic="warning" /></div>
        <div className="cp-tools">{operationNotice
          ? <Pill icon="check" tone="live" label={t("host.notice.qualityApplied")} comic="hint-quality" onDismiss={() => setOperationNotice(false)} />
          : <button type="button" className="lr-btn is-compact" onClick={() => setOperationNotice(true)}>{en ? "Show operation result" : "显示操作结果"}</button>}</div>
        <div className="cp-tools"><StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "peer", peerId: "preview" }, mediaReady: true }, true)} />
          <StatusIndicator status={deriveParticipantStatus({ upstream: { kind: "none" } }, true)} />
        </div>
        <p className="cp-feedback" aria-live="polite">{feedback || (en ? "Button feedback appears here." : "点一下上面的按钮,回应会出现在这里。")}</p>
      </section>
    </div>
    <PeoplePreview />
    <section id="source-preview" className="cp-section">
      <header className="cp-section-head"><span className="cp-number">06</span><div><h2>{en ? "Choose a picture" : "挑一块画面。"}</h2>
        <p>{en ? "The actual source selector, with sample windows and cameras. Selection only updates this preview." : "正式的画面选择器,放入了示例窗口和摄像头;选择只影响这张预览。"}</p></div></header>
      <div className="cp-tools">{(["ready", "loading", "refreshing", "unavailable", "incompatible", "unsupported", "failed", "empty"] as const).map((value, index) => <Chip key={value}
        title={value} selected={sourceState === value} onClick={() => { setSourceState(value); setSourceOpen(true); }}>
        {en ? ["Available", "Loading", "Refreshing", "App unavailable", "Update needed", "Capture unavailable", "Read failed", "Empty list"][index] : ["正常", "读取中", "刷新中", "App 未连接", "需要更新", "无法采集", "读取失败", "空列表"][index]}</Chip>)}
        <SwitchItem checked={captureBorderAvailable} onChange={setCaptureBorderAvailable}
          label={en ? "Windows border control" : "Windows 边框控制"} />
        <SwitchItem checked={systemSourcePicker} onChange={value => { setSystemSourcePicker(value); setSourceOpen(true); setSourceRevision(value => value + 1); }}
          label={t("host.sourcePicker.tab.picker")} />
        <SwitchItem checked={browserCaptureSupported} onChange={setBrowserCaptureSupported}
          label={en ? "Browser screen capture" : "浏览器录屏"} />
        <a className="lr-btn" href="/__tooltip-preview?source=display#source-preview" onClick={() => {
          // The same URL does not remount the picker or reset its selected tab.
          setSourceState("ready"); setSourceOpen(true); setSourceRevision(value => value + 1);
        }}>
          <Glyph name="speakerOff" size={18} />{t("host.sourcePicker.excludeAudio")}
        </a>
      </div>
      <div className="cp-stage"><StageTv hasEntry label={t("host.sourcePicker.title")}>
        <img className="cp-poster" src={POSTER} alt="" />
        {sourceOpen ? <CaptureSourcePicker key={sourceRevision} nativeSources={sourceState === "empty" ? { ...SOURCES, sources: [], captureBorderControl: captureBorderAvailable }
          : sourceState === "ready" ? systemSourcePicker
            ? { ...SOURCES, sources: sourceTargets, processAudio: false, processAudioExclusion: false, captureBorderControl: false }
            : { ...SOURCES, captureBorderControl: captureBorderAvailable }
          : sourceState === "refreshing" ? { kind: "loading", appDetected: true, sources: sourceTargets } : { kind: sourceState }}
          initialShowCaptureBorder={showCaptureBorder}
          browserSupported={browserCaptureSupported}
          initialTab={displayPreview ? "display" : "window"}
          onBrowser={() => { setSourceOpen(false); notify(); }}
          onCamera={() => { setSourceOpen(false); notify(); }}
          loadCameras={previewCameras}
          onNative={(_target, _audio, showBorder) => { setShowCaptureBorder(showBorder); setSourceOpen(false); notify(); }}
          onPreview={previewSource} onRefresh={() => setSourceState("refreshing")} onCancel={() => setSourceOpen(false)} />
          : <div className="cp-stage-action"><Btn icon="cast" tone="primary" title="host.start" cap="host.start" hint="hint-share-start" onClick={() => setSourceOpen(true)} /></div>}
      </StageTv></div>
    </section>
    <section id="playback-preview" className="cp-section">
      <header className="cp-section-head"><span className="cp-number">07</span><div><h2>{en ? "The playback bar" : "播放时,顺手就能找到。"}</h2>
        <p>{en ? "This bar shows its waiting state. The playback test page includes a moving picture, volume and picture in picture." : "这里展示等待画面时的播放栏;动态画面、音量和小窗可进入完整播放预览试用。"}</p></div></header>
      <div className={theater ? "lr-room is-theater" : "cp-stage"}><div className="lr-scene"><StageTv label={t("playback.controls")} indicator={<StatusIndicator status={STATUS_CATALOG.joining} />}>
        <video ref={video} poster={POSTER} playsInline inert style={{ objectFit: pictureFit }} />
        <StageOverlay dim waiting icon={STATUS_CATALOG.joining.icon} message={t(STATUS_CATALOG.joining.labelKey)} comic={STATUS_CATALOG.joining.comic} />
        <PlaybackControls videoRef={video} stream={null} canPlay={false} theaterMode={theater} onPlay={notify}
          settings={{ pictureFit, setPictureFit, pictureRotation, setPictureRotation, route: { preference: viewerRoute, onChange: setViewerRoute,
            sfuAvailable: true, sfuOnly: false, peerOnly: false, disabled: false, rejected: false } }}
          onToggleTheater={() => setTheater(!theater)} onReconnect={notify} reconnectAvailable />
      </StageTv></div></div>
      <p><a href="/__playback-preview">{en ? "Open the full playback preview" : "进入完整播放预览"} →</a></p>
      <SwitchItem checked={nativePermissionPreview} onChange={setNativePermissionPreview}
        label={t("native.confirmInApp")} />
      {nativePermissionPreview && <div className="cp-stage"><StageTv label={t("native.confirmInApp")}>
        <StageOverlay icon="window" comic="source-starting" tone="busy" message={t("native.confirmInApp")}
          onActivate={() => { setNativePermissionPreview(false); notify(); }} />
      </StageTv></div>}
    </section>
    <section id="launcher-preview" className="cp-section">
      <header className="cp-section-head"><span className="cp-number">08</span><h2>{t("client.launch.title")}</h2></header>
      <div className="cp-tools">
        <button className="lr-btn" type="button" aria-pressed={majorUpdate} onClick={() => setMajorUpdate(value => !value)}>
          {en ? "Preview major update" : "预览跨大版本更新"}
        </button>
        <SwitchItem checked={launchSites.length > 1} label={en ? "Many approved sites" : "多个已授权站点"}
          onChange={many => { setLaunchSites(many ? ["https://demo.piik.tv", "https://friends.example.org", "https://screen-sharing-with-friends.preview.example.org:8443", "https://movie-night.example.net", "https://192.0.2.10:8787", "https://weekend-games.example.org"] : ["https://demo.piik.tv"]); setStartupSite(""); }} />
        <SwitchItem checked={launchSites.length === 0} label={en ? "No approved sites" : "尚未授权站点"}
          onChange={empty => { setLaunchSites(empty ? [] : ["https://demo.piik.tv"]); setStartupSite(""); }} />
      </div>
      <div className="lr-client-launch">
        <LauncherForm mode={launchMode} onModeChange={setLaunchMode}
          startupSite={startupSite} onToggleStartupSite={site => setStartupSite(value => value === site ? "" : site)}
          sites={launchSites} onSelectSite={notify} onOpen={event => { event.preventDefault(); notify(); }}
          onRemoveSite={site => { setLaunchSites(sites => sites.filter(value => value !== site)); if (startupSite === site) setStartupSite(""); }}
          lan={{ selected: launchLan, onChange: setLaunchLan, addresses: [
            { address: "192.0.2.10", name: "Wi-Fi" },
            { address: "192.0.2.20", name: "vEthernet (Example Virtual Network Adapter with a Long Name)" },
          ] }}
          localAccessPassword={launchPassword} onLocalAccessPasswordChange={setLaunchPassword}
          onSubmit={event => event.preventDefault()}>
          <AppReleaseNotice update={{ kind: majorUpdate ? "major-update" : "update-available",
            version: releaseVersion, revision: null,
            url: `https://github.com/TNTcraftHIM/Piik/releases/download/${releaseVersion}/piik-app-windows-amd64.zip`,
            releaseURL }} />
        </LauncherForm>
      </div>
    </section>
    <section id="interaction-preview" className="cp-section">
      <header className="cp-section-head"><span className="cp-number">09</span><div><h2>{en ? "A little company" : "聊两句,丢个番茄。"}</h2>
        <p>{en ? "Chat, reactions and room voice share one window. This catalogue simulates voice controls without opening your microphone." : "聊天、表情与房间语音共用一个窗口。这里的语音控件仅作演示,不会打开麦克风。"}</p></div></header>
      <InteractionControlsPreview />
    </section>
    <RemoteControlsPreview />
    <section id="brand-preview" className="cp-section">
      <header className="cp-section-head"><span className="cp-number">11</span><h2>{en ? "Brand motion" : "Mascot 动画"}</h2></header>
      <div className="cp-tools">
        {(["static", "once", "loop"] as const).map(motion => <figure className="cp-control-sample" key={motion}>
          <BrandMark size={88} motion={motion} />
          <figcaption>{motion === "static" ? en ? "Static" : "静态"
            : motion === "once" ? en ? "Hover to replay" : "悬停重播" : en ? "Loop" : "循环"}</figcaption>
        </figure>)}
      </div>
    </section>
  </>;
}

function InteractionControlsPreview() {
  const [viewer, setViewer] = useState(false);
  const { session, receiveSample } = usePreviewInteractions(viewer);
  const [crowded, setCrowded] = useState(false);
  const voice = useRoomVoicePreview(viewer, crowded);
  const [reaction, setReaction] = useState<ReactionId>("heart");
  const [theater, setTheater] = useTheaterMode();
  const video = useRef<HTMLVideoElement>(null);
  const { t, lang } = useCopy();
  return <><div className="cp-tools">
    <SwitchItem checked={viewer} onChange={setViewer} label={lang === "en" ? "Viewer perspective" : "观众视角"} />
    <SwitchItem checked={crowded} onChange={setCrowded} label={lang === "en" ? "20 viewers" : "20 位观众"} />
    <button type="button" className="lr-btn" onClick={() => receiveSample({
      kind: "chat", text: lang === "en" ? "I'm here. Save me a seat!" : "来了,给我留个位置!",
    })}><Glyph name="chat" size={18} />{lang === "en" ? "Receive a sample message" : "模拟收到消息"}</button>
    <label className="lr-input cp-reaction-select"><span>{lang === "en" ? "Reaction" : "表情"}</span>
      <select value={reaction} onChange={event => setReaction(event.target.value as ReactionId)}>
        {REACTION_IDS.map(id => <option key={id} value={id}>{t(`interaction.reaction.${id}`)}</option>)}
      </select>
    </label>
    <button type="button" className="lr-btn" onClick={() => receiveSample({ kind: "reaction", reaction,
      targetPeerId: crowded ? "preview-friend-1" : viewer ? "preview-friend" : "preview-host",
    })}><Glyph name="smile" size={18} />{lang === "en" ? "Receive a reaction" : "模拟收到表情"}</button>
  </div><div className={theater ? "lr-room is-theater" : "cp-interaction-room"}><div className="lr-scene">
  <StageTv label={t("interaction.title")} indicator={<StatusIndicator status={STATUS_CATALOG.connected} />}>
    <video ref={video} poster={POSTER} playsInline />
    <RoomChatOverlay session={session} visible />
    <PlaybackControls videoRef={video} stream={null} canPlay={false} onPlay={() => {}}
      theaterMode={theater} onToggleTheater={() => setTheater(value => !value)} onReconnect={() => {}} reconnectAvailable={false}
      overlayAction={<RoomChatToggle session={session} />}
      overlaySettings={session && <RoomChatOverlaySettings session={session} />} />
  </StageTv><RoomInteractions session={session} voice={voice} voiceState={voice.room}
    view={viewer ? "viewer" : "host"} host={{ key: "preview-host", name: "Piik", you: !viewer }} entries={
      Array.from({ length: crowded ? 20 : 1 }, (_, index) => ({
        key: index ? `preview-friend-${index}` : "preview-friend", name: index ? `Friend ${index + 1}` : "Piik friend",
        you: viewer && index === 0,
        status: deriveParticipantStatus({ upstream: { kind: "peer", peerId: "preview-host" }, mediaReady: true }, true),
      }))
    } /></div></div></>;
}