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
feat(editor): unify upload into the text editor + 📎 in prompt bar (#6)
Joey-nexu4b0e0d936644
diff --git a/src/components/ai-prompt-bar.tsx b/src/components/ai-prompt-bar.tsxindex b3c3a362..c22b0315 100644--- a/src/components/ai-prompt-bar.tsx+++ b/src/components/ai-prompt-bar.tsx@@ -1,21 +1,29 @@"use client";-import { useState } from "react";+import { useRef, useState } from "react";import { useStore } from "@/lib/store";import { useT } from "@/lib/i18n";import { useDraft } from "@/lib/use-draft";+import { useUploadFile } from "@/lib/use-upload";++const ACCEPT_TYPES =+ ".md,.txt,.csv,.tsv,.xlsx,.xls,.json,.sql,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp,.svg,.html,.htm,.xml,.log";/*** Sticky one-line input pinned to the bottom of the editor's Text tab. The* user types a natural-language instruction ("write a tweet about X"); the* selected agent streams a markdown draft that's appended below the current- * editor content. Convert (HTML output) is unaffected — this is a separate- * /api/draft endpoint that prompts the agent for plain markdown.+ * editor content. The 📎 button on the same row reuses the same upload+ * pipeline as the textarea drag-and-drop target, so users can attach a file+ * without leaving this row. Convert (HTML output) is unaffected — Draft is+ * a separate /api/draft endpoint that prompts the agent for plain markdown.*/export function AiPromptBar() {const [value, setValue] = useState("");+ const fileInputRef = useRef<HTMLInputElement>(null);const agent = useStore((s) => s.selectedAgent);const { run, cancel, status, error } = useDraft();+ const { ingest } = useUploadFile();const t = useT();const isRunning = status === "running";@@ -61,6 +69,25 @@ export function AiPromptBar() {color: "var(--ink)",}}/>+ <button+ onClick={() => fileInputRef.current?.click()}+ className="shrink-0 inline-flex items-center gap-1 rounded-full px-2.5 py-1.5 text-[12px] text-[var(--ink-mute)] transition-colors hover:bg-[var(--surface)] hover:text-[var(--ink)]"+ title={t("editor.attachTooltip")}+ >+ <span aria-hidden>📎</span>+ <span className="hidden text-[11.5px] sm:inline">{t("editor.attach")}</span>+ </button>+ <input+ ref={fileInputRef}+ type="file"+ multiple+ className="hidden"+ accept={ACCEPT_TYPES}+ onChange={(e) => {+ ingest(e.target.files);+ e.target.value = "";+ }}+ /><buttononClick={onSubmit}disabled={!isRunning && !canSubmit}diff --git a/src/components/editor-pane.tsx b/src/components/editor-pane.tsxindex 4aeb8131..0e874704 100644--- a/src/components/editor-pane.tsx+++ b/src/components/editor-pane.tsx@@ -5,30 +5,30 @@ import { useStore, selectActiveTask, usePersistHydrated } from "@/lib/store";import { detectFormat } from "@/lib/parsers/auto";import { useAutosave, relativeTime } from "@/lib/use-autosave";import { downloadMarkdown } from "@/lib/export/download";+import { useUploadFile } from "@/lib/use-upload";import { useT, type DictKey } from "@/lib/i18n";-import { UploadDropzone } from "./upload-dropzone";import { DraftsMenu } from "./drafts-menu";import { SamplesGallery } from "./samples-gallery";import { FormatsGallery } from "./formats-gallery";import { AiPromptBar } from "./ai-prompt-bar";-const TAB_KEY: Record<"text" | "upload" | "formats" | "samples", DictKey> = {+const TAB_KEY: Record<"text" | "formats" | "samples", DictKey> = {text: "editor.tab.text",- upload: "editor.tab.upload",formats: "editor.tab.formats",samples: "editor.tab.samples",};export function EditorPane() {- const [tab, setTab] = useState<"text" | "upload" | "formats" | "samples">("text");+ const [tab, setTab] = useState<"text" | "formats" | "samples">("text");+ const [dragActive, setDragActive] = useState(false);const hydrated = usePersistHydrated();const content = useStore((s) => selectActiveTask(s)?.content ?? "");const setContent = useStore((s) => s.setContent);const format = useStore((s) => selectActiveTask(s)?.format ?? "text");const setFormat = useStore((s) => s.setFormat);- const filename = useStore((s) => selectActiveTask(s)?.filename);const setFilename = useStore((s) => s.setFilename);const { status: saveStatus, savedAt } = useAutosave();+ const { ingest } = useUploadFile();const t = useT();const detected = useMemo(() => detectFormat(content), [content]);@@ -42,8 +42,8 @@ export function EditorPane() {style={{ borderBottom: "1px solid var(--line-faint)" }}><div className="flex items-center justify-between gap-3">- <div className="flex shrink-0 gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">- {(["text", "upload", "formats", "samples"] as const).map((id) => (+ <div className="flex shrink-0 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ {(["text", "formats", "samples"] as const).map((id) => (<buttonkey={id}onClick={() => setTab(id)}@@ -64,7 +64,7 @@ export function EditorPane() {{hasContent && (<div className="flex flex-wrap items-center justify-end gap-x-2.5 gap-y-1 whitespace-nowrap text-[11px] text-[var(--ink-faint)]"><button- onClick={() => downloadMarkdown(content, filename?.replace(/\.[^.]+$/, "") || "draft")}+ onClick={() => downloadMarkdown(content, "draft")}className="shrink-0 whitespace-nowrap text-[10px] uppercase tracking-[0.14em] text-[var(--ink-faint)] hover:text-[var(--ink)] transition-colors"title={t("editor.backupTooltip")}>@@ -72,15 +72,6 @@ export function EditorPane() {</button><DraftsMenu /><span className="shrink-0 opacity-40">|</span>- {filename && (- <span- className="max-w-[160px] shrink-0 truncate rounded-md px-1.5 py-0.5 font-mono"- style={{ background: "var(--paper)", color: "var(--ink-soft)" }}- title={filename}- >- {filename}- </span>- )}<span className="shrink-0 whitespace-nowrap"><code className="font-mono text-[var(--ink-soft)]">{format || detected}</code><span className="mx-1 opacity-40">·</span>@@ -92,7 +83,32 @@ export function EditorPane() {<div className="relative flex-1 overflow-hidden">{tab === "text" && (- <div className="flex h-full flex-col">+ <div+ className="flex h-full flex-col"+ onDragEnter={(e) => {+ if (e.dataTransfer?.types?.includes("Files")) {+ e.preventDefault();+ setDragActive(true);+ }+ }}+ onDragOver={(e) => {+ if (e.dataTransfer?.types?.includes("Files")) {+ e.preventDefault();+ }+ }}+ onDragLeave={(e) => {+ // Only deactivate when leaving the outer container, not when+ // crossing into a child element inside it.+ if (e.currentTarget === e.target || !e.currentTarget.contains(e.relatedTarget as Node)) {+ setDragActive(false);+ }+ }}+ onDrop={(e) => {+ e.preventDefault();+ setDragActive(false);+ ingest(e.dataTransfer?.files ?? null);+ }}+ ><div className="relative flex-1 overflow-hidden">{!hydrated && (<div className="absolute inset-0 flex items-center justify-center pointer-events-none z-10">@@ -113,15 +129,24 @@ export function EditorPane() {spellCheck={false}disabled={!hydrated}/>+ {dragActive && (+ <div+ className="pointer-events-none absolute inset-2 z-20 flex flex-col items-center justify-center gap-2 rounded-2xl text-center"+ style={{+ background: "color-mix(in srgb, var(--paper) 92%, transparent)",+ border: "2px dashed var(--coral)",+ color: "var(--ink)",+ }}+ >+ <div className="text-3xl">📂</div>+ <div className="text-[13px] font-semibold">{t("editor.dropTitle")}</div>+ <div className="text-[11px] text-[var(--ink-faint)]">{t("editor.dropHint")}</div>+ </div>+ )}</div><AiPromptBar /></div>)}- {tab === "upload" && (- <div className="h-full p-4">- <UploadDropzone />- </div>- )}{tab === "formats" && (<FormatsGallery onLoaded={() => setTab("text")} />)}diff --git a/src/components/upload-dropzone.tsx b/src/components/upload-dropzone.tsxdeleted file mode 100644index 3e9f1390..00000000--- a/src/components/upload-dropzone.tsx+++ /dev/null@@ -1,86 +0,0 @@-"use client";--import { useCallback, useRef, useState } from "react";-import { parseFile } from "@/lib/parsers/file";-import { useStore } from "@/lib/store";-import { useT } from "@/lib/i18n";--export function UploadDropzone() {- const [active, setActive] = useState(false);- const inputRef = useRef<HTMLInputElement>(null);- const setContent = useStore((s) => s.setContent);- const setFormat = useStore((s) => s.setFormat);- const setFilename = useStore((s) => s.setFilename);- const addAsset = useStore((s) => s.addAsset);- const pushLog = useStore((s) => s.pushLog);- const t = useT();-- const onFiles = useCallback(- async (files: FileList | null) => {- if (!files || files.length === 0) return;- const file = files[0];- try {- const parsed = await parseFile(file);- // For images, replace the inline base64 data URL in `text` with a- // short `asset:<id>` placeholder so the textarea stays readable.- // The real bytes live in task.assets and are inlined back at- // Convert time.- let bodyText = parsed.text;- if (parsed.format === "image" && parsed.dataUrl) {- const id = addAsset(parsed.dataUrl);- bodyText = ``;- }- setContent(bodyText);- setFormat(parsed.format);- setFilename(parsed.filename);- pushLog({- kind: "info",- text: t("upload.loadedLog", { name: parsed.filename ?? "", fmt: parsed.format }),- });- } catch (e) {- pushLog({- kind: "error",- text: t("upload.failedLog", { err: e instanceof Error ? e.message : String(e) }),- });- }- },- [setContent, setFormat, setFilename, addAsset, pushLog, t],- );-- return (- <div- onDragOver={(e) => {- e.preventDefault();- setActive(true);- }}- onDragLeave={() => setActive(false)}- onDrop={(e) => {- e.preventDefault();- setActive(false);- onFiles(e.dataTransfer?.files ?? null);- }}- className={`flex h-full flex-col items-center justify-center gap-3 rounded-2xl p-8 text-center text-sm transition-colors ${- active ? "dropzone-active" : ""- }`}- style={{- background: "var(--paper)",- border: "2px dashed var(--line)",- color: "var(--ink-mute)",- }}- >- <div className="text-4xl">📂</div>- <div className="font-semibold text-[var(--ink)] text-[15px]">{t("upload.title")}</div>- <div className="text-xs text-[var(--ink-faint)]">{t("upload.types")}</div>- <button onClick={() => inputRef.current?.click()} className="btn-ink mt-2">- {t("upload.button")}- </button>- <input- ref={inputRef}- type="file"- className="hidden"- accept=".md,.txt,.csv,.tsv,.xlsx,.xls,.json,.sql,.yaml,.yml,.png,.jpg,.jpeg,.gif,.webp,.svg,.html,.htm,.xml,.log"- onChange={(e) => onFiles(e.target.files)}- />- </div>- );-}diff --git a/src/lib/i18n.ts b/src/lib/i18n.tsindex 642324b9..560ce2f0 100644--- a/src/lib/i18n.ts+++ b/src/lib/i18n.ts@@ -100,9 +100,12 @@ export interface Dict {// Editor pane"editor.tab.text": string;- "editor.tab.upload": string;"editor.tab.samples": string;"editor.tab.formats": string;+ "editor.attach": string;+ "editor.attachTooltip": string;+ "editor.dropTitle": string;+ "editor.dropHint": string;"editor.backup": string;"editor.backupTooltip": string;"editor.restoring": string;@@ -226,9 +229,6 @@ export interface Dict {"drafts.emptyPreview": string;// Upload dropzone- "upload.title": string;- "upload.types": string;- "upload.button": string;"upload.loadedLog": string;"upload.failedLog": string;@@ -372,9 +372,12 @@ const en: Dict = {"We ship English and Simplified Chinese today. Adding a locale means dropping a dictionary into src/lib/i18n.ts — contributors welcome.","editor.tab.text": "✏️ Text",- "editor.tab.upload": "⬆️ Upload","editor.tab.samples": "✨ Samples","editor.tab.formats": "📋 Formats",+ "editor.attach": "Attach",+ "editor.attachTooltip": "Drop a file or click to attach — appended to the editor below",+ "editor.dropTitle": "Drop to attach",+ "editor.dropHint": ".md .txt .csv .tsv .xlsx .json .sql .yaml .png .jpg — appended to your editor","editor.backup": "⤓ Backup","editor.backupTooltip": "Download the current content as a .md / .txt backup","editor.restoring": "Restoring last content…",@@ -497,9 +500,6 @@ const en: Dict = {"drafts.chars": "{n} chars","drafts.emptyPreview": "(empty)",- "upload.title": "Drop a file here",- "upload.types": "Supports .md .txt .csv .tsv .xlsx .json .sql .yaml .png .jpg",- "upload.button": "Choose a file","upload.loadedLog": "Loaded {name} ({fmt})","upload.failedLog": "Parse failed: {err}",@@ -642,9 +642,12 @@ const zhCN: Dict = {"目前发布的是 English 和简体中文。增加一种语言只需要在 src/lib/i18n.ts 里加一份字典 — 欢迎贡献。","editor.tab.text": "✏️ 输入",- "editor.tab.upload": "⬆️ 上传","editor.tab.samples": "✨ 示例","editor.tab.formats": "📋 格式",+ "editor.attach": "附加文件",+ "editor.attachTooltip": "拖文件进来或点这里上传 — 自动接到编辑器内容末尾",+ "editor.dropTitle": "松手附加",+ "editor.dropHint": ".md .txt .csv .tsv .xlsx .json .sql .yaml .png .jpg — 内容会接到编辑器末尾","editor.backup": "⤓ 备份","editor.backupTooltip": "把当前内容下载为 .md / .txt 备份文件","editor.restoring": "恢复上次内容…",@@ -764,9 +767,6 @@ const zhCN: Dict = {"drafts.chars": "{n} 字","drafts.emptyPreview": "(空)",- "upload.title": "把文件拖到这里",- "upload.types": "支持 .md .txt .csv .tsv .xlsx .json .sql .yaml .png .jpg",- "upload.button": "选择文件","upload.loadedLog": "已加载 {name} ({fmt})","upload.failedLog": "解析失败: {err}",diff --git a/src/lib/parsers/file.ts b/src/lib/parsers/file.tsindex 6bb4cb2f..2115da9d 100644--- a/src/lib/parsers/file.ts+++ b/src/lib/parsers/file.ts@@ -49,7 +49,7 @@ export async function parseFile(file: File): Promise<FileParseResult> {r.onerror = reject;r.readAsDataURL(file);});- // Caller (upload-dropzone) is expected to register the dataUrl as an+ // Caller (useUploadFile) is expected to register the dataUrl as an// asset and substitute an `asset:<id>` token into `text` before writing// it to the editor — keeping the textarea readable. We still return the// raw inline form here as a fallback for legacy callers.diff --git a/src/lib/use-convert.ts b/src/lib/use-convert.tsindex beca3479..662f9c49 100644--- a/src/lib/use-convert.ts+++ b/src/lib/use-convert.ts@@ -44,7 +44,7 @@ export function useConvert() {const startedAt = Date.now();store.patchStatsFor(taskId, { startedAt });- // Inline `asset:<id>` placeholders (created by upload-dropzone for+ // Inline `asset:<id>` placeholders (created by useUploadFile for// images) back into real `data:image/...` URLs before the agent// sees the prompt. Editor stays readable; agent gets the bytes.const taskWithAssets = store.tasks.find((t) => t.id === taskId);diff --git a/src/lib/use-upload.ts b/src/lib/use-upload.tsnew file mode 100644index 00000000..49f6871a--- /dev/null+++ b/src/lib/use-upload.ts@@ -0,0 +1,63 @@+"use client";++import { useCallback } from "react";+import { parseFile } from "@/lib/parsers/file";+import { useStore } from "@/lib/store";+import { useT } from "@/lib/i18n";++/**+ * Shared upload pipeline used by the editor's textarea drop target and+ * paperclip button. Parses one or more files via `parseFile`, registers+ * image bytes as task assets (so the textarea keeps a short+ * `` placeholder), and **appends** the resulting+ * body text to the active task's content. Empty content gets the upload+ * verbatim; non-empty content gets a blank-line separator before the+ * appended payload.+ *+ * Returns `{ ingest }` — call with a `FileList` or array of `File`. Errors+ * surface in the task log via `pushLog`.+ */+export function useUploadFile() {+ const addAsset = useStore((s) => s.addAsset);+ const pushLog = useStore((s) => s.pushLog);+ const t = useT();++ const ingest = useCallback(+ async (files: FileList | File[] | null) => {+ if (!files || files.length === 0) return;+ const list = Array.from(files);+ for (const file of list) {+ try {+ const parsed = await parseFile(file);+ let bodyText = parsed.text;+ if (parsed.format === "image" && parsed.dataUrl) {+ const id = addAsset(parsed.dataUrl);+ bodyText = ``;+ }+ // Read latest content fresh inside the loop so successive uploads+ // append to one another rather than racing on a stale closure.+ const store = useStore.getState();+ const prev = store.tasks.find((x) => x.id === store.activeTaskId)?.content ?? "";+ const sep = prev.length === 0 ? "" : prev.endsWith("\n\n") ? "" : prev.endsWith("\n") ? "\n" : "\n\n";+ store.setContent(prev + sep + bodyText);+ // Format flag: sticky to the *first* upload's format so converters+ // that branch on csv / json / etc. still pick something reasonable.+ // For mixed appends we leave whatever was set previously.+ if (!prev) store.setFormat(parsed.format);+ pushLog({+ kind: "info",+ text: t("upload.loadedLog", { name: parsed.filename ?? "", fmt: parsed.format }),+ });+ } catch (e) {+ pushLog({+ kind: "error",+ text: t("upload.failedLog", { err: e instanceof Error ? e.message : String(e) }),+ });+ }+ }+ },+ [addAsset, pushLog, t],+ );++ return { ingest };+}