The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
fix(motion): anchor media popovers to their timeline targets (#172)
open-design-crew[bot]c5f6975cfde7
diff --git a/README.md b/README.mdindex 799fc5f9..a574b3bc 100644--- a/README.md+++ b/README.md@@ -74,6 +74,8 @@ After you accept, the Agent follows the [template-to-video workflow](skills/moti**Bring more media when you need it.** The Studio model gateway accepts requests for images, video or audio through configured providers; you choose which results to place in your project. Providers use your own accounts and may charge for generation. [Verified capabilities](docs/model-gateway.md) · [Nine public MCP tools](docs/mcp-phase1-tools.md)+Media panels open beside the triggering button or timeline selection and adjust to scrolling and available space. The empty-timeline guide hides during generation and after insertion; it returns when the panel closes without an insertion or when undo leaves the timeline empty. [Editor interaction details](docs/product/media-generation-design.md#时间轴交互规则及原因)+## MCP and lightweight installationThe [lightweight npm installer](docs/npm-installation.md) installs nine MCP Tools and five Skills for Codex, Claude Code, DeepSeek Harness or WorkBuddy. It shares the application and prepares verified native tools on demand. Build locally with `npm run package:npm`; the npm package is not publicly published. Complete ZIPs remain available as a backup.diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdindex 8cc21f66..f1bcba07 100644--- a/docs/README.zh-CN.md+++ b/docs/README.zh-CN.md@@ -74,6 +74,8 @@**需要更多素材时**,可以在 Studio 里通过已配置的模型网关请求图片、视频或音频,再选择放进工程的结果。模型调用使用自己的供应商账户,可能产生费用。[已验证能力](model-gateway.md) · [一期九个公开 MCP 工具](mcp-phase1-tools.md)+素材弹框贴近触发按钮或时间轴选区,并随滚动和可用空间调整。空轨道进入生成时隐藏起步引导,插入后保持隐藏;关闭且未插入、或撤销至空轨道时恢复。[编辑交互说明](product/media-generation-design.md#时间轴交互规则及原因)+## MCP 与轻量安装[npm 轻量安装器](npm-installation.md) 可为 Codex、Claude Code、DeepSeek Harness、WorkBuddy 同装九个 MCP Tool 和五个 Skill,共用应用并按需准备经过校验的原生工具。运行 `npm run package:npm` 本地构建;npm 包尚未公开发布,完整 ZIP 保留备用。diff --git a/docs/editor-fork.md b/docs/editor-fork.mdindex dc4f8eb2..600a6a38 100644--- a/docs/editor-fork.md+++ b/docs/editor-fork.md@@ -28,9 +28,11 @@ OpenDesign 的 `WorkspaceFrame` 放在原生 App 外,负责通用导航和会先用 [产品架构](product/architecture.md#职责分层与依赖方向) 判断需求归属;多模态入口、原图修改和后续属性面板接入遵循 [素材生成设计](product/media-generation-design.md)。该设计记录用户意图、候选采用、原生历史与过期目标的边界,本页维护实现位置。-模型设置位于顶栏,空时间轴、时间轴工具栏和素材面板共用 `MediaGatewayProvider`。生成面板读取已选时段,提供模态/模型/参数与任务结果,显式放置才调用原生 `useTimelineAssetDropOps`,沿用撤销与保存。上下文绑定会在工程/合成切换及卸载时失效。素材菜单增加可见入口、预览和下载,其他操作继续使用原生文件服务。模型协议与限制见 [模型网关](model-gateway.md)。+模型设置位于侧栏,嵌入视图保留顶栏入口;空时间轴、时间轴工具栏和素材面板共用 `MediaGatewayProvider`。生成面板读取已选时段,提供模态/模型/参数与任务结果,显式放置才调用原生 `useTimelineAssetDropOps`,沿用撤销与保存。上下文绑定会在工程/合成切换及卸载时失效。素材菜单增加可见入口、预览和下载,其他操作继续使用原生文件服务。模型协议与限制见 [模型网关](model-gateway.md)。-`TimelineMediaBar` 订阅原生片段选择、已完成的范围选择和标尺点击,在时间轴上方就地显示描述/生成/修改入口;原有范围 Agent 弹框通过「交给 Agent」继续使用。图片修改传 `referenceAsset`,结果选择后通过 `handleDomAttributeBatchCommit` 只改 `src`,在文件队列内的 `validateContent` 检查修改前的原始引用,保留原生历史、时长与动画。`prepareContent` 用于服务端已执行 patch 后的后处理,不能用作修改前验证。不要绕过该提交链整页重写 HTML,也不要在工程切换后恢复旧选区。+`TimelineMediaBar` 订阅原生片段选择、已完成的范围选择和标尺点击,在实际目标旁显示描述/生成/修改入口;原有范围 Agent 弹框通过「交给 Agent」继续使用。图片修改传 `referenceAsset`,结果选择后通过 `handleDomAttributeBatchCommit` 只改 `src`,在文件队列内的 `validateContent` 检查修改前的原始引用,保留原生历史、时长与动画。`prepareContent` 用于服务端已执行 patch 后的后处理,不能用作修改前验证。不要绕过该提交链整页重写 HTML,也不要在工程切换后恢复旧选区。++`MediaRequest.anchor` 保存触发元素或时间轴虚拟锚点。`useMediaPopoverPosition` 共用实际浮层尺寸、滚动监听与 `ResizeObserver`:优先放在目标上方,空间不足时翻转或限制高度,保持 8px 间距与 12px 视口边距,不再轮询整个时间轴顶部。片段锚点读取可见片段的位置;范围/标尺锚点换算缩放与滚动后的坐标。空态引导在生成面板打开时隐藏且不可聚焦,保留布局以跟随按钮位置;文件拖入仍显示拖放反馈。是否切换到真实轨道继续由原生元素列表决定,不维护另一个“已插入”标记;关闭面板后仍为空或撤销至空轨道时恢复引导。| 需求 | 入口 || --- | --- |@@ -41,7 +43,7 @@ OpenDesign 的 `WorkspaceFrame` 放在原生 App 外,负责通用导航和会| 首页分类模板与精确复刻 | `studio/src/motion/HomeTemplates.tsx` || 宿主插槽 | `studio/src/motion/StudioHost.tsx`、`studio/src/components/StudioHeader.tsx` || 模型设置、生成面板、时间轴桥接 | `studio/src/motion/ModelSettings.tsx`、`MediaGenerator.tsx`、`MediaGatewayContext.tsx`、`MotionTimelineMedia.tsx` |-| 时间轴就地生成与图片修改 | `studio/src/motion/TimelineMediaBar.tsx`、`timelineMediaSelection.ts`;挂载于 `Timeline.tsx` 的原生 Provider 内 |+| 时间轴就地生成与图片修改 | `studio/src/motion/TimelineMediaBar.tsx`、`timelineMediaSelection.ts`;挂载于 `Timeline.tsx` 的原生 Provider 内;定位共用 `mediaPopoverPosition.ts`、`useMediaPopoverPosition.ts` || 共享生成合约与服务 | `shared/gateway.ts`、`gateway/`、`server.ts`、`mcp.ts` || 原生 Capture、Inspector、Export | `studio/src/components/StudioHeader.tsx` || 模板画廊、视频预览、出处与热度 | `web/template-gallery.ts`、`web/template-gallery.css`、`template-catalog.ts` |diff --git a/docs/product/changes.md b/docs/product/changes.mdindex bac0fa36..d73337af 100644--- a/docs/product/changes.md+++ b/docs/product/changes.md@@ -1,5 +1,14 @@# 公开变更记录+## REQ-20261107-001:素材浮层就近定位与空时间轴引导++- **问题与对象:** 现有创作者从空轨道、素材库或已有片段进入生成时,弹框远离触发位置;生成期间仍显示空轨道起步引导,干扰继续编辑。+- **选择与实现:** 操作栏读取片段、范围或标尺的实际锚点,生成面板继承该位置;按钮入口传入触发元素。共用浮层尺寸测量、视口限位、上下避让与滚动/尺寸监听。生成时隐藏空态引导并禁止交互,关闭且仍为空时恢复;插入后使用原生轨道,撤销至空轨道时恢复引导。+- **影响与边界:** 保留原生素材放置、撤销和工程归属;不改变模型路由、账户、费用规则或素材归属。本次改善既有剪辑流程,没有新增画像或商业化结论。+- **验证:** 定向测试覆盖定位、内容增长、滚动跟随、空态切换和原生放置;按本次公开 PR 的提交运行 Studio 类型检查、构建、仓库检查与真实浏览器交互,实际结果写在 PR。不沿用历史执行结果,也不将本地素材验证当作供应商生成或视频导出验收。+- **文档:** [English introduction](../../README.md)、[中文介绍](../README.zh-CN.md)、[使用手册](../usage.md)、[素材生成设计](media-generation-design.md#时间轴交互规则及原因)、[编辑器开发](../editor-fork.md)。+- **后续待验证:** 实际多轨创作中的遮挡、操作效率与目标系统差异;不因本次 UI 回归通过推断模型创作质量或发布状态。+## 2026-11-06:五个 Skill、界面与双语介绍同步- **问题与对象:** 现有 Agent 用户、模板作者和仓库贡献者需要一致的 Skill 名称、安装包和使用说明,避免改名后引导失效或打包漏项。diff --git a/docs/product/media-generation-design.md b/docs/product/media-generation-design.mdindex f41c2e8e..bf174e8b 100644--- a/docs/product/media-generation-design.md+++ b/docs/product/media-generation-design.md@@ -103,11 +103,12 @@ MCP 路径复用图中的 Gateway、任务和素材阶段。调用方通过 `mot| 入口 / 情境 | 当前行为 | 设计目的 || --- | --- | --- |-| 空时间轴 | 同时提供导入文件和生成素材 | 用户可以从已有素材或新素材开始,第一次操作可见 |+| 空时间轴 | 提供导入文件和生成素材;进入生成时隐藏引导并保留目标时段,关闭且仍为空时恢复;真正放入素材后切换为原生轨道,撤销至空轨道时恢复引导 | 用户开始操作后不再同时看到重复的起步提示;生成中或生成失败不冒充已插入素材 || 素材面板 | 获取、预览和管理文件;通过原生操作放入作品 | 素材可先收集,不强制立即决定剪辑位置 || 完成时间范围选择 | 以该范围优先带入开始时间和时长 | 用户已经表达了“这一段需要内容”,不重新询问位置 || 选中单个片段 | 带入片段的开始时间、时长与轨道;本地图片增加修改入口 | 将“再生成一个”与“修改这张图”明确为两种意图 || 未选片段时点击标尺 | 以点击位置为开始时间,默认 3 秒 | 为时间点快速补内容,时长可在生成面板调整 |+| 浮层位置 | 操作栏靠近选中片段、时段或标尺;生成面板沿用该目标,按钮入口则靠近实际按钮;跟随滚动与面板尺寸变化,自动上下避让和视口限位 | 位置关联用户刚操作的目标,避免从空态或较低轨道跳到整个时间线的左上方;内容增长时仍可滚动访问 || 模型 / 比例 / 数量 | 常用参数直接展示;模型特殊字段进入高级 JSON | 保留常用操作可见性,同时承认供应商输入差异;当前没有完整通用 schema 表单 || 图片修改 | 显示参考图,只列已声明参考图能力的图片模型,锁定原时段 | 改的是片段内容;需要改变编排时另做时间轴编辑 || 结果采用 | 提供放入时间轴;图片修改另有替换按钮 | 一次生成得到候选,用户决定采用方式;撤销编辑不删除生成文件或撤销供应商费用 |diff --git a/docs/usage.md b/docs/usage.mdindex 273eac8b..07a334b8 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -27,7 +27,7 @@ MCP 打开预览、创建产物、应用/复刻模板时,`previewUrl` 默认侧栏底部「模型设置」(嵌入视图保留在编辑器顶栏)提供 **Model Router / Gateway**:检测本机 Codex 的登录和内置生图能力,配置 Atlas Cloud / fal.ai Key,发现多模态模型并选择默认路由。空时间轴支持「导入文件 / 生成素材」,生成面板可以选择图片、视频、音乐、语音及参数;结果存入工程素材库,再放到选定时段。素材菜单支持预览、在播放头处添加、复制路径、下载、重命名与删除。-选中时间轴片段、Shift 拖选时段或在未选片段时点击标尺,会弹出素材操作栏。选中图片可直接「修改图片」,由本地 Codex 以原图为参考生成候选;确认替换后保留原片段时长、动画与样式,并可撤销。图片修改支持工程内 PNG/JPEG/WebP(20 MB 以内);视频、音乐和语音目前支持生成。+选中时间轴片段、Shift 拖选时段或在未选片段时点击标尺,会在目标附近弹出素材操作栏。生成面板贴近触发按钮或原选区,随滚动和面板尺寸调整位置,空间不足时切换到另一侧并限制高度。空时间轴进入生成时收起导入/生成引导;关闭且未放入素材时恢复,素材放入轨道后不再显示,撤销至空轨道时恢复。选中图片可直接「修改图片」,由本地 Codex 以原图为参考生成候选;确认替换后保留原片段时长、动画与样式,并可撤销。图片修改支持工程内 PNG/JPEG/WebP(20 MB 以内);视频、音乐和语音目前支持生成。Studio 与 MCP 共用这套模型和任务服务。云 Key 的填写不等于已验证权限/额度;调用使用用户自有账户,失败不会自动重试或换到另一付费供应商。Key 仅保存在本地独立配置中,不返回给前端/MCP,也不随工程导出。可使用环境变量 `ATLASCLOUD_API_KEY` / `FAL_KEY`。本地 Codex 需要已登录、支持 `--ephemeral` 且开启 `image_generation`;不会复制 Codex 登录 token。详细说明见 [模型网关](model-gateway.md)。diff --git a/studio/src/components/sidebar/AssetsTab.tsx b/studio/src/components/sidebar/AssetsTab.tsxindex 1eb77a1b..d23d4777 100644--- a/studio/src/components/sidebar/AssetsTab.tsx+++ b/studio/src/components/sidebar/AssetsTab.tsx@@ -1,5 +1,6 @@import { useI18n } from "../../i18n/I18n";import { useMediaGateway } from "../../motion/MediaGatewayContext";+import { mediaPopoverAnchor } from "../../motion/mediaPopoverPosition";import { buildProjectApiPath } from "../../utils/projectRouting";// fallow-ignore-file code-duplicationimport { memo, useState, useCallback, useRef, useMemo, useEffect } from "react";@@ -364,7 +365,7 @@ export const AssetsTab = memo(function AssetsTab({))}</div>{/* Import */}- {onImport && mediaGateway && <button className="motion-asset-generate" onClick={() => mediaGateway.openGenerator()}>{t("Generate media")}</button>}+ {onImport && mediaGateway && <button className="motion-asset-generate" onClick={event => mediaGateway.openGenerator({ anchor: mediaPopoverAnchor(event.currentTarget) })}>{t("Generate media")}</button>}{onImport && (<><ImportButton importing={importing} onClick={() => fileInputRef.current?.click()} />diff --git a/studio/src/motion/MediaGateway.test.tsx b/studio/src/motion/MediaGateway.test.tsxindex 229ee226..514c9bf7 100644--- a/studio/src/motion/MediaGateway.test.tsx+++ b/studio/src/motion/MediaGateway.test.tsx@@ -9,6 +9,7 @@ import { I18nProvider } from '../i18n/I18n';import type { GenerationJob, Model } from './gatewayClient';import { MediaGenerator } from './MediaGenerator';import { ArtifactViewActive } from './ArtifactViewState';+import { Timeline } from '../player/components/Timeline';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let root: Root | undefined;@@ -18,6 +19,45 @@ function Trigger() { const gateway = useMediaGateway(); return <button onClick={function button(text: string) { const found = Array.from(document.querySelectorAll('button')).find(el => el.textContent === text); if (!found) throw new Error('Missing ' + text); return found; }function type(selector: string, value: string) { const el = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(selector)!; Object.getOwnPropertyDescriptor(el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype, 'value')!.set!.call(el, value); el.dispatchEvent(new Event('input', { bubbles: true })); }+it('hides the empty guide during generation, restores it on close, and removes it after placement until undo', async () => {+ usePlayerStore.setState({ timelineProjectId: 'project', timelineReady: true, duration: 6 });+ const job = { id: 'completed', projectId: 'project', state: 'completed', prompt: 'a forest', model,+ assets: [{ path: 'assets/generated/one.png', bytes: 1000, mimeType: 'image/png' }] } as GenerationJob;+ vi.stubGlobal('fetch', vi.fn(async (url: string) => {+ if (url.includes('models/capabilities')) return Response.json({ providers: [{ id: 'codex', available: true }], routes: {} });+ if (url.includes('/models?')) return Response.json({ models: [model], nextOffset: null });+ if (url.endsWith('project/status')) return Response.json({ projectId: 'project' });+ if (url.includes('/generations?')) return Response.json({ jobs: [job] });+ throw new Error('Unexpected request ' + url);+ }));+ const place = vi.fn(async () => { usePlayerStore.setState({ elements: [{ id: 'image', tag: 'img', src: job.assets[0].path, start: 0, duration: 3, track: 0 }] }); });+ const host = document.createElement('div'); document.body.append(host); root = createRoot(host);+ await act(async () => root!.render(<I18nProvider initialLocale="en"><MediaGatewayProvider>+ <MotionTimelineMedia projectId="project" compositionId="main" disabled={false} onAssetDrop={place} />+ <Timeline onFileDrop={() => {}} />+ </MediaGatewayProvider></I18nProvider>));+ const guide = () => document.querySelector<HTMLElement>('[data-motion-empty-media]');+ const open = () => guide()!.querySelector<HTMLButtonElement>('.motion-media-primary')!.click();+ expect(guide()!.style.visibility).toBe('');+ const opener = guide()!.querySelector<HTMLButtonElement>('.motion-media-primary')!;+ vi.spyOn(opener, 'getBoundingClientRect').mockReturnValue(new DOMRect(800, 700, 80, 32));+ await act(async () => open());+ expect(guide()!.style.visibility).toBe('hidden');+ expect(guide()!.hasAttribute('inert')).toBe(true);+ const generator = document.querySelector<HTMLElement>('.motion-generator')!;+ expect(Number.parseFloat(generator.style.left)).toBeGreaterThan(12);+ await act(async () => document.querySelector<HTMLButtonElement>('[aria-label="Close media generator"]')!.click());+ expect(guide()!.style.visibility).toBe('');+ await act(async () => open());+ await act(async () => button('Place on timeline').click());+ expect(place).toHaveBeenCalledTimes(1);+ expect(guide()).toBeNull();+ await act(async () => document.querySelector<HTMLButtonElement>('[aria-label="Close media generator"]')!.click());+ expect(guide()).toBeNull();+ await act(async () => usePlayerStore.setState({ elements: [] }));+ expect(guide()!.style.visibility).toBe('');+});+it('generates through the shared API, shows only completed output, and places it at the selected range with failure reporting', async () => {vi.useFakeTimers(); usePlayerStore.setState({ timelineProjectId: 'native-project', rangeSelection: { t0: 2, t1: 7 } });const place = vi.fn().mockResolvedValue(undefined);diff --git a/studio/src/motion/MediaGatewayContext.tsx b/studio/src/motion/MediaGatewayContext.tsxindex c68ad2c4..8211af2a 100644--- a/studio/src/motion/MediaGatewayContext.tsx+++ b/studio/src/motion/MediaGatewayContext.tsx@@ -4,6 +4,7 @@ import { ModelSettings } from './ModelSettings';import { MediaGenerator } from './MediaGenerator';import { useArtifactViewActive } from './ArtifactViewState';import type { GenerateInput, GenerationJob, Modality } from './gatewayClient';+import type { MediaPopoverAnchor } from './mediaPopoverPosition';import './media-gateway.css';export type MediaPlacement = { start: number; duration: number; track: number };@@ -11,7 +12,7 @@ export type SelectedMedia = { key: string; elementId: string; path: string; src:export type TimelineMediaTarget = { projectId: string; compositionId: string; place: (asset: string, placement: MediaPlacement) => Promise<void>; replace?: (asset: string, selection: SelectedMedia) => Promise<void>; importFiles: (files: File[]) => Promise<void>; currentPlacement: () => MediaPlacement };export type MediaRequest = { id: string; modality?: Modality; prompt?: string; usage?: GenerateInput['usage'];placement?: MediaPlacement; target?: TimelineMediaTarget; onComplete?: (job: GenerationJob) => void;- selection?: SelectedMedia; intent?: 'edit'; anchorX?: number };+ selection?: SelectedMedia; intent?: 'edit'; anchor?: MediaPopoverAnchor };type GatewayUI = { openSettings: () => void; openGenerator: (input?: Omit<MediaRequest, 'id' | 'target'>) => void;bindTimeline: (target: TimelineMediaTarget | null) => void; importFiles: () => void; generationOpen: boolean };const MediaGatewayContext = createContext<GatewayUI | null>(null);diff --git a/studio/src/motion/MediaGenerator.tsx b/studio/src/motion/MediaGenerator.tsxindex 91894936..a5f1c986 100644--- a/studio/src/motion/MediaGenerator.tsx+++ b/studio/src/motion/MediaGenerator.tsx@@ -3,6 +3,8 @@ import { useI18n } from '../i18n/I18n';import { usePlayerStore } from '../player/store/playerStore';import { gatewayRequest, generateAsset, loadGateway, type GatewayStatus, type Model, type GenerationJob, type Modality } from './gatewayClient';import type { MediaRequest } from './MediaGatewayContext';+import { useMediaPopoverPosition } from './useMediaPopoverPosition';+import { useArtifactViewActive } from './ArtifactViewState';export function generationParameters(model: Model, ratio: string, duration: number, extra: Record<string, unknown>) {const [w, h] = ratio.split(':').map(Number);@@ -31,7 +33,8 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Mediconst [params, setParams] = useState('{}'), [jobs, setJobs] = useState<GenerationJob[]>([]);const [busy, setBusy] = useState(false), [error, setError] = useState(''), [placed, setPlaced] = useState<string[]>([]);const [replaced, setReplaced] = useState<string | null>(null);- const [position, setPosition] = useState({ left: 16, bottom: 200, maxHeight: 500 });+ const active = useArtifactViewActive();+ const popover = useMediaPopoverPosition(request.anchor, 640, active);const delivered = useRef(new Set<string>());const submission = useRef<{ hash: string; id: string } | null>(null);const mediaKind: Modality = kind === 'music' || kind === 'voice' ? 'audio' : kind;@@ -49,12 +52,6 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Mediwindow.addEventListener('motion:gateway-changed', refresh);return () => { active = false; window.removeEventListener('motion:gateway-changed', refresh); };}, []);- useEffect(() => {- const update = () => { const rect = document.querySelector('[data-studio-timeline]')?.getBoundingClientRect(); if (rect) { const bottom = Math.max(16, Math.min(window.innerHeight - rect.top + 8, window.innerHeight - 280)); setPosition({ left: Math.max(12, Math.min(request.anchorX ?? rect.left + 10, window.innerWidth - 660)), bottom, maxHeight: window.innerHeight - bottom - 16 }); } };- update(); window.addEventListener('resize', update);- const timer = window.setInterval(update, 500);- return () => { window.removeEventListener('resize', update); clearInterval(timer); };- }, [request.anchorX]);useEffect(() => {if (!projectId) return;let active = true, pending = false;@@ -120,7 +117,7 @@ export function MediaGenerator({ request, onClose, onSettings }: { request: Medi}const nativeProjectId = request.target?.projectId;const visibleJobs = editing ? jobs.filter(job => job.reference?.path === request.selection?.path) : jobs;- return <aside className="motion-generator motion-media-surface" style={position} role="dialog" aria-labelledby="media-generator-title" onKeyDown={event => { event.stopPropagation(); if (event.key === 'Escape') onClose(); }}>+ return <aside ref={popover.ref} className="motion-generator motion-media-surface" style={popover.style} role="dialog" aria-labelledby="media-generator-title" onKeyDown={event => { event.stopPropagation(); if (event.key === 'Escape') onClose(); }}><header><strong id="media-generator-title">{t(editing ? 'Edit image' : 'Generate media')}</strong><div className="motion-media-row"><button onClick={onSettings}>{t('Model settings')}</button><button className="motion-media-close" aria-label={t('Close media generator')} onClick={onClose}>×</button></div></header>{editing ? <div className="motion-media-reference">{request.target && <img alt={t('Reference image')} src={`/api/projects/${encodeURIComponent(request.target.projectId)}/preview/${request.selection!.path}`} />}<span>{request.selection!.label}<small>{t('Uses the original image as a reference. Choose a result to replace it.')}</small></span></div> : <div className="motion-media-tabs">{(['image', 'video', 'music', 'voice'] as Kind[]).map(value => <button key={value} aria-pressed={kind === value} onClick={() => { setKind(value); setSelected(''); if (value === 'video' && duration < 4) setDuration(5); }}>{t({ image: 'Image', video: 'Video', music: 'Music', voice: 'Voice' }[value])}</button>)}</div>}<textarea autoFocus aria-label={t('Describe your media')} placeholder={t(editing ? 'Describe how to change this image…' : 'Describe what goes here…')} maxLength={20000} value={prompt} onChange={event => setPrompt(event.target.value)} rows={3} />diff --git a/studio/src/motion/MotionTimelineMedia.tsx b/studio/src/motion/MotionTimelineMedia.tsxindex 9f05369b..ba7a8661 100644--- a/studio/src/motion/MotionTimelineMedia.tsx+++ b/studio/src/motion/MotionTimelineMedia.tsx@@ -9,6 +9,7 @@ import { readTagAttribute, readTagSnippetByTarget } from '../utils/sourcePatcherimport { resolveTimelineAssetSrc } from '../utils/timelineAssetDrop';import { encodeUrlPath } from '@hyperframes/parsers';import { selectedMedia, projectMediaPath } from './timelineMediaSelection';+import { mediaPopoverAnchor } from './mediaPopoverPosition';export function MotionTimelineMedia({ projectId, compositionId, disabled, onFileDrop, onAssetDrop }: {projectId: string; compositionId: string; disabled: boolean;@@ -56,5 +57,5 @@ export function MotionTimelineMedia({ projectId, compositionId, disabled, onFilereturn () => { bound = false; bind(null); };}, [bind, projectId, compositionId, t]);if (!gateway) return null;- return <div className="motion-timeline-media-actions"><button disabled={disabled} onClick={() => gateway.openGenerator()}>{t('Generate media')}</button><button disabled={disabled || !onFileDrop} onClick={gateway.importFiles}>{t('Import files…')}</button></div>;+ return <div className="motion-timeline-media-actions"><button disabled={disabled} onClick={event => gateway.openGenerator({ anchor: mediaPopoverAnchor(event.currentTarget) })}>{t('Generate media')}</button><button disabled={disabled || !onFileDrop} onClick={gateway.importFiles}>{t('Import files…')}</button></div>;}diff --git a/studio/src/motion/TimelineMediaBar.test.tsx b/studio/src/motion/TimelineMediaBar.test.tsxindex 3e2cbc1b..d1b7d9f9 100644--- a/studio/src/motion/TimelineMediaBar.test.tsx+++ b/studio/src/motion/TimelineMediaBar.test.tsx@@ -22,7 +22,7 @@ beforeEach(() => {const host = document.createElement('div'); host.dataset.motionStudio = ''; document.body.append(host); root = createRoot(host);const timeline = document.createElement('div'); timeline.dataset.studioTimeline = ''; document.body.append(timeline);viewport = document.createElement('div'); timeline.append(viewport); viewport.scrollLeft = 40;- vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue({ left: 100, top: 500, width: 800, height: 300 } as DOMRect);+ vi.spyOn(viewport, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 500, 800, 300));vi.spyOn(timeline, 'getBoundingClientRect').mockReturnValue({ top: 460 } as DOMRect);hooks.state = { timelineReady: true, elements: [clip], selectedElementId: clip.key!, sessionEpoch: 1,canvas: { scrollRef: { current: viewport }, pps: 100, contentOrigin: 80 }, overlays: {} } as TimelineState;@@ -66,6 +66,26 @@ it('reference selection resolves project media and rejects remote or locked mediexpect(selectedMedia({ ...clip, timelineLocked: true })).toBeUndefined();});+it('anchors both surfaces to the selected track and follows scrolling instead of the timeline header', async () => {+ const element = document.createElement('div'); element.dataset.clip = 'true'; element.dataset.elId = clip.key;+ viewport.append(element);+ const rect = vi.spyOn(element, 'getBoundingClientRect').mockReturnValue(new DOMRect(340, 690, 180, 36));+ const nativeRect = HTMLElement.prototype.getBoundingClientRect;+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {+ return this.matches('.motion-timeline-media-bar') ? new DOMRect(0, 0, 680, 88) : nativeRect.call(this);+ });+ await render();+ const surface = document.querySelector<HTMLElement>('.motion-timeline-media-bar')!;+ expect(Number.parseFloat(surface.style.top) + 88).toBe(682);+ await act(async () => button('Generate media').click());+ const request = hooks.open.mock.lastCall![0];+ expect(request.anchor.getBoundingClientRect()).toEqual({ left: 340, right: 520, top: 690, bottom: 726 });+ rect.mockReturnValue(new DOMRect(240, 610, 180, 36));+ await act(async () => viewport.dispatchEvent(new Event('scroll')));+ expect(Number.parseFloat(surface.style.top) + 88).toBe(602);+ expect(request.anchor.getBoundingClientRect()).toEqual({ left: 240, right: 420, top: 610, bottom: 646 });+});+it('removes the portalled media actions while the owning Viewer is hidden and restores them with the Viewer', async () => {const renderActive = async (active: boolean) => act(async () => root.render(<I18nProvider initialLocale="en"><ArtifactViewActive.Provider value={active}><TimelineMediaBar /></ArtifactViewActive.Provider></I18nProvider>));await renderActive(true);diff --git a/studio/src/motion/TimelineMediaBar.tsx b/studio/src/motion/TimelineMediaBar.tsxindex 6e5f373b..fbcc671d 100644--- a/studio/src/motion/TimelineMediaBar.tsx+++ b/studio/src/motion/TimelineMediaBar.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { createPortal } from 'react-dom';import { useMediaGateway } from './MediaGatewayContext';import { selectedMedia } from './timelineMediaSelection';@@ -10,6 +10,8 @@ import { useStudioShellContextOptional } from '../contexts/StudioContext';import { useI18n } from '../i18n/I18n';import { EditPopover } from '../player/components/EditModal';import { useArtifactViewActive } from './ArtifactViewState';+import { useMediaPopoverPosition } from './useMediaPopoverPosition';+import type { MediaPopoverAnchor } from './mediaPopoverPosition';export function TimelineMediaBar() {const gateway = useMediaGateway();@@ -25,7 +27,6 @@ function ConnectedTimelineMediaBar() {const selectedIds = usePlayerStore(s => s.selectedElementIds);const [interaction, setInteraction] = useState(0), [caret, setCaret] = useState<number | null>(null);const [dismissed, setDismissed] = useState(''), [prompt, setPrompt] = useState(''), [ask, setAsk] = useState(false);- const [position, setPosition] = useState({ left: 16, bottom: 240 });const range = state.overlays.showPopover ? state.overlays.rangeSelection : null;const clip = !range && selectedIds.size <= 1 ? state.elements.find(el => (el.key ?? el.id) === state.selectedElementId) : undefined;const media = selectedMedia(clip);@@ -33,6 +34,32 @@ function ConnectedTimelineMediaBar() {const duration = range ? Math.abs(range.end - range.start) : clip?.duration ?? 3;const identity = `${shell?.projectId}:${state.sessionEpoch}:${range ? 'range' : clip?.key ?? clip?.id ?? 'caret'}:${start}:${duration}:${interaction}`;const scroll = state.canvas.scrollRef;+ const clipKey = clip?.key ?? clip?.id;+ const pps = state.canvas.pps, contentOrigin = state.canvas.contentOrigin;+ const rangeY = range?.anchorY;+ const anchor = useMemo<MediaPopoverAnchor>(() => {+ let rangeOffset: number | undefined;+ return {+ get contextElement() { return scroll.current ?? undefined; },+ getBoundingClientRect: () => {+ const viewport = scroll.current;+ if (!viewport) return { left: 12, right: 12, top: window.innerHeight - 12, bottom: window.innerHeight - 12 };+ const rect = viewport.getBoundingClientRect();+ const clampX = (x: number) => Math.max(rect.left + contentOrigin, Math.min(x, rect.right));+ const clampY = (y: number) => Math.max(rect.top + RULER_H, Math.min(y, rect.bottom));+ const element = clipKey ? viewport.querySelector(`[data-clip][data-el-id="${CSS.escape(clipKey)}"]`) : null;+ if (element) {+ const clipRect = element.getBoundingClientRect();+ return { left: clampX(clipRect.left), right: clampX(clipRect.right), top: clampY(clipRect.top), bottom: clampY(clipRect.bottom) };+ }+ const left = clampX(rect.left + contentOrigin + start * pps - viewport.scrollLeft);+ if (rangeY === undefined) return { left, right: left, top: rect.top, bottom: rect.top + RULER_H };+ rangeOffset ??= rangeY - rect.top + viewport.scrollTop;+ const y = clampY(rect.top + rangeOffset - viewport.scrollTop);+ return { left, right: clampX(rect.left + contentOrigin + (start + duration) * pps - viewport.scrollLeft), top: y, bottom: y };+ },+ };+ }, [scroll, clipKey, start, duration, pps, contentOrigin, rangeY]);useEffect(() => {const viewport = scroll.current;if (!viewport) return;@@ -48,30 +75,19 @@ function ConnectedTimelineMediaBar() {return () => viewport.removeEventListener('pointerup', activate);}, [scroll, state.timelineReady, state.canvas.pps, state.canvas.contentOrigin]);useEffect(() => { setCaret(null); setAsk(false); }, [state.sessionEpoch, shell?.activeCompPath]);- useEffect(() => {- const update = () => {- const viewport = scroll.current;- const timeline = viewport?.closest('[data-studio-timeline]');- if (!viewport || !timeline) return;- const rect = viewport.getBoundingClientRect();- const x = rect.left + state.canvas.contentOrigin + start * state.canvas.pps - viewport.scrollLeft;- setPosition({ left: Math.max(12, Math.min(x - 24, window.innerWidth - 692)), bottom: Math.max(16, window.innerHeight - timeline.getBoundingClientRect().top + 8) });- };- update(); window.addEventListener('resize', update); scroll.current?.addEventListener('scroll', update);- const observer = new ResizeObserver(update); if (scroll.current) observer.observe(scroll.current);- return () => { window.removeEventListener('resize', update); scroll.current?.removeEventListener('scroll', update); observer.disconnect(); };- }, [scroll, start, state.canvas.pps, state.canvas.contentOrigin]);const hidden = readOnly || !state.timelineReady || gateway.generationOpen || playing || shell?.writeBlockedReason || shell?.renderQueue.isRendering|| state.canvas.isScrubbing || state.canvas.draggedElement || state.canvas.resizingClip || state.canvas.marqueeRect|| state.overlays.clipContextMenu || state.overlays.kfContextMenu || state.overlays.gapContextMenu|| dismissed === identity || (!range && !clip && caret === null);+ const popover = useMediaPopoverPosition(anchor, 680, !hidden && !ask);if (hidden) return null;const close = () => { setDismissed(identity); setAsk(false); };const open = (edit = false) => gateway.openGenerator({ prompt, placement: { start, duration: Math.max(.1, duration), track: clip?.track ?? 0 },- anchorX: position.left, modality: media?.modality, selection: media, ...(edit ? { intent: 'edit' as const } : {}) });+ anchor, modality: media?.modality, selection: media, ...(edit ? { intent: 'edit' as const } : {}) });const host = document.querySelector('[data-motion-studio]') ?? document.body;- return createPortal(ask ? <EditPopover initialPrompt={prompt} rangeStart={start} rangeEnd={start + duration} anchorX={position.left} anchorY={window.innerHeight - position.bottom} onClose={close} /> :- <aside className="motion-timeline-media-bar motion-media-surface" style={position} aria-label={t('Timeline media actions')} onPointerDown={e => e.stopPropagation()} onKeyDown={e => { e.stopPropagation(); if (e.key === 'Escape') close(); }}>+ const anchorRect = anchor.getBoundingClientRect();+ return createPortal(ask ? <EditPopover initialPrompt={prompt} rangeStart={start} rangeEnd={start + duration} anchorX={(anchorRect.left + anchorRect.right) / 2} anchorY={anchorRect.top - 8} onClose={close} /> :+ <aside ref={popover.ref} className="motion-timeline-media-bar motion-media-surface" style={popover.style} aria-label={t('Timeline media actions')} onPointerDown={e => e.stopPropagation()} onKeyDown={e => { e.stopPropagation(); if (e.key === 'Escape') close(); }}><div className="motion-media-context"><span>{start.toFixed(1)}–{(start + duration).toFixed(1)}s</span><span title={media?.label}>{media?.label ?? t(range ? 'Selected time range' : clip ? 'Selected clip' : 'At playhead')}</span><button className="motion-media-close" aria-label={t('Close timeline media actions')} onClick={close}>×</button></div><form onSubmit={e => { e.preventDefault(); open(); }}><input aria-label={t('Timeline media prompt')} value={prompt} onChange={e => setPrompt(e.target.value)} placeholder={t(media?.modality === 'image' ? 'Describe a new image or how to change this one…' : 'Describe what goes here…')} />diff --git a/studio/src/motion/media-gateway.css b/studio/src/motion/media-gateway.cssindex 8e3c564f..5c8d5ea5 100644--- a/studio/src/motion/media-gateway.css+++ b/studio/src/motion/media-gateway.css@@ -50,7 +50,7 @@.motion-media-reference span { min-width: 0; overflow-wrap: anywhere; }.motion-media-reference small { color: var(--motion-muted); margin-top: 4px; }.motion-generated-actions { display: flex; flex-direction: column; align-items: stretch; gap: 6px; }-.motion-timeline-media-bar { position: fixed; z-index: 180; width: min(680px, calc(100vw - 24px)); padding: 8px; }+.motion-timeline-media-bar { position: fixed; z-index: 180; width: min(680px, calc(100vw - 24px)); padding: 8px; overflow: auto; }.motion-media-context { display: flex; align-items: center; gap: 10px; min-width: 0; padding-left: 8px; color: var(--motion-muted); font-size: 11px; }.motion-media-context > span:first-child { color: var(--motion-accent); font-family: var(--motion-font-mono); white-space: nowrap; }.motion-media-context > span:nth-child(2) { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1; }diff --git a/studio/src/motion/mediaPopoverPosition.test.ts b/studio/src/motion/mediaPopoverPosition.test.tsnew file mode 100644index 00000000..f60ca263--- /dev/null+++ b/studio/src/motion/mediaPopoverPosition.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';+import { mediaPopoverPosition } from './mediaPopoverPosition';++const viewport = { left: 0, top: 0, width: 1920, height: 960 };+const panel = { width: 640, height: 440 };++describe('media popover placement', () => {+ it('sits directly above the empty timeline button and a lower selected track', () => {+ for (const anchor of [+ { left: 1133, right: 1208, top: 784, bottom: 816 },+ { left: 820, right: 960, top: 720, bottom: 756 },+ ]) {+ const result = mediaPopoverPosition(anchor, panel, viewport);+ expect(result.top + panel.height).toBe(anchor.top - 8);+ expect(result.left + panel.width / 2).toBe((anchor.left + anchor.right) / 2);+ }+ });++ it('flips below an opener near the top and stays inside the right edge', () => {+ const result = mediaPopoverPosition({ left: 1840, right: 1900, top: 50, bottom: 82 }, panel, viewport);+ expect(result.top).toBe(90);+ expect(result.left + panel.width).toBe(viewport.width - 12);+ expect(result.maxHeight).toBeGreaterThan(panel.height);+ });++ it('limits a tall result panel to the larger side without covering the opener', () => {+ const anchor = { left: 280, right: 320, top: 300, bottom: 336 };+ const result = mediaPopoverPosition(anchor, { width: 366, height: 900 }, { ...viewport, width: 390, height: 640 });+ expect(result.left).toBe(12);+ expect(result.top).toBe(344);+ expect(result.top + result.maxHeight).toBe(628);+ });++ it('keeps an offscreen anchor and oversized content within the visible viewport', () => {+ const result = mediaPopoverPosition({ left: -200, right: -100, top: 1300, bottom: 1340 }, { ...panel, height: 2000 }, viewport);+ expect(result.left).toBe(12);+ expect(result.top).toBe(12);+ expect(result.top + result.maxHeight).toBeLessThan(viewport.height);+ });+});diff --git a/studio/src/motion/mediaPopoverPosition.ts b/studio/src/motion/mediaPopoverPosition.tsnew file mode 100644index 00000000..9933f293--- /dev/null+++ b/studio/src/motion/mediaPopoverPosition.ts@@ -0,0 +1,41 @@+export type MediaAnchorRect = Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>;+export type MediaPopoverAnchor = {+ getBoundingClientRect: () => MediaAnchorRect;+ contextElement?: Element;+};++/** Keep the last visible position when an opener disappears after inserting a clip. */+export function mediaPopoverAnchor(element: HTMLElement): MediaPopoverAnchor {+ let lastRect = element.getBoundingClientRect();+ return {+ contextElement: element,+ getBoundingClientRect: () => {+ const rect = element.getBoundingClientRect();+ if (element.isConnected && (rect.width || rect.height)) lastRect = rect;+ return lastRect;+ },+ };+}++export function mediaPopoverPosition(+ anchor: MediaAnchorRect,+ panel: { width: number; height: number },+ viewport: { left: number; top: number; width: number; height: number },+) {+ const margin = 12, gap = 8;+ const leftEdge = viewport.left + margin, rightEdge = viewport.left + viewport.width - margin;+ const topEdge = viewport.top + margin, bottomEdge = viewport.top + viewport.height - margin;+ const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(value, max));+ const anchorTop = clamp(anchor.top, topEdge, bottomEdge);+ const anchorBottom = clamp(anchor.bottom, topEdge, bottomEdge);+ const above = Math.max(0, anchorTop - topEdge - gap);+ const below = Math.max(0, bottomEdge - anchorBottom - gap);+ const side = panel.height <= above || (panel.height > below && above >= below) ? 'top' : 'bottom';+ const maxHeight = side === 'top' ? above : below;+ const height = Math.min(panel.height, maxHeight);+ return {+ left: clamp((anchor.left + anchor.right - panel.width) / 2, leftEdge, rightEdge - panel.width),+ top: side === 'top' ? anchorTop - gap - height : anchorBottom + gap,+ maxHeight,+ };+}diff --git a/studio/src/motion/useMediaPopoverPosition.test.tsx b/studio/src/motion/useMediaPopoverPosition.test.tsxnew file mode 100644index 00000000..045d227e--- /dev/null+++ b/studio/src/motion/useMediaPopoverPosition.test.tsx@@ -0,0 +1,41 @@+// @vitest-environment happy-dom+import React, { act } from 'react';+import { createRoot } from 'react-dom/client';+import { expect, it, vi } from 'vitest';+import { useMediaPopoverPosition } from './useMediaPopoverPosition';+import { mediaPopoverAnchor } from './mediaPopoverPosition';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++it('repositions before paint when results grow, and follows the opener on scroll', async () => {+ const host = document.createElement('div'), opener = document.createElement('button');+ document.body.append(host, opener);+ const openerRect = vi.spyOn(opener, 'getBoundingClientRect').mockReturnValue(new DOMRect(700, 700, 80, 32));+ const nativeRect = HTMLElement.prototype.getBoundingClientRect;+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {+ return this.dataset.height ? new DOMRect(0, 0, 640, Number(this.dataset.height)) : nativeRect.call(this);+ });+ const anchor = mediaPopoverAnchor(opener);+ function Surface({ height }: { height: number }) {+ const popover = useMediaPopoverPosition(anchor, 640);+ return <aside ref={popover.ref} style={popover.style} data-height={height} />;+ }+ const root = createRoot(host);+ try {+ await act(async () => root.render(<Surface height={440} />));+ const panel = host.querySelector('aside')!;+ expect(Number.parseFloat(panel.style.top) + 440).toBe(692);+ // No resize event or observer delivery: the new content must anchor in its own commit.+ await act(async () => root.render(<Surface height={590} />));+ expect(Number.parseFloat(panel.style.top) + 590).toBe(692);+ openerRect.mockReturnValue(new DOMRect(600, 620, 80, 32));+ await act(async () => opener.dispatchEvent(new Event('scroll')));+ expect(Number.parseFloat(panel.style.top) + 590).toBe(612);+ opener.remove();+ openerRect.mockReturnValue(new DOMRect());+ expect(anchor.getBoundingClientRect().top).toBe(620);+ } finally {+ act(() => root.unmount());+ host.remove(); opener.remove(); vi.restoreAllMocks();+ }+});diff --git a/studio/src/motion/useMediaPopoverPosition.ts b/studio/src/motion/useMediaPopoverPosition.tsnew file mode 100644index 00000000..20637011--- /dev/null+++ b/studio/src/motion/useMediaPopoverPosition.ts@@ -0,0 +1,49 @@+import { useCallback, useLayoutEffect, useRef, useState, type CSSProperties } from 'react';+import { mediaPopoverPosition, type MediaPopoverAnchor } from './mediaPopoverPosition';++/** Measure the actual surface and follow its opener through scrolling and Dock resizing. */+export function useMediaPopoverPosition(anchor: MediaPopoverAnchor | undefined, width: number, enabled = true) {+ const ref = useRef<HTMLElement>(null);+ // Keep mount-time autofocus available; the layout effect sets the final position before paint.+ const [style, setStyle] = useState<CSSProperties>({ left: 12, top: 12 });+ const update = useCallback(() => {+ const panel = ref.current;+ if (!enabled || !panel) return;+ const viewport = window.visualViewport;+ const bounds = { left: viewport?.offsetLeft ?? 0, top: viewport?.offsetTop ?? 0,+ width: viewport?.width ?? window.innerWidth, height: viewport?.height ?? window.innerHeight };+ const rect = panel.getBoundingClientRect();+ const panelWidth = rect.width || Math.min(width, bounds.width - 24);+ const panelHeight = Math.max(rect.height, panel.scrollHeight + panel.offsetHeight - panel.clientHeight);+ // Programmatic callers without an opener get a centered, viewport-safe panel.+ const next = anchor ? mediaPopoverPosition(anchor.getBoundingClientRect(), { width: panelWidth, height: panelHeight }, bounds) : {+ left: bounds.left + (bounds.width - panelWidth) / 2,+ top: bounds.top + Math.max(12, (bounds.height - panelHeight) / 2),+ maxHeight: bounds.height - 24,+ };+ setStyle(previous => previous.left === next.left && previous.top === next.top && previous.maxHeight === next.maxHeight ? previous : next);+ }, [anchor, width, enabled]);+ // Results, tabs and expanded parameters can resize the panel in the same commit.+ // Measure before paint as well as observing external layout/image changes.+ useLayoutEffect(update);+ useLayoutEffect(() => {+ const panel = ref.current;+ if (!enabled || !panel) return;+ const observer = new ResizeObserver(update);+ observer.observe(panel);+ // Ancestor size changes include the split panes that can move the opener without resizing it.+ for (let element = anchor?.contextElement; element; element = element.parentElement ?? undefined) observer.observe(element);+ window.addEventListener('resize', update);+ window.addEventListener('scroll', update, { capture: true, passive: true });+ window.visualViewport?.addEventListener('resize', update);+ window.visualViewport?.addEventListener('scroll', update);+ return () => {+ observer.disconnect();+ window.removeEventListener('resize', update);+ window.removeEventListener('scroll', update, true);+ window.visualViewport?.removeEventListener('resize', update);+ window.visualViewport?.removeEventListener('scroll', update);+ };+ }, [anchor, enabled, update]);+ return { ref, style };+}diff --git a/studio/src/player/components/TimelineEmptyState.tsx b/studio/src/player/components/TimelineEmptyState.tsxindex 35cfaf81..4df58831 100644--- a/studio/src/player/components/TimelineEmptyState.tsx+++ b/studio/src/player/components/TimelineEmptyState.tsx@@ -3,6 +3,7 @@ import type { DragEventHandler } from "react";import { GUTTER, RULER_H } from "./timelineLayout";import { useMediaGateway } from "../../motion/MediaGatewayContext";import { usePlayerStore } from "../store/playerStore";+import { mediaPopoverAnchor } from "../../motion/mediaPopoverPosition";function EmptyGenerationRange() {const range = usePlayerStore(s => s.rangeSelection);@@ -27,6 +28,7 @@ export function TimelineEmptyState({}: TimelineEmptyStateProps) {const { t } = useI18n();const gateway = useMediaGateway();+ const hideGuide = !!gateway?.generationOpen && !isDragOver;return (<divclassName={`h-full border-t bg-[var(--timeline-shell-bg)] flex flex-col select-none transition-colors duration-150 ${@@ -60,6 +62,10 @@ export function TimelineEmptyState({<div className="relative flex-1 flex items-center justify-center overflow-hidden">{onFileDrop && gateway?.generationOpen && <EmptyGenerationRange />}<div+ data-motion-empty-media+ style={hideGuide ? { visibility: 'hidden' } : undefined}+ aria-hidden={hideGuide || undefined}+ inert={hideGuide}className={`flex items-center gap-3 px-6 py-3 border border-dashed rounded-lg transition-colors duration-150 ${isDragOver ? "border-studio-accent/60 bg-studio-accent/6" : "border-neutral-700/50"}`}@@ -108,7 +114,7 @@ export function TimelineEmptyState({</div>{onFileDrop && gateway && <div className="motion-empty-media-actions"><button onClick={gateway.importFiles}>{t("Import files…")}</button>- <button className="motion-media-primary" onClick={() => gateway.openGenerator()}>{t("Generate media")}</button>+ <button className="motion-media-primary" onClick={event => gateway.openGenerator({ anchor: mediaPopoverAnchor(event.currentTarget) })}>{t("Generate media")}</button></div>}</>)}