import {
getMidsceneRecorderEventDescription,
getMidsceneRecorderSemantic,
} from '@midscene/shared/recorder';
import { useTextTruncation } from '@midscene/visualizer';
import { Tooltip } from 'antd';
import {
type ReactNode,
type RefObject,
useEffect,
useRef,
useState,
} from 'react';
import type {
StudioRecordedEvent,
StudioRecordingSession,
} from '../../recorder/types';
import { StudioModeTab } from '../../recorder/types';
import {
StudioTimelineEmptyState,
StudioTimelinePanel,
} from '../StudioTimelinePanel';
import {
RecorderButtonIcon,
RecorderGenerateNaturalLanguageIcon,
RecorderScreenshotIcon,
} from './assets/recorder-icons';
interface RecorderFloatingPanelProps {
canStartRecording: boolean;
canGenerateMarkdown: boolean;
error?: string | null;
isMarkdownGenerating: boolean;
isRecording: boolean;
isStoppingRecording: boolean;
onGenerateMarkdown: () => void;
onShowScreenshots: () => void;
onToggleCollapsed: () => void;
onToggleRecording: () => void;
recorderPanelEvents: StudioRecordedEvent[];
recorderPanelSession: StudioRecordingSession | null;
showExpandedDetail: boolean;
timelineCollapsed: boolean;
statusText: string;
detailView: ReactNode;
}
function RecorderFloatingTimeline({
events,
isRecording,
}: {
events: StudioRecordedEvent[];
isRecording: boolean;
}) {
if (events.length === 0 && !isRecording) {
return (
);
}
return (
{events.map((event, index) => (
-
))}
);
}
function StudioTimelineEventCopy({ event }: { event: StudioRecordedEvent }) {
const tooltip = getStudioTimelineEventTooltip(event);
const { ref, truncated } = useTextTruncation(
tooltip,
'multi-line',
);
const copy = (
);
return truncated ? {copy} : copy;
}
function StudioTimelineTargetIcon() {
return (
);
}
function StudioTimelineScrollIcon() {
return (
);
}
function getStudioTimelineEventType(event: StudioRecordedEvent) {
return (event.actionType || event.type || '').toLowerCase();
}
function StudioTimelineEventIcon({ event }: { event: StudioRecordedEvent }) {
const eventType = getStudioTimelineEventType(event);
if (eventType === 'scroll') {
return (
);
}
return (
);
}
function getStudioTimelineEventTitle(event: StudioRecordedEvent) {
const eventType = getStudioTimelineEventType(event);
switch (eventType) {
case 'tap':
case 'click':
return 'Click';
case 'drag':
return 'Drag';
case 'input':
return 'Input';
case 'scroll':
return 'Scroll';
case 'navigation':
return 'Navigate';
case 'setviewport':
return 'Set viewport';
case 'keydown':
return 'Key down';
default:
return event.type || event.actionType || 'Event';
}
}
function getStudioTimelineEventDescription(event: StudioRecordedEvent) {
const eventTitle = getStudioTimelineEventTitle(event);
const semantic = getMidsceneRecorderSemantic(event);
const actionSummary =
'actionSummary' in event && typeof event.actionSummary === 'string'
? event.actionSummary
: '';
if (semantic?.status === 'ready') {
return trimStudioTimelineEventTitlePrefix(
getMidsceneRecorderEventDescription(event),
eventTitle,
);
}
if (semantic?.status === 'pending') {
return '';
}
if (actionSummary) {
return trimStudioTimelineEventTitlePrefix(actionSummary, eventTitle);
}
if (getStudioTimelineEventType(event) === 'scroll') {
return (
trimStudioTimelineEventTitlePrefix(
getMidsceneRecorderEventDescription(event),
eventTitle,
) || 'recorded scroll'
);
}
if (event.value) {
return event.value;
}
return trimStudioTimelineEventTitlePrefix(
getMidsceneRecorderEventDescription(event),
eventTitle,
);
}
function trimStudioTimelineEventTitlePrefix(
description: string,
title: string,
) {
const prefix = `${title} - `;
return description.startsWith(prefix)
? description.slice(prefix.length)
: description;
}
function getStudioTimelineEventTooltip(event: StudioRecordedEvent) {
const title = getStudioTimelineEventTitle(event);
const description = getStudioTimelineEventDescription(event);
const semantic = getMidsceneRecorderSemantic(event);
const text =
description ||
(semantic?.status === 'pending' ? 'analyzing target...' : '');
return text ? `${title} - ${text}` : title;
}
function StudioTimelineEventText({ event }: { event: StudioRecordedEvent }) {
const title = getStudioTimelineEventTitle(event);
const description = getStudioTimelineEventDescription(event);
const semantic = getMidsceneRecorderSemantic(event);
return (
<>
{title}
{description ? (
<>
-
{description}
>
) : semantic?.status === 'pending' ? (
<>
-
analyzing target...
>
) : null}
>
);
}
function getStudioRecorderEventInlineScreenshot(event: StudioRecordedEvent) {
return (
event.screenshotWithBox || event.screenshotAfter || event.screenshotBefore
);
}
function hasStudioRecorderEventScreenshots(events: StudioRecordedEvent[]) {
return events.some((event) =>
Boolean(
getStudioRecorderEventInlineScreenshot(event) || event.screenshotAsset,
),
);
}
function formatStudioRecorderScreenshotEventName(
event: StudioRecordedEvent,
screenshotIndex: number,
) {
return `screenshot-${String(screenshotIndex + 1).padStart(3, '0')}-${event.type}`;
}
function RecorderFloatingOutputs({
canGenerateMarkdown,
canShowScreenshots,
isMarkdownGenerating,
onGenerateMarkdown,
onShowScreenshots,
recorderPanelSession,
}: {
canGenerateMarkdown: boolean;
canShowScreenshots: boolean;
isMarkdownGenerating: boolean;
onGenerateMarkdown: () => void;
onShowScreenshots: () => void;
recorderPanelSession: StudioRecordingSession | null;
}) {
let markdownOutput: ReactNode = null;
if (isMarkdownGenerating) {
markdownOutput = (
);
} else if (canGenerateMarkdown && recorderPanelSession) {
markdownOutput = (
);
}
if (canShowScreenshots && recorderPanelSession) {
return (
{markdownOutput}
);
}
return markdownOutput;
}
function toImagePreviewDataUrl(source: string): Promise {
if (source.startsWith('data:')) {
return Promise.resolve(source);
}
return fetch(source)
.then(async (response) => {
if (!response.ok) {
throw new Error(`Screenshot request failed (${response.status})`);
}
return await response.blob();
})
.then(
(blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === 'string') {
resolve(reader.result);
return;
}
reject(new Error('Screenshot preview data is unavailable.'));
};
reader.onerror = () =>
reject(
reader.error || new Error('Failed to read screenshot data.'),
);
reader.readAsDataURL(blob);
}),
);
}
function RecorderScreenshotCard({
event,
index,
listRef,
getScreenshotAssetUrl,
}: {
event: StudioRecordedEvent;
index: number;
listRef: RefObject;
getScreenshotAssetUrl: (assetId: string) => string | null;
}) {
const cardRef = useRef(null);
const inlineScreenshot = getStudioRecorderEventInlineScreenshot(event);
const assetUrl = event.screenshotAsset
? getScreenshotAssetUrl(event.screenshotAsset.id)
: null;
const [shouldLoadAsset, setShouldLoadAsset] = useState(
Boolean(inlineScreenshot),
);
const [loadError, setLoadError] = useState(false);
const [loadAttempt, setLoadAttempt] = useState(0);
const title = getStudioTimelineEventTitle(event);
const description = getStudioTimelineEventDescription(event);
const screenshotFileName = formatStudioRecorderScreenshotEventName(
event,
index,
);
const imageSource = inlineScreenshot || (shouldLoadAsset ? assetUrl : null);
useEffect(() => {
if (inlineScreenshot || shouldLoadAsset) {
return;
}
const card = cardRef.current;
if (!card) {
return;
}
if (typeof IntersectionObserver === 'undefined') {
setShouldLoadAsset(true);
return;
}
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((entry) => entry.isIntersecting)) {
setShouldLoadAsset(true);
observer.disconnect();
}
},
{ root: listRef.current, rootMargin: '600px 0px' },
);
observer.observe(card);
return () => observer.disconnect();
}, [inlineScreenshot, listRef, shouldLoadAsset]);
useEffect(() => {
setLoadError(false);
}, [imageSource, loadAttempt]);
return (
#{index + 1}
{screenshotFileName}
{imageSource && !loadError ? (
) : loadError || (shouldLoadAsset && !assetUrl) ? (
Screenshot unavailable
) : (
)}
);
}
export function RecorderScreenshotDetailView({
events,
getScreenshotAssetUrl = () => null,
}: {
events: StudioRecordedEvent[];
getScreenshotAssetUrl?: (assetId: string) => string | null;
}) {
const listRef = useRef(null);
const screenshotEvents = events
.map((event, index) => ({ event, index }))
.filter(
(
item,
): item is {
event: StudioRecordedEvent;
index: number;
} =>
Boolean(
getStudioRecorderEventInlineScreenshot(item.event) ||
item.event.screenshotAsset,
),
);
return (
{screenshotEvents.length > 0 ? (
{screenshotEvents.map(({ event, index }, itemIndex) => (
))}
) : (
No screenshots available for this recording.
)}
);
}
export function RecorderFloatingPanel({
canStartRecording,
canGenerateMarkdown,
detailView,
error,
isMarkdownGenerating,
isRecording,
isStoppingRecording,
onGenerateMarkdown,
onShowScreenshots,
onToggleCollapsed,
onToggleRecording,
recorderPanelEvents,
recorderPanelSession,
showExpandedDetail,
timelineCollapsed,
statusText,
}: RecorderFloatingPanelProps) {
const timelineScrollRef = useRef(null);
const showRecordingVisual = isRecording && !isStoppingRecording;
const recordingButtonLabel = isStoppingRecording
? 'Stopping recording'
: showRecordingVisual
? 'Stop recording'
: 'Start recording';
const recordingButtonTitle = isStoppingRecording
? 'Stopping recording'
: showRecordingVisual
? 'Stop recording'
: statusText;
const controlCardClassName = [
'studio-recorder-control-card',
showRecordingVisual ? 'studio-recorder-control-card-recording' : '',
]
.filter(Boolean)
.join(' ');
const isTimelineEmpty =
recorderPanelEvents.length === 0 &&
!showRecordingVisual &&
!showExpandedDetail;
const taskCardClassName = 'studio-recorder-task-card';
const mainClassName = [
'studio-recorder-floating-main',
timelineCollapsed ? 'studio-recorder-floating-main-collapsed' : '',
]
.filter(Boolean)
.join(' ');
const outputsClassName = [
'studio-recorder-floating-outputs',
hasStudioRecorderEventScreenshots(recorderPanelEvents) &&
!isRecording &&
!showExpandedDetail
? 'studio-recorder-floating-outputs-with-screenshot'
: '',
timelineCollapsed || showExpandedDetail
? 'studio-recorder-floating-outputs-hidden'
: '',
]
.filter(Boolean)
.join(' ');
const shouldShowOutputs =
isMarkdownGenerating ||
canGenerateMarkdown ||
(hasStudioRecorderEventScreenshots(recorderPanelEvents) && !isRecording);
const shouldRenderTimelinePanel =
!isTimelineEmpty || showExpandedDetail || shouldShowOutputs;
useEffect(() => {
if (timelineCollapsed || recorderPanelEvents.length === 0) {
return;
}
const scrollToLatestEvent = () => {
const timeline = timelineScrollRef.current;
if (timeline) {
timeline.scrollTop = timeline.scrollHeight;
}
};
// The output footer animates in after recording stops. Scroll once after
// the commit and again after the height transition so its buttons are not
// left below the visible timeline area.
const initialTimeoutId = window.setTimeout(scrollToLatestEvent);
const settledTimeoutId = window.setTimeout(scrollToLatestEvent, 220);
return () => {
window.clearTimeout(initialTimeoutId);
window.clearTimeout(settledTimeoutId);
};
}, [outputsClassName, recorderPanelEvents.length, timelineCollapsed]);
return (
{error ?
{error}
: null}
Record & Generate Markdown
Record interactions, then generate a natural language description.
{shouldRenderTimelinePanel ? (
) : null
}
onToggleCollapsed={onToggleCollapsed}
scrollBody={!isTimelineEmpty || showExpandedDetail}
variant={StudioModeTab.Record}
>
{showExpandedDetail ? (
detailView
) : (
)}
) : null}
);
}