Merge pull request #1010 from heygen-com/worktree-feat+studio-blocks-drop-position

feat(studio): preserve drop position when dropping blocks onto preview
This commit is contained in:
Miguel Ángel
2026-05-22 00:28:42 +02:00
committed by GitHub
13 changed files with 351 additions and 137 deletions
+22 -1
View File
@@ -481,6 +481,22 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
app.get("/icons/*", serveStudioStaticFile);
app.get("/favicon.svg", serveStudioStaticFile);
// ── Runtime env injection ───────────────────────────────────────────────
// When the studio is served as a pre-built SPA, Vite `VITE_STUDIO_*` env
// vars were baked at build time. Collect any such vars from the current
// process.env and inject them as `window.__HF_STUDIO_ENV__` so the client
// can pick them up at runtime, overriding the baked defaults.
function buildRuntimeEnvScript(): string {
const overrides: Record<string, string> = {};
for (const [key, value] of Object.entries(process.env)) {
if (key.startsWith("VITE_STUDIO_") && value !== undefined) {
overrides[key] = value;
}
}
if (Object.keys(overrides).length === 0) return "";
return `<script>window.__HF_STUDIO_ENV__=${JSON.stringify(overrides)};</script>`;
}
// SPA fallback
app.get("*", (c) => {
const indexPath = resolve(studioDir, "index.html");
@@ -540,7 +556,12 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
500,
);
}
return c.html(readFileSync(indexPath, "utf-8"));
let html = readFileSync(indexPath, "utf-8");
const envScript = buildRuntimeEnvScript();
if (envScript) {
html = html.replace("<head>", `<head>${envScript}`);
}
return c.html(html);
});
return { app, watcher };
+41
View File
@@ -12,6 +12,7 @@ import { usePreviewPersistence } from "./hooks/usePreviewPersistence";
import { useTimelineEditing } from "./hooks/useTimelineEditing";
import { addBlockToProject } from "./utils/blockInstaller";
import type { BlockParam } from "@hyperframes/core/registry";
import type { BlockPreviewInfo } from "./components/sidebar/BlocksTab";
import { useDomEditSession } from "./hooks/useDomEditSession";
import { useAppHotkeys } from "./hooks/useAppHotkeys";
import { useClipboard } from "./hooks/useClipboard";
@@ -80,6 +81,7 @@ export function StudioApp() {
params: BlockParam[];
compositionPath: string;
} | null>(null);
const [blockPreview, setBlockPreview] = useState<BlockPreviewInfo | null>(null);
const previewIframeRef = useRef<HTMLIFrameElement | null>(null);
const activeCompPathRef = useRef(activeCompPath);
@@ -190,6 +192,8 @@ export function StudioApp() {
projectId,
blockName,
activeCompPath,
previewIframe: previewIframeRef.current,
currentTime: usePlayerStore.getState().currentTime,
timelineElements,
readProjectFile: fileManager.readProjectFile,
writeProjectFile: fileManager.writeProjectFile,
@@ -233,6 +237,40 @@ export function StudioApp() {
blockName,
activeCompPath,
placement,
previewIframe: previewIframeRef.current,
currentTime: usePlayerStore.getState().currentTime,
timelineElements,
readProjectFile: fileManager.readProjectFile,
writeProjectFile: fileManager.writeProjectFile,
recordEdit: editHistory.recordEdit,
refreshFileTree: fileManager.refreshFileTree,
reloadPreview,
showToast,
});
},
[
projectId,
activeCompPath,
timelineElements,
fileManager.readProjectFile,
fileManager.writeProjectFile,
fileManager.refreshFileTree,
editHistory.recordEdit,
reloadPreview,
showToast,
],
);
const handlePreviewBlockDrop = useCallback(
(blockName: string, position: { left: number; top: number }) => {
if (!projectId) return;
void addBlockToProject({
projectId,
blockName,
activeCompPath,
visualPosition: position,
previewIframe: previewIframeRef.current,
currentTime: usePlayerStore.getState().currentTime,
timelineElements,
readProjectFile: fileManager.readProjectFile,
writeProjectFile: fileManager.writeProjectFile,
@@ -532,6 +570,7 @@ export function StudioApp() {
leftSidebarRef={leftSidebarRef}
onSelectComposition={handleSelectComposition}
onAddBlock={handleAddBlock}
onPreviewBlock={setBlockPreview}
onLint={handleLint}
linting={linting}
/>
@@ -541,6 +580,7 @@ export function StudioApp() {
handleTimelineElementDelete={timelineEditing.handleTimelineElementDelete}
handleTimelineAssetDrop={timelineEditing.handleTimelineAssetDrop}
handleTimelineBlockDrop={handleTimelineBlockDrop}
handlePreviewBlockDrop={handlePreviewBlockDrop}
handleTimelineFileDrop={timelineEditing.handleTimelineFileDrop}
handleTimelineElementMove={timelineEditing.handleTimelineElementMove}
handleTimelineElementResize={timelineEditing.handleTimelineElementResize}
@@ -548,6 +588,7 @@ export function StudioApp() {
setCompIdToSrc={setCompIdToSrc}
setCompositionLoading={setCompositionLoading}
shouldShowSelectedDomBounds={shouldShowSelectedDomBounds}
blockPreview={blockPreview}
/>
{!panelLayout.rightCollapsed && (
@@ -7,11 +7,13 @@ import { usePanelLayoutContext } from "../contexts/PanelLayoutContext";
import { useStudioContext } from "../contexts/StudioContext";
import { useFileManagerContext } from "../contexts/FileManagerContext";
import { getPersistedRenderSettings } from "./renders/renderSettings";
import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
export interface StudioLeftSidebarProps {
leftSidebarRef: RefObject<LeftSidebarHandle | null>;
onSelectComposition: (comp: string) => void;
onAddBlock: (blockName: string) => void;
onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;
onLint: () => void;
linting: boolean;
}
@@ -21,6 +23,7 @@ export function StudioLeftSidebar({
leftSidebarRef,
onSelectComposition,
onAddBlock,
onPreviewBlock,
onLint,
linting,
}: StudioLeftSidebarProps) {
@@ -128,6 +131,7 @@ export function StudioLeftSidebar({
linting={linting}
onToggleCollapse={toggleLeftSidebar}
onAddBlock={onAddBlock}
onPreviewBlock={onPreviewBlock}
/>
<div
className="group w-2 flex-shrink-0 cursor-col-resize flex items-center justify-center"
@@ -12,6 +12,7 @@ import {
} from "./editor/manualEditingAvailability";
import { useStudioContext } from "../contexts/StudioContext";
import { useDomEditContext } from "../contexts/DomEditContext";
import type { BlockPreviewInfo } from "./sidebar/BlocksTab";
export interface StudioPreviewAreaProps {
timelineToolbar: ReactNode;
@@ -29,6 +30,10 @@ export interface StudioPreviewAreaProps {
blockName: string,
placement: Pick<TimelineElement, "start" | "track">,
) => Promise<void> | void;
handlePreviewBlockDrop?: (
blockName: string,
position: { left: number; top: number },
) => Promise<void> | void;
handleTimelineFileDrop: (
files: File[],
placement?: Pick<TimelineElement, "start" | "track">,
@@ -45,6 +50,7 @@ export interface StudioPreviewAreaProps {
setCompIdToSrc: (map: Map<string, string>) => void;
setCompositionLoading: (loading: boolean) => void;
shouldShowSelectedDomBounds: boolean;
blockPreview?: BlockPreviewInfo | null;
}
export function StudioPreviewArea({
@@ -53,6 +59,7 @@ export function StudioPreviewArea({
handleTimelineElementDelete,
handleTimelineAssetDrop,
handleTimelineBlockDrop,
handlePreviewBlockDrop,
handleTimelineFileDrop,
handleTimelineElementMove,
handleTimelineElementResize,
@@ -60,6 +67,7 @@ export function StudioPreviewArea({
setCompIdToSrc,
setCompositionLoading,
shouldShowSelectedDomBounds,
blockPreview,
}: StudioPreviewAreaProps) {
const {
projectId,
@@ -104,6 +112,7 @@ export function StudioPreviewArea({
onDeleteElement={handleTimelineElementDelete}
onAssetDrop={handleTimelineAssetDrop}
onBlockDrop={handleTimelineBlockDrop}
onPreviewBlockDrop={handlePreviewBlockDrop}
onFileDrop={handleTimelineFileDrop}
onMoveElement={handleTimelineElementMove}
onResizeElement={handleTimelineElementResize}
@@ -123,7 +132,26 @@ export function StudioPreviewArea({
}}
onIframeRef={handlePreviewIframeRef}
previewOverlay={
captionEditMode ? (
blockPreview ? (
<div className="absolute inset-0 z-30 bg-black pointer-events-none">
{blockPreview.videoUrl ? (
<video
src={blockPreview.videoUrl}
autoPlay
muted
loop
playsInline
className="w-full h-full object-contain"
/>
) : blockPreview.posterUrl ? (
<img
src={blockPreview.posterUrl}
alt={blockPreview.title}
className="w-full h-full object-contain"
/>
) : null}
</div>
) : captionEditMode ? (
<CaptionOverlay iframeRef={previewIframeRef} />
) : STUDIO_INSPECTOR_PANELS_ENABLED ? (
<DomEditOverlay
@@ -323,7 +323,7 @@ export const PropertyPanel = memo(function PropertyPanel({
</div>
<div className="mt-3">
<MetricField
label="Layer"
label="Z-index"
value={String(parseInt(styles["z-index"] || "auto", 10) || 0)}
scrub
onCommit={(next) => onSetStyle("z-index", next)}
@@ -30,7 +30,16 @@ export function resolveStudioBooleanEnvFlag(
// and downstream `env[name]` reads would crash. Fall back to `{}` so
// every flag resolves to its declared default outside Vite. Direct
// property access keeps Vite's compile-time transform happy.
const env = (import.meta.env ?? {}) as StudioFeatureFlagEnv;
//
// When the studio is served as a pre-built SPA by the embedded Hono server,
// `import.meta.env` values were baked at build time. The server injects
// `window.__HF_STUDIO_ENV__` with any `VITE_STUDIO_*` env vars from the
// user's shell, so runtime overrides take precedence over baked defaults.
const runtimeEnv =
typeof window !== "undefined"
? ((window as Window & { __HF_STUDIO_ENV__?: StudioFeatureFlagEnv }).__HF_STUDIO_ENV__ ?? {})
: {};
const env = { ...(import.meta.env ?? {}), ...runtimeEnv } as StudioFeatureFlagEnv;
export const STUDIO_PREVIEW_MANUAL_EDITING_ENABLED = resolveStudioBooleanEnvFlag(
env,
@@ -13,6 +13,7 @@ import type { TimelineElement } from "../../player";
import type { BlockedTimelineEditIntent } from "../../player/components/timelineEditing";
import { NLEPreview } from "./NLEPreview";
import { CompositionBreadcrumb } from "./CompositionBreadcrumb";
import { usePreviewBlockDrop } from "./usePreviewBlockDrop";
import { useCompositionStack } from "./useCompositionStack";
import {
TIMELINE_TOGGLE_SHORTCUT_LABEL,
@@ -54,6 +55,10 @@ interface NLELayoutProps {
blockName: string,
placement: Pick<TimelineElement, "start" | "track">,
) => Promise<void> | void;
onPreviewBlockDrop?: (
blockName: string,
position: { left: number; top: number },
) => Promise<void> | void;
/** Persist timeline move actions back into source HTML */
onMoveElement?: (
element: TimelineElement,
@@ -107,6 +112,7 @@ export const NLELayout = memo(function NLELayout({
onDeleteElement,
onAssetDrop,
onBlockDrop,
onPreviewBlockDrop,
onMoveElement,
onResizeElement,
onBlockedEditAttempt,
@@ -131,6 +137,22 @@ export const NLELayout = memo(function NLELayout({
usePlayerStore.getState().reset();
}
const stageRefForDrop = useRef<HTMLDivElement | null>(null);
const handleStageRef = useCallback((ref: React.RefObject<HTMLDivElement | null>) => {
stageRefForDrop.current = ref.current;
}, []);
const {
isDragOver: previewDragOver,
handleDragOver: handlePreviewDragOver,
handleDragLeave: handlePreviewDragLeave,
handleDrop: handlePreviewDrop,
} = usePreviewBlockDrop({
portrait,
stageRef: stageRefForDrop as React.RefObject<HTMLDivElement | null>,
onBlockDrop: onPreviewBlockDrop,
});
// Lightweight reload: change iframe src instead of destroying the Player.
// refreshPlayer() saves the seek position and appends a cache-busting _t
// param — the Player instance stays alive so the adapter is available for
@@ -344,7 +366,13 @@ export const NLELayout = memo(function NLELayout({
>
{/* Preview + player controls */}
<div className="flex-1 min-h-0 flex flex-col">
<div className="flex-1 min-h-0 relative" data-preview-pan-surface="true">
<div
className="flex-1 min-h-0 relative"
data-preview-pan-surface="true"
onDragOver={handlePreviewDragOver}
onDragLeave={handlePreviewDragLeave}
onDrop={handlePreviewDrop}
>
<NLEPreview
projectId={projectId}
iframeRef={iframeRef}
@@ -353,7 +381,11 @@ export const NLELayout = memo(function NLELayout({
portrait={portrait}
directUrl={directUrl}
suppressLoadingOverlay={hasLoadedOnceRef.current}
onStageRef={handleStageRef}
/>
{previewDragOver && (
<div className="absolute inset-2 z-40 rounded-lg border-2 border-dashed border-studio-accent/50 bg-studio-accent/[0.04] pointer-events-none" />
)}
{!isFullscreen && previewOverlay}
</div>
<div className="bg-neutral-950 border-t border-neutral-800/50 flex-shrink-0">
@@ -12,7 +12,6 @@ import {
type PreviewZoomState,
} from "./previewZoom";
import { readStudioUiPreferences, writeStudioUiPreferences } from "../../utils/studioUiPreferences";
interface NLEPreviewProps {
projectId: string;
iframeRef: Ref<HTMLIFrameElement>;
@@ -21,6 +20,7 @@ interface NLEPreviewProps {
portrait?: boolean;
directUrl?: string;
suppressLoadingOverlay?: boolean;
onStageRef?: (ref: React.RefObject<HTMLDivElement | null>) => void;
}
export function getPreviewPlayerKey({
@@ -90,10 +90,14 @@ export const NLEPreview = memo(function NLEPreview({
portrait,
directUrl,
suppressLoadingOverlay,
onStageRef,
}: NLEPreviewProps) {
const activeKey = getPreviewPlayerKey({ projectId, directUrl });
const viewportRef = useRef<HTMLDivElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
useEffect(() => {
onStageRef?.(stageRef);
}, [onStageRef]);
const [stageSize, setStageSize] = useState(() => resolvePreviewStageSize(0, 0, portrait));
const zoomRef = useRef<PreviewZoomState>(loadInitialZoom());
@@ -0,0 +1,109 @@
import { useCallback, useState, type RefObject } from "react";
import { TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
interface UsePreviewBlockDropOptions {
portrait?: boolean;
stageRef: RefObject<HTMLDivElement | null>;
onBlockDrop?: (blockName: string, position: { left: number; top: number }) => void;
}
interface BlockDropPayload {
name: string;
dimensions?: { width: number; height: number };
}
function parseBlockPayload(raw: string): BlockDropPayload | null {
try {
const parsed = JSON.parse(raw) as {
name?: string;
dimensions?: { width: number; height: number };
};
return parsed.name ? (parsed as BlockDropPayload) : null;
} catch {
return null;
}
}
function resolveCompositionPosition(
clientX: number,
clientY: number,
stageRect: DOMRect,
portrait: boolean | undefined,
): { left: number; top: number } | null {
if (stageRect.width === 0 || stageRect.height === 0) return null;
const normalizedX = (clientX - stageRect.left) / stageRect.width;
const normalizedY = (clientY - stageRect.top) / stageRect.height;
const compWidth = portrait ? 1080 : 1920;
const compHeight = portrait ? 1920 : 1080;
return {
left: Math.max(0, Math.min(normalizedX * compWidth, compWidth)),
top: Math.max(0, Math.min(normalizedY * compHeight, compHeight)),
};
}
function centerBlockAtPosition(
pos: { left: number; top: number },
block: BlockDropPayload,
): { left: number; top: number } {
const blockW = block.dimensions?.width ?? 0;
const blockH = block.dimensions?.height ?? 0;
return {
left: Math.max(0, pos.left - blockW / 2),
top: Math.max(0, pos.top - blockH / 2),
};
}
export function usePreviewBlockDrop({
portrait,
stageRef,
onBlockDrop,
}: UsePreviewBlockDropOptions) {
const [isDragOver, setIsDragOver] = useState(false);
const handleDragOver = useCallback(
(e: React.DragEvent) => {
if (!onBlockDrop) return;
if (!e.dataTransfer.types.includes(TIMELINE_BLOCK_MIME)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
setIsDragOver(true);
},
[onBlockDrop],
);
const handleDragLeave = useCallback(() => {
setIsDragOver(false);
}, []);
// fallow-ignore-next-line complexity
const handleDrop = useCallback(
(e: React.DragEvent) => {
setIsDragOver(false);
if (!onBlockDrop) return;
const payload = e.dataTransfer.getData(TIMELINE_BLOCK_MIME);
if (!payload) return;
e.preventDefault();
const block = parseBlockPayload(payload);
const stage = stageRef.current;
if (!block || !stage) return;
const pos = resolveCompositionPosition(
e.clientX,
e.clientY,
stage.getBoundingClientRect(),
portrait,
);
if (!pos) return;
onBlockDrop(block.name, centerBlockAtPosition(pos, block));
},
[onBlockDrop, stageRef, portrait],
);
return { isDragOver, handleDragOver, handleDragLeave, handleDrop };
}
@@ -1,5 +1,4 @@
import { memo, useState, useCallback, useRef, useEffect } from "react";
import { createPortal } from "react-dom";
import { useBlockCatalog } from "../../hooks/useBlockCatalog";
import {
BLOCK_CATEGORIES,
@@ -8,12 +7,19 @@ import {
} from "../../utils/blockCategories";
import { TIMELINE_BLOCK_MIME } from "../../utils/timelineAssetDrop";
export interface BlockPreviewInfo {
videoUrl?: string;
posterUrl?: string;
title: string;
}
interface BlocksTabProps {
onAddBlock: (blockName: string) => void;
onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;
}
// fallow-ignore-next-line complexity
export const BlocksTab = memo(function BlocksTab({ onAddBlock }: BlocksTabProps) {
export const BlocksTab = memo(function BlocksTab({ onAddBlock, onPreviewBlock }: BlocksTabProps) {
const { loading, error, search, setSearch, category, setCategory, filteredBlocks } =
useBlockCatalog();
@@ -114,6 +120,7 @@ export const BlocksTab = memo(function BlocksTab({ onAddBlock }: BlocksTabProps)
videoUrl={block.preview?.video}
dimensions={dims}
onAdd={() => onAddBlock(block.name)}
onPreview={onPreviewBlock}
/>
);
})}
@@ -163,6 +170,7 @@ function BlockCard({
videoUrl,
dimensions,
onAdd,
onPreview,
}: {
name: string;
title: string;
@@ -173,52 +181,35 @@ function BlockCard({
videoUrl?: string;
dimensions?: { width: number; height: number };
onAdd: () => void;
onPreview?: (preview: BlockPreviewInfo | null) => void;
}) {
const [hovered, setHovered] = useState(false);
const [adding, setAdding] = useState(false);
const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const leaveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const videoRef = useRef<HTMLVideoElement | null>(null);
const colors = getCategoryColors(category);
const needsWebGL = tags?.includes("html-in-canvas") || tags?.includes("webgl");
const cancelLeave = useCallback(() => {
if (leaveTimer.current) {
clearTimeout(leaveTimer.current);
leaveTimer.current = null;
}
}, []);
const handleEnter = useCallback(() => {
cancelLeave();
hoverTimer.current = setTimeout(() => setHovered(true), 500);
}, [cancelLeave]);
const dismiss = useCallback(() => {
if (hoverTimer.current) {
clearTimeout(hoverTimer.current);
hoverTimer.current = null;
}
cancelLeave();
setHovered(false);
}, [cancelLeave]);
hoverTimer.current = setTimeout(() => {
setHovered(true);
onPreview?.({ videoUrl, posterUrl, title });
}, 300);
}, [onPreview, videoUrl, posterUrl, title]);
const handleLeave = useCallback(() => {
if (hoverTimer.current) {
clearTimeout(hoverTimer.current);
hoverTimer.current = null;
}
leaveTimer.current = setTimeout(() => setHovered(false), 150);
}, []);
setHovered(false);
onPreview?.(null);
}, [onPreview]);
useEffect(() => {
if (!hovered) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") dismiss();
return () => {
if (hoverTimer.current) clearTimeout(hoverTimer.current);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [hovered, dismiss]);
}, []);
const handleAdd = useCallback(
(e: React.MouseEvent) => {
@@ -251,7 +242,6 @@ function BlockCard({
<div className="aspect-video w-full overflow-hidden relative">
{hovered && videoUrl ? (
<video
ref={videoRef}
src={videoUrl}
autoPlay
muted
@@ -313,72 +303,6 @@ function BlockCard({
</span>
</div>
</div>
{/* Fullscreen hover preview */}
{hovered &&
(videoUrl || posterUrl) &&
createPortal(
<div
className="fixed inset-0 z-50 flex items-center justify-center cursor-pointer"
onClick={dismiss}
onPointerEnter={cancelLeave}
onPointerLeave={handleLeave}
>
<div className="bg-black/80 absolute inset-0" />
<button
type="button"
onClick={dismiss}
className="absolute top-4 right-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-neutral-800/80 text-neutral-400 hover:text-white hover:bg-neutral-700 transition-colors"
>
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
</button>
<div
className="relative rounded-xl overflow-hidden shadow-2xl border border-neutral-600/30 cursor-default"
style={{ width: "80vw", maxWidth: 1200, maxHeight: "80vh" }}
onClick={(e) => e.stopPropagation()}
>
<div className="aspect-video bg-neutral-950">
{videoUrl ? (
<video
src={videoUrl}
autoPlay
muted
loop
playsInline
className="w-full h-full object-contain"
/>
) : (
<img src={posterUrl} alt={title} className="w-full h-full object-contain" />
)}
</div>
<div className="bg-neutral-900/95 px-4 py-3">
<div className="text-[14px] font-semibold text-neutral-100">{title}</div>
<div className="flex items-center gap-2 mt-1">
<span className={`w-2 h-2 rounded-full ${colors.dot}`} />
<span className={`text-[11px] ${colors.text}`}>
{BLOCK_CATEGORIES.find((c) => c.id === category)?.label}
</span>
{duration != null && (
<span className="text-[11px] text-neutral-500">{duration}s</span>
)}
</div>
</div>
</div>
</div>,
document.body,
)}
</div>
);
}
@@ -10,7 +10,7 @@ import {
import { CompositionsTab } from "./CompositionsTab";
import { AssetsTab } from "./AssetsTab";
import { trackStudioEvent } from "../../utils/studioTelemetry";
import { BlocksTab } from "./BlocksTab";
import { BlocksTab, type BlockPreviewInfo } from "./BlocksTab";
import { FileTree } from "../editor/FileTree";
import { STUDIO_BLOCKS_PANEL_ENABLED } from "../editor/manualEditingAvailability";
@@ -55,6 +55,7 @@ interface LeftSidebarProps {
linting?: boolean;
onToggleCollapse?: () => void;
onAddBlock?: (blockName: string) => void;
onPreviewBlock?: (preview: BlockPreviewInfo | null) => void;
takeoverContent?: ReactNode;
}
@@ -84,6 +85,7 @@ export const LeftSidebar = memo(
linting,
onToggleCollapse,
onAddBlock,
onPreviewBlock,
takeoverContent,
},
ref,
@@ -165,7 +167,7 @@ export const LeftSidebar = memo(
: "text-neutral-500 hover:text-neutral-200"
}`}
>
Blocks
Catalog
</button>
)}
</div>
@@ -245,7 +247,7 @@ export const LeftSidebar = memo(
)}
{STUDIO_BLOCKS_PANEL_ENABLED && tab === "blocks" && onAddBlock && (
<BlocksTab onAddBlock={onAddBlock} />
<BlocksTab onAddBlock={onAddBlock} onPreviewBlock={onPreviewBlock} />
)}
{/* Lint button pinned at the bottom */}
+62 -29
View File
@@ -9,11 +9,29 @@ import { formatTimelineAttributeNumber } from "../player/components/timelineEdit
import { saveProjectFilesWithHistory } from "./studioFileHistory";
import type { EditHistoryKind } from "./editHistory";
function getMaxZIndexFromIframe(iframe: HTMLIFrameElement | null): number {
try {
const doc = iframe?.contentDocument;
if (!doc) return 0;
let max = 0;
for (const el of doc.body.querySelectorAll("*")) {
const z = parseInt(getComputedStyle(el).zIndex, 10);
if (Number.isFinite(z) && z > max) max = z;
}
return max;
} catch {
return 0;
}
}
interface AddBlockOptions {
projectId: string;
blockName: string;
activeCompPath: string | null;
placement?: { start: number; track: number };
visualPosition?: { left: number; top: number };
previewIframe?: HTMLIFrameElement | null;
currentTime?: number;
timelineElements: TimelineElement[];
readProjectFile: (path: string) => Promise<string>;
writeProjectFile: (path: string, content: string) => Promise<void>;
@@ -44,6 +62,7 @@ export async function addBlockToProject(
blockName,
activeCompPath,
placement,
visualPosition,
timelineElements,
readProjectFile,
writeProjectFile,
@@ -102,20 +121,18 @@ export async function addBlockToProject(
const isBlock = block.type === "hyperframes:block";
const hostDims = resolveTimelineAssetInitialGeometry(originalContent);
const currentTime = opts.currentTime ?? 0;
const start = placement
? Number(formatTimelineAttributeNumber(placement.start))
: isBlock
? relevantElements.reduce(
(max, te) => Math.max(max, (te.start ?? 0) + (te.duration ?? 0)),
0,
)
: 0;
const duration = isBlock
? (block as { duration: number }).duration
: relevantElements.reduce(
(max, te) => Math.max(max, (te.start ?? 0) + (te.duration ?? 0)),
10,
);
: Number(formatTimelineAttributeNumber(currentTime));
const blockDuration =
"duration" in block ? (block as { duration: number }).duration : undefined;
const duration =
blockDuration ??
relevantElements.reduce(
(max, te) => Math.max(max, (te.start ?? 0) + (te.duration ?? 0)),
10,
);
const track =
placement?.track ??
(isBlock
@@ -124,26 +141,42 @@ export async function addBlockToProject(
? Math.max(...relevantElements.map((te) => te.track)) + 1
: 1);
const zIndex = Math.max(1, relevantElements.length + 1);
const zIndex = getMaxZIndexFromIframe(opts.previewIframe ?? null) + 1;
const width = isBlock
? (block as { dimensions: { width: number } }).dimensions.width
: hostDims.width;
const height = isBlock
? (block as { dimensions: { height: number } }).dimensions.height
: hostDims.height;
const width = hostDims.width;
const height = hostDims.height;
const subCompHtml =
`<div data-composition-id="${compId}" ` +
`data-composition-src="${compositionFile}" ` +
`data-start="${formatTimelineAttributeNumber(start)}" ` +
`data-duration="${formatTimelineAttributeNumber(duration)}" ` +
`data-track-index="${track}" ` +
`data-width="${width}" data-height="${height}" ` +
`style="position: absolute; left: 0px; top: 0px; width: ${width}px; height: ${height}px; z-index: ${zIndex}">` +
`</div>`;
const left = visualPosition ? Math.round(visualPosition.left) : 0;
const top = visualPosition ? Math.round(visualPosition.top) : 0;
const patchedContent = insertTimelineAssetIntoSource(originalContent, subCompHtml);
const subCompHtml = [
`<div`,
` data-composition-id="${compId}"`,
` data-composition-src="${compositionFile}"`,
` data-start="${formatTimelineAttributeNumber(start)}"`,
` data-duration="${formatTimelineAttributeNumber(duration)}"`,
` data-track-index="${track}"`,
` data-width="${width}"`,
` data-height="${height}"`,
` style="position: absolute; left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px; z-index: ${zIndex}"`,
`></div>`,
].join("\n");
let patchedContent = insertTimelineAssetIntoSource(originalContent, subCompHtml);
const newEnd = start + duration;
const rootDurMatch = patchedContent.match(
/(<[^>]*data-composition-id="[^"]*"[^>]*data-duration=")([^"]*)(")/,
);
if (rootDurMatch) {
const rootDur = parseFloat(rootDurMatch[2]!);
if (newEnd > rootDur) {
patchedContent = patchedContent.replace(
rootDurMatch[0],
`${rootDurMatch[1]}${formatTimelineAttributeNumber(newEnd)}${rootDurMatch[3]}`,
);
}
}
await saveProjectFilesWithHistory({
projectId,
@@ -126,5 +126,12 @@ export function insertTimelineAssetIntoSource(source: string, assetHtml: string)
throw new Error("No composition root found in target source");
}
const insertAt = match.index + match[0].length;
return `${source.slice(0, insertAt)}${assetHtml}${source.slice(insertAt)}`;
const lineStart = source.lastIndexOf("\n", match.index);
const leadingWhitespace = source.slice(lineStart + 1, match.index).match(/^(\s*)/)?.[1] ?? "";
const childIndent = leadingWhitespace + " ";
const indented = assetHtml
.split("\n")
.map((line, i) => (i === 0 ? line : childIndent + line))
.join("\n");
return `${source.slice(0, insertAt)}\n${childIndent}${indented}${source.slice(insertAt)}`;
}