Files
piik/src/client/components/living/CaptureSourcePicker.tsx
T
AAA 3b55934178 fix(capture): link source failures to their shared diagnosis
Let the source picker read its message and help destination from the existing error owner. App response timeouts point to connection help; enumeration failures retain capture help. Controlled WebSocket and real React picker checks preserve active sharing and App authorization during request-scoped failures.
2026-11-24 22:54:56 -05:00

496 lines
23 KiB
TypeScript

import type { NativeCaptureSelection } from "../../native/capture-selection";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import type { NativeCaptureTarget } from "../../native/wire";
import { ChannelDiagnosisHelp } from "../../channel/components/ChannelDiagnosisHelp";
import { diagnoseChannelFact } from "../../channel/diagnosis";
import { channelErrorPresentation } from "../../channel/error-presentation";
import { audioApplicationKey, audioApplications, nativeCaptureTargetKey } from "../../native/capture-selection";
import { useCopy } from "../../ui/copy";
import { Glyph, type GlyphName } from "../../ui/icons";
import { navigateTabs } from "../../ui/tab-navigation";
import { Tooltip } from "./Tooltip";
import { HintComic } from "./hints";
import { Btn, Pill } from "./primitives";
import { AudioDeviceSelect } from "./AudioDeviceSelect";
import { CameraSources, useCameraSources } from "./CameraSources";
import { CaptureSourceCard } from "./CaptureSourceCard";
import { WrappingSegmentedControl } from "./WrappingSegmentedControl";
import { AudioExclusionSelect } from "./AudioExclusionSelect";
import type { loadCameraPreviews } from "../../media/camera-previews";
const SOURCE_TABS = ["browser", "camera", "window", "display", "picker", "external"] as const;
type SourceTab = (typeof SOURCE_TABS)[number];
const SOURCE_ICONS = {
browser: "globe",
window: "window",
display: "display",
camera: "camera",
picker: "share",
external: "cast",
} satisfies Record<SourceTab, GlyphName>;
export type NativeSourceList =
| { kind: "browser" }
| { kind: "loading"; appDetected?: boolean; sources?: NativeCaptureTarget[] }
| { kind: "unavailable" }
| { kind: "incompatible" }
| { kind: "unsupported" }
| { kind: "failed"; error?: string; sources?: NativeCaptureTarget[] }
| {
kind: "ready";
sources: NativeCaptureTarget[];
processAudio: boolean;
systemAudio: boolean;
renderEndpoints?: { id: string; label: string }[] | null;
processAudioExclusion?: boolean;
captureBorderControl?: boolean;
};
export function RenderEndpointSelect({ devices, value, disabled, onChange, onRefresh }: {
devices: { id: string; label: string }[] | null; value?: string; disabled?: boolean;
onChange: (id?: string) => void; onRefresh: () => void;
}) {
return <AudioDeviceSelect output label="host.sourcePicker.renderEndpoint" value={value ?? ""}
list={{ status: devices === null ? "failed" : "ready", devices: devices ?? [] }}
disabled={disabled} onChange={id => onChange(id || undefined)} onRefresh={onRefresh} />;
}
export function nativeAppDetected(sources: NativeSourceList | null): boolean {
return sources?.kind === "loading" ? sources.appDetected === true
: sources !== null && sources.kind !== "browser" && sources.kind !== "unavailable";
}
export function CaptureSourcePicker({
nativeSources,
roomName,
onBrowser,
onWatch,
onCamera,
onNative,
onExternalInput,
onPreview,
onRefresh,
onCancel,
browserSupported = true,
cameraSupported = true,
initialTab = "window",
initialCamera = "",
activeCameraVideo,
loadCameras,
initialAudio = true,
initialShowCaptureBorder = false,
initialExcludeAudio,
initialRenderEndpointId,
audioLocked = false,
selectionDisabled = false,
}: {
nativeSources: NativeSourceList;
roomName?: string;
onBrowser: () => void;
onWatch?: () => void;
onCamera?: (deviceId: string) => void;
initialCamera?: string;
activeCameraVideo?: HTMLVideoElement | null;
loadCameras?: typeof loadCameraPreviews;
onNative: (selection: NativeCaptureSelection) => void;
onExternalInput?: () => void;
onPreview: (
target: NativeCaptureTarget,
signal?: AbortSignal,
) => Promise<string | null>;
onRefresh: () => void;
onCancel: () => void;
browserSupported?: boolean;
cameraSupported?: boolean;
initialTab?: SourceTab;
initialAudio?: boolean;
initialShowCaptureBorder?: boolean;
initialRenderEndpointId?: string;
initialExcludeAudio?: NativeCaptureTarget;
audioLocked?: boolean;
selectionDisabled?: boolean;
}) {
const { t } = useCopy();
const pickerId = useId();
const panelRef = useRef<HTMLDivElement>(null);
const bodyRef = useRef<HTMLDivElement>(null);
const [tab, setTab] = useState<SourceTab | null>(null);
const [shareAudio, setShareAudio] = useState(initialAudio);
const [showCaptureBorder, setShowCaptureBorder] = useState(initialShowCaptureBorder);
const [renderEndpointId, setRenderEndpointId] = useState(initialRenderEndpointId);
const [excludeAudio, setExcludeAudio] = useState(initialExcludeAudio);
const appDetected = nativeAppDetected(nativeSources);
// Retained targets classify tabs during refresh and failure. Only ready targets are selectable.
const targets = "sources" in nativeSources ? nativeSources.sources : undefined;
const pickerOnly = !!targets?.length && targets.every(target => target.kind === "picker");
const tabs = SOURCE_TABS.filter(value => value === "browser" ? browserSupported || !!onWatch
: value === "external" ? !!onExternalInput
: value === "camera" ? cameraSupported
: value === "picker" ? pickerOnly
: !pickerOnly && (appDetected || nativeSources.kind === "loading"));
const requestedTab = tab ?? initialTab;
const preferredTab = pickerOnly && (requestedTab === "window" || requestedTab === "display") ? "picker" : requestedTab;
const tabAvailable = (value: SourceTab) => value !== "camera" || !!onCamera;
const activeTab = tabs.includes(preferredTab) && tabAvailable(preferredTab)
? preferredTab : tabs.find(tabAvailable) ?? tabs[0];
const nativeTab = activeTab === "window" || activeTab === "display" || activeTab === "picker";
const retryNativeTab = nativeSources.kind === "unavailable" &&
(requestedTab === "window" || requestedTab === "display" || requestedTab === "picker");
useEffect(() => { bodyRef.current?.scrollTo({ top: 0 }); }, [activeTab]);
const browserCapture = activeTab === "browser";
const cameraSources = useCameraSources(activeTab === "camera" && !!onCamera, activeCameraVideo, loadCameras);
const supportsCaptureBorder = nativeTab && nativeSources.kind === "ready" && nativeSources.captureBorderControl === true;
const issueKey = !nativeTab ? null : nativeSources.kind === "incompatible" ? "native.incompatible"
: (nativeSources.kind === "unsupported" || nativeSources.kind === "failed")
? `host.sourcePicker.${nativeSources.kind}` as const
: null;
const nativeFailure = nativeTab && nativeSources.kind === "failed" ? nativeSources.error : undefined;
const nativeDiagnosis = nativeFailure ? diagnoseChannelFact({ area: "error", code: nativeFailure }) : null;
const issueMessage = nativeDiagnosis ? t(nativeDiagnosis.message)
: nativeFailure ? channelErrorPresentation(nativeFailure, t, "host.sourcePicker.failed").message
: issueKey ? t(issueKey) : null;
useEffect(() => {
const cancelOnEscape = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing ||
panelRef.current?.querySelector('[popover="auto"]:popover-open') ||
!panelRef.current?.contains(event.target as Node | null)) return;
event.preventDefault();
onCancel();
};
window.addEventListener("keydown", cancelOnEscape);
return () => window.removeEventListener("keydown", cancelOnEscape);
}, [onCancel]);
const sources =
nativeTab && nativeSources.kind === "ready"
? nativeSources.sources.filter(
(target) => target.kind === activeTab || target.kind === "picker",
)
: [];
const supportsAudio = (target: NativeCaptureTarget): boolean =>
nativeSources.kind === "ready" &&
(target.kind === "window"
? nativeSources.processAudio
: nativeSources.systemAudio);
const anyNativeAudio = sources.some(supportsAudio);
// Source enumeration already owns process identity; do not create a second app scanner.
const applications = nativeSources.kind === "ready" ? audioApplications(nativeSources.sources) : [];
const exclusionKey = excludeAudio ? audioApplicationKey(excludeAudio) : "";
const canExcludeAudio = activeTab === "display" && nativeSources.kind === "ready" && nativeSources.processAudioExclusion;
const missingExclusion = !!excludeAudio && !applications.some(target => audioApplicationKey(target) === exclusionKey);
const exclusionUnavailable = activeTab === "display" && shareAudio && !!excludeAudio && (!canExcludeAudio || missingExclusion);
const refreshing = activeTab === "camera" ? cameraSources.busy : nativeSources.kind === "loading";
const refreshLabel = t(refreshing ? "host.sourcePicker.loading" : "host.sourcePicker.refresh");
const audioAction = t(!anyNativeAudio ? "host.noAudio" : audioLocked
? "host.sourcePicker.audioLocked"
: shareAudio ? "host.sourcePicker.audioOff" : "host.sourcePicker.audioOn");
const audioLabel = t(
activeTab === "window" && sources.some((target) => target.kind === "window")
? "host.sourcePicker.windowAudio"
: "host.sourcePicker.systemAudio",
);
const audioSwitch = (
<button
type="button"
className="lr-switch"
role="switch"
aria-checked={shareAudio && anyNativeAudio}
aria-label={audioLabel}
disabled={audioLocked || !anyNativeAudio}
onClick={() => setShareAudio((current) => !current)}
/>
);
return (
<div
ref={panelRef}
className="lr-tv-overlay lr-source-picker"
role="dialog"
aria-labelledby={`${pickerId}-title`}
aria-describedby={roomName ? `${pickerId}-room` : undefined}
onKeyDown={event => {
if (event.key !== "Tab" || event.defaultPrevented || event.nativeEvent.isComposing) return;
// This TV-local task keeps its keyboard loop without making the room
// modal; pointer users can still reach the surrounding room controls.
const controls = [...event.currentTarget.querySelectorAll<HTMLElement>(
'button, input, select, textarea, a[href], summary, [tabindex]',
)].filter(element => element.tabIndex >= 0 && !element.matches(":disabled") && element.getClientRects().length);
const next = event.shiftKey && event.target === controls[0] ? controls.at(-1)
: !event.shiftKey && event.target === controls.at(-1) ? controls[0] : undefined;
if (next) { event.preventDefault(); next.focus(); }
}}
>
<div className="lr-source-picker-panel">
<header className="lr-source-picker-head">
<span className="lr-source-picker-mark" aria-hidden="true">
<Glyph name="window" size={22} draw="capture-source" />
</span>
<span className="lr-source-picker-copy">
<strong id={`${pickerId}-title`}>{t("host.sourcePicker.title")}</strong>
{roomName && <small id={`${pickerId}-room`}>{roomName}</small>}
</span>
{activeTab === "camera" || nativeTab || retryNativeTab ? <Btn
icon="refresh" size="dense" className="lr-source-picker-refresh" title={{ text: refreshLabel }}
disabled={refreshing} busy={refreshing} onClick={activeTab === "camera" ? cameraSources.refresh : onRefresh}
hint="hint-refresh-sources" hintTone={refreshing ? "busy" : undefined}
hintMotion={refreshing ? "progress" : undefined} hintPlace="below" hintAlign="end" /> : null}
<Btn icon="x" size="dense" quiet className="lr-source-picker-close" title="common.cancel"
onClick={onCancel} autoFocus hint="hint-close" hintPlace="below" hintAlign="end" />
</header>
{tabs.length > 0 && <WrappingSegmentedControl
className="lr-source-picker-tabs"
role="tablist"
aria-label={t("host.sourcePicker.title")}
onKeyDown={navigateTabs}
>
{tabs.map((value) => {
const button = (
<button
type="button"
role="tab"
id={`${pickerId}-${value}`}
className={activeTab === value ? "is-selected" : undefined}
data-source-tab={value}
aria-controls={`${pickerId}-panel`}
aria-selected={activeTab === value}
aria-label={t(`host.sourcePicker.tab.${value}`)}
tabIndex={activeTab === value ? 0 : -1}
disabled={!tabAvailable(value)}
onClick={() => setTab(value)}
>
<Glyph
name={SOURCE_ICONS[value]}
size={20}
draw={`source-tab-${value}`}
/>
<span>{t(`host.sourcePicker.tab.${value}`)}</span>
</button>
);
return (
<Tooltip
key={value}
kind={value === "external" || value === "picker" ? "hint-source-picker" : `hint-capture-${value}`}
text={t(value === "browser" ? "host.sourcePicker.browserHint"
: value === "camera" ? "host.sourcePicker.cameraHint" : `host.sourcePicker.tab.${value}`)}
place="below"
>
{button}
</Tooltip>
);
})}
</WrappingSegmentedControl>}
<div
ref={bodyRef}
className="lr-source-picker-body"
role={activeTab ? "tabpanel" : undefined}
id={`${pickerId}-panel`}
aria-labelledby={activeTab ? `${pickerId}-${activeTab}` : undefined}
>
{nativeTab &&
nativeSources.kind === "ready" &&
(supportsCaptureBorder || sources.length > 0) ? (
<div className="lr-source-picker-options">
{supportsCaptureBorder ? (
<div className="lr-source-picker-option">
<span aria-hidden="true"><Glyph name="window" size={19} /></span>
<span>{t("host.sourcePicker.showCaptureBorder")}</span>
<Tooltip kind={showCaptureBorder ? "hint-hide-capture-border" : "hint-show-capture-border"}
text={t("host.sourcePicker.showCaptureBorderHint")} place="below">
<button
type="button"
className="lr-switch"
role="switch"
aria-checked={showCaptureBorder}
aria-label={t("host.sourcePicker.showCaptureBorder")}
aria-description={t("host.sourcePicker.showCaptureBorderHint")}
onClick={() => setShowCaptureBorder((current) => !current)}
/>
</Tooltip>
</div>
) : null}
{sources.length > 0 ? (
<div className="lr-source-picker-option">
<span aria-hidden="true">
<Glyph name="speaker" size={19} />
</span>
<span>{audioLabel}</span>
<Tooltip
kind={!anyNativeAudio ? "no-audio" : audioLocked
? (shareAudio ? "hint-share-audio-fixed" : "hint-silent-share-fixed")
: shareAudio ? "hint-stop-audio" : "hint-share-audio"}
text={`${audioAction}\n${t("host.sourcePicker.audioHint")}`}
place="below"
>
{audioSwitch}
</Tooltip>
</div>
) : null}
{activeTab === "display" && shareAudio && !excludeAudio && nativeSources.kind === "ready" && nativeSources.renderEndpoints !== undefined &&
<RenderEndpointSelect onRefresh={onRefresh} devices={nativeSources.renderEndpoints} value={renderEndpointId} disabled={selectionDisabled} onChange={setRenderEndpointId} />}
{activeTab === "display" && shareAudio && anyNativeAudio && !renderEndpointId && (canExcludeAudio || excludeAudio) ? (
<details className="lr-source-exclusion" onToggle={event => {
if (event.currentTarget.open) event.currentTarget.scrollIntoView({ block: "nearest" });
}}>
<summary>
<Glyph name="speakerOff" size={18} />
<span>{t("host.sourcePicker.excludeAudio")}{excludeAudio ? `: ${excludeAudio.title}` : ""}</span>
<Glyph name="chevron" size={14} />
</summary>
<AudioExclusionSelect sources={canExcludeAudio ? applications : []} value={excludeAudio}
showLabel={false} disabled={selectionDisabled} onChange={setExcludeAudio} />
</details>
) : null}
</div>
) : null}
{activeTab === "camera" ? <CameraSources {...cameraSources} selected={initialCamera}
disabled={selectionDisabled || !onCamera} onSelect={id => {
cameraSources.cancel();
onCamera?.(id);
}} /> : <>
<div className="lr-source-picker-list" data-tooltip-controls>
{browserCapture ? (
<button
type="button"
className="lr-source-option is-action"
aria-label={t("host.sourcePicker.browser")}
disabled={selectionDisabled || !browserSupported}
onClick={onBrowser}
>
<span className="lr-source-option-icon" aria-hidden="true">
<Glyph name={SOURCE_ICONS.browser} size={23} />
</span>
<span className="lr-source-option-copy">
<strong>{t("host.sourcePicker.browser")}</strong>
<small>{t("host.sourcePicker.browserHint")}</small>
</span>
</button>
) : null}
{browserCapture && onWatch && <button type="button" className="lr-source-option is-action"
disabled={selectionDisabled} onClick={onWatch} aria-label={t("watch.start")}>
<span className="lr-source-option-icon" aria-hidden="true"><Glyph name="play" size={23} /></span>
<span className="lr-source-option-copy"><strong>{t("watch.start")}</strong><small>{t("watch.sourceHint")}</small></span>
</button>}
{nativeTab && !browserCapture
? sources.map((target) => (
<CaptureSourceOption
key={nativeCaptureTargetKey(target)}
target={target}
disabled={
selectionDisabled || exclusionUnavailable || (audioLocked && shareAudio && !supportsAudio(target))
}
onPreview={onPreview}
onSelect={() =>
onNative({ target, audio: shareAudio && supportsAudio(target), showCaptureBorder: supportsCaptureBorder && showCaptureBorder,
excludeAudio: target.kind === "display" ? excludeAudio : undefined,
renderEndpointId: target.kind === "display" ? renderEndpointId : undefined })
}
/>
))
: null}
</div>
</>}
{activeTab === "external" && onExternalInput && <div className="lr-source-picker-list" data-tooltip-controls><Tooltip kind="hint-source-picker"
text={t("host.sourcePicker.externalHint")} className="lr-source-option-hint"><button type="button" className="lr-source-option is-action"
aria-label={t("host.sourcePicker.externalAction")} disabled={selectionDisabled} onClick={onExternalInput}>
<span className="lr-source-option-icon" aria-hidden="true"><Glyph name="cast" size={23} /></span>
<span className="lr-source-option-copy"><strong>{t("host.sourcePicker.externalAction")}</strong><small>{t("host.sourcePicker.externalHint")}</small></span>
</button></Tooltip></div>}
{retryNativeTab && <p className="lr-source-picker-status" role="status">{t("channel.error.appDisconnected")}</p>}
{nativeTab && nativeSources.kind === "loading" ? (
<span className="lr-source-picker-status" role="status" aria-label={t("host.sourcePicker.loading")}>
<Glyph name="refresh" className="lr-spin" size={18} />{t("host.sourcePicker.loading")}
</span>
) : issueMessage ? (
<Pill icon="alert" label={issueMessage} comic="warning" />
) : browserCapture || activeTab === "camera" || activeTab === "external" ? null : sources.length === 0 ? (
<span
className="lr-source-picker-status"
role="status"
aria-label={t(activeTab ? "host.sourcePicker.empty" : "host.capture.noSource")}
>
<HintComic kind="hint-no-sources" size={240} />
{t(activeTab ? "host.sourcePicker.empty" : "host.capture.noSource")}
</span>
) : null}
{nativeTab && (nativeSources.kind === "failed" || (nativeSources.kind === "ready" && sources.length === 0)) &&
<ChannelDiagnosisHelp diagnosis={nativeDiagnosis ?? { topic: "capture" }} />}
</div>
</div>
</div>
);
}
function CaptureSourceOption({
target,
disabled,
onPreview,
onSelect,
}: {
target: NativeCaptureTarget;
disabled: boolean;
onPreview: (
target: NativeCaptureTarget,
signal?: AbortSignal,
) => Promise<string | null>;
onSelect: () => void;
}) {
const { t } = useCopy();
const buttonRef = useRef<HTMLButtonElement | null>(null);
const previewRequestRef = useRef<AbortController | null>(null);
const [preview, setPreview] = useState<string | null>(null);
const requestPreview = useCallback(() => {
if (target.kind === "picker" || previewRequestRef.current) return;
const request = new AbortController();
previewRequestRef.current = request;
void onPreview(target, request.signal).then((value) => {
if (!request.signal.aborted && value) setPreview(value);
});
}, [onPreview, target]);
useEffect(
() => () => {
previewRequestRef.current?.abort();
previewRequestRef.current = null;
},
[],
);
useEffect(() => {
const button = buttonRef.current;
if (!button || typeof IntersectionObserver === "undefined") return;
const observer = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
requestPreview();
observer.disconnect();
}
});
observer.observe(button);
return () => observer.disconnect();
}, [requestPreview]);
const title =
target.kind === "picker" ? t("host.sourcePicker.system") : target.title;
const action =
target.kind === "picker"
? t("host.sourcePicker.systemAction")
: t(
target.kind === "display"
? "host.sourcePicker.display"
: "host.sourcePicker.window",
{ title },
);
return <CaptureSourceCard title={title} action={action}
icon={target.kind === "picker" ? "share" : target.kind}
hint={target.kind === "picker" ? "hint-source-picker" : target.kind === "display" ? "hint-capture-display" : "hint-capture-window"}
preview={target.kind === "picker" ? undefined : preview} nativeKey={nativeCaptureTargetKey(target)} buttonRef={buttonRef}
disabled={disabled} onPreview={requestPreview} onSelect={onSelect} />;
}