From 805d64c4bc835b73f74cc08ad28a38fc868e6c64 Mon Sep 17 00:00:00 2001 From: tinygusie2 Date: Mon, 28 Sep 2026 22:03:42 +0200 Subject: [PATCH 1/2] Editor: filmstrips, a proper render dialog, faster timeline, media pool Timeline - Clip filmstrips: the frames under each part of a clip (trim, source offset and speed included), from one strip per file cached in .cache/thumbs/. - Dragging moves the blocks instead of rebuilding the timeline; trimming takes the playhead along so the preview shows the frame you cut on. - Alt while dragging: no snapping. , and . (or Alt+arrows) nudge the selection a frame (Shift: ten), as one undo step. Dragging one of several selected items moves them all. The view scrolls along near its edges. \ or the new button fits the whole video. Shift+Delete ripple-deletes clips. - Clicking an empty spot of a track, of the preview, Esc or the new close button in the inspector deselects. Scrubbing no longer selects text, and the playhead's red handle can be dragged. Render dialog - State chip, percentage, time left, a chip per format or video, the log folded away (opened on errors), Stop that ends the whole render tree and removes only the half-written file. - A result view with a player framed to the output's shape, render time, total size, and a row per file (format, resolution, size, download). Media pool - Clips and Audio tabs with counts, search, cards with duration, a used mark and scrubbing on hover, empty states, audio rows with length and role. - Drag a clip or audio file onto the timeline: clips land on the row and time where they're dropped; audio becomes the music there (or the voice on its row). Editing and saving - Typing in a text field patches the preview directly and rebuilds it once the typing stops. - Undo restores the selection and the playhead, and history is kept per video. - A pending save survives a reload (sendBeacon) and closing the window (main.mjs flushes before it closes); brand edits too. Offline - GSAP ships as a dependency: the preview and every render project load a local copy instead of the CDN, so a blocked or missing connection no longer breaks the preview. Tests - npm run test:ui: editor tests in the installed Chrome or Edge through playwright-core (skipped without one), also run in CI. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + CONTRIBUTING.md | 5 +- README.md | 6 +- docs/ARCHITECTURE.md | 20 +- main.mjs | 8 + package-lock.json | 29 +- package.json | 7 +- src/server.mjs | 81 ++++- src/template.mjs | 2 +- src/workspace.mjs | 4 + test/server.test.mjs | 19 ++ test/ui/editor.test.mjs | 196 ++++++++++++ ui/editor.css | 204 +++++++++--- ui/editor.js | 653 ++++++++++++++++++++++++++++++++------- ui/i18n.js | 28 +- ui/index.html | 40 ++- ui/widgets.js | 2 + 17 files changed, 1121 insertions(+), 185 deletions(-) create mode 100644 test/ui/editor.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04c32b3..be727a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,3 +23,5 @@ jobs: ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - run: npm run check - run: npm test + # The editor in the runner's Chrome (playwright-core drives the installed browser, nothing to download). + - run: npm run test:ui diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a3a71c..7130b61 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -77,10 +77,13 @@ User content (video names, captions, file names, the video itself) is never tran ### Checking your change `npm test` runs the unit tests (`test/*.test.mjs`, Node's built-in runner, no extra dependencies) and -`npm run check` syntax-checks every script. Both run automatically on every pull request. Before opening a PR, +`npm run check` syntax-checks every script. `npm run test:ui` drives the editor in your installed Chrome or Edge +(`test/ui/`, through playwright-core; without either browser the tests are skipped). All three run automatically on +every pull request. Before opening a PR, please: - Run `npm run check` and `npm test`, and add a test when you change `src/` (look at the existing ones, they're short). + Changed how the timeline or undo behaves? Run `npm run test:ui` too, and add a case there. - Open the editor (`npm run serve` or `npm start`) and try what you changed, plus undo/redo. - If you touched `src/template.mjs`, render a short video (the Render button) and look at the MP4, not only the preview. diff --git a/README.md b/README.md index 1585667..f5a04a6 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,7 @@ On first start, create a project folder (*New project…*), drop a screen record | --- | --- | | `npm start` | Run the app from source (Electron) | | `npm test` / `npm run check` | Run the tests / syntax-check every script (both run in CI on every pull request) | +| `npm run test:ui` | Editor tests in your installed Chrome or Edge (dragging, trimming, splitting, undo, saving) | | `npm run serve` | Run the editor in your normal browser at http://localhost:3400, which is handy for development | | `npm run pack` | Build `dist/Motion Studio-win32-x64/Motion Studio.exe` | | `npm run sign` | Sign that `.exe` (see [signing](#signing-on-windows)) | @@ -90,6 +91,8 @@ On first start, create a project folder (*New project…*), drop a screen record Space play · S split · T tap mode · M marker · [ ] previous/next marker or beat · Ctrl+C/V copy/paste (also between videos) · Ctrl+Shift+V paste at the same time · +, . nudge the selection a frame · Alt while dragging: no snapping · +Shift+Del ripple delete a clip · \ fit the timeline · Ctrl+R render · Alt menu bar. The full list is under *Help → Keyboard shortcuts*. ## 🤝 Where you can help @@ -106,7 +109,8 @@ Everything below is open for grabs. Comment on (or open) an issue so others know **Bigger features** - 🍎 **macOS and Linux builds**: the code is cross-platform, but packaging and testing aren't there yet - 🎙️ **Exact word timing** for captions with Whisper (`hyperframes transcribe`) instead of estimates -- 🧪 **Editor tests**: the modules are covered (`npm test`); the editor UI and rendering aren't yet +- 🧪 **More tests**: the modules (`npm test`) and the timeline basics (`npm run test:ui`) are covered; rendering and + most of the inspector aren't yet - 🎞️ **Transitions between clips**: crossfades, slides and whip pans on the device screen - 🖼️ **Templates**: save a video as a reusable starting point for the next one diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7ddf0dd..af2990b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -19,6 +19,10 @@ A video is a JSON **spec**. The editor edits the spec, the server saves it, and small seekable player. The render feeds the same page to [HyperFrames](https://hyperframes.heygen.com), so the preview and the MP4 always match. +GSAP comes from the `gsap` npm package, not a CDN: the preview gets it at `/preview//gsap.min.js` and every +render project gets a copy next to its `index.html`, so neither needs the network (the editor's icon font still +comes from Google Fonts). + `npm run serve` runs the same server without Electron, and you can use the editor in a normal browser at http://localhost:3400. That's the quickest way to develop the UI. @@ -42,9 +46,18 @@ http://localhost:3400. That's the quickest way to develop the UI. - `scripts/`: Windows code signing, and `check.mjs` (a syntax check of every script). - `test/`: unit tests for the pure modules (`npm test`, Node's built-in test runner). -Every change in the editor goes through `commit(fn)`. That function takes an undo snapshot, re-renders and saves. -Position-only edits made directly in the preview (taps, callouts, captions) use `commit(fn, { quiet: true })`, -which saves without rebuilding the preview. +Every change in the editor goes through `commit(fn)`. That function takes an undo snapshot (the spec, the +selection and the playhead), re-renders and saves 350 ms later. Position-only edits made directly in the preview +(taps, callouts, captions) use `commit(fn, { quiet: true })`, which saves without rebuilding the preview. Text +fields pass `live` to `field()`: the text is patched into the preview that is on screen (`liveEdit`), and the +preview is rebuilt once typing stops. Undo history is kept per video while the editor is open. + +A pending save is not lost when the page goes away: a reload or a closed browser tab sends it with +`navigator.sendBeacon` (a POST to the same route), and the Electron window calls `window.__flushSave()` before it +closes (`main.mjs`). + +While dragging on the timeline only the blocks move (`layoutTimeline`); the timeline is rebuilt when the drag ends, +or when the rows change shape. ## Projects (workspaces) @@ -58,6 +71,7 @@ Every project is a folder. Motion Studio can switch between them (Bestand → Pr | `assets/clips/` | screen recordings (converted to H.264 on upload) and screenshots (png/jpg); deleted files go to `.trash/` | | `assets/vo/` | audio (voice and music); generated voice-overs land here; deleted files go to `.trash/` | | `renders/` | finished MP4s (`-[-4x5\|-1x1\|-16x9].mp4`), plus a `.srt` when the video has captions | +| `.cache/thumbs/` | timeline filmstrips: one JPEG row of frames per clip version (`/api/thumbs/`), safe to delete | To build without the app, run `node src/cli.mjs build [id,id…]`, then `npx hyperframes render` in `/projects`. diff --git a/main.mjs b/main.mjs index 92631a7..a39829e 100644 --- a/main.mjs +++ b/main.mjs @@ -51,6 +51,14 @@ async function createWindow() { webPreferences: { preload: join(here, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true } }); win.once('ready-to-show', () => { win.maximize(); win.show(); }); + // Closing: let the editor write its last change first (it saves 350 ms after an edit), then close for real. + let flushed = false; + win.on('close', e => { + if (flushed || smoke) return; + e.preventDefault(); flushed = true; + const flush = win.webContents.executeJavaScript('window.__flushSave?.()', true).catch(() => {}); + Promise.race([flush, new Promise(r => setTimeout(r, 3000))]).finally(() => win.destroy()); + }); // Links (e.g. to fonts.google.com) open in the normal browser. win.webContents.setWindowOpenHandler(({ url: target }) => { shell.openExternal(target); return { action: 'deny' }; }); await win.loadURL(url); diff --git a/package-lock.json b/package-lock.json index ced575b..20c0728 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,9 +7,17 @@ "": { "name": "motion-studio", "version": "1.2.0", + "license": "MIT", + "dependencies": { + "gsap": "3.14.2" + }, "devDependencies": { "@electron/packager": "^20.3.0", - "electron": "^44.4.5" + "electron": "^44.4.5", + "playwright-core": "^1.63.0" + }, + "engines": { + "node": ">=22" } }, "node_modules/@electron-internal/extract-zip": { @@ -412,6 +420,12 @@ "dev": true, "license": "ISC" }, + "node_modules/gsap": { + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/gsap/-/gsap-3.14.2.tgz", + "integrity": "sha512-P8/mMxVLU7o4+55+1TCnQrPmgjPKnwkzkXOK1asnR9Jg2lna4tEY5qBJjMmAaOBDDZWtlRjBXjLa0w53G/uBLA==", + "license": "Standard 'no charge' license: https://gsap.com/standard-license." + }, "node_modules/isbinaryfile": { "version": "4.0.10", "resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-4.0.10.tgz", @@ -530,6 +544,19 @@ "url": "https://github.com/sponsors/jet2jet" } }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/plist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", diff --git a/package.json b/package.json index 338a5d7..ce4e7d7 100644 --- a/package.json +++ b/package.json @@ -27,10 +27,15 @@ "sign:cert": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/make-selfsigned-cert.ps1", "dist": "npm run pack && npm run sign", "test": "node --test \"test/*.test.mjs\"", + "test:ui": "node --test \"test/ui/*.test.mjs\"", "check": "node scripts/check.mjs" }, "devDependencies": { "@electron/packager": "^20.3.0", - "electron": "^44.4.5" + "electron": "^44.4.5", + "playwright-core": "^1.63.0" + }, + "dependencies": { + "gsap": "3.14.2" } } diff --git a/src/server.mjs b/src/server.mjs index f02ccd3..2bed2c0 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -10,7 +10,7 @@ import { join, extname, basename, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { layouts, formats, normalize, defaultTheme, defaultChipColors } from './template.mjs'; import { toSrt } from './captions.mjs'; -import { APP_ROOT, Workspace, createWorkspace, isWorkspace, loadSettings, saveSettings, validId } from './workspace.mjs'; +import { APP_ROOT, GSAP_FILE, Workspace, createWorkspace, isWorkspace, loadSettings, saveSettings, validId } from './workspace.mjs'; const UI = join(APP_ROOT, 'ui'); const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8','.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.mp4': 'video/mp4', '.webm': 'video/webm', '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.otf': 'font/otf', '.ico': 'image/x-icon' }; @@ -42,9 +42,11 @@ const clone = o => JSON.parse(JSON.stringify(o)); const inside = (dir, file) => resolve(file).startsWith(resolve(dir)); const slug = name => basename(name, extname(name)).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-|-$/g, '') || 'file'; -function run(cmd, args, opts = {}, onLine) { +// onSpawn gets the child process, so a job can stop it. +function run(cmd, args, opts = {}, onLine, onSpawn) { return new Promise((ok, fail) => { const p = spawn(cmd, args, { shell: process.platform === 'win32' && cmd === 'npx', windowsHide: true, ...opts }); + onSpawn?.(p); let out = ''; const take = d => { const s = d.toString(); out += s; if (onLine) s.split(/[\r\n]+/).forEach(onLine); }; p.stdout.on('data', take); p.stderr.on('data', take); @@ -117,7 +119,20 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } const key = `${kind}:${id}`; if (jobs.get(key)?.state === 'running') return jobs.get(key); // span: the part of the bar the current step fills (a batch or a multi-format render runs several steps). - const job = { kind, id, state: 'running', log: [], progress: 0, span: [0, 100], started: Date.now() }; + // step: what runs now, for the progress dialog. Stopping kills the running tools (the whole tree on Windows, + // where npx runs in a shell). + const job = { kind, id, state: 'running', log: [], progress: 0, span: [0, 100], step: null, started: Date.now() }; + const procs = new Set(); + Object.defineProperties(job, { + track: { value: p => { procs.add(p); p.on('close', () => procs.delete(p)); } }, + cancel: { value: () => { + job.cancelled = true; + for (const p of procs) { + if (process.platform === 'win32') spawn('taskkill', ['/pid', String(p.pid), '/T', '/F'], { windowsHide: true }); + else p.kill('SIGTERM'); + } + } } + }); jobs.set(key, job); const log = raw => { const line = String(raw).replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '').trim(); @@ -125,8 +140,9 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } job.log.push(line); if (job.log.length > 400) job.log.shift(); const m = /(\d{1,3}(?:\.\d+)?)\s*%/.exec(line); if (m) job.progress = Math.min(100, job.span[0] + (job.span[1] - job.span[0]) * Math.min(100, +m[1]) / 100); }; - work(log, job).then(result => { job.state = 'done'; job.progress = 100; job.result = result; }) - .catch(err => { job.state = 'error'; log(String(err.message || err)); }); + work(log, job).then(result => { job.state = job.cancelled ? 'cancelled' : 'done'; if (!job.cancelled) job.progress = 100; job.result = result; }) + .catch(err => { job.state = job.cancelled ? 'cancelled' : 'error'; log(job.cancelled ? 'Gestopt.' : String(err.message || err)); }) + .finally(() => { job.finished = Date.now(); }); return job; } @@ -136,14 +152,20 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } await ensureIcons().catch(e => log(`Icoon-font niet bijgewerkt: ${e.message}`)); const downloads = join(homedir(), 'Downloads'); const toDownloads = settings.copyToDownloads && existsSync(downloads); - const fmts = w.formatsOf(v), files = []; + const fmts = w.formatsOf(v), files = [], outputs = []; for (const [k, f] of fmts.entries()) { - if (job) job.span = [span[0] + (span[1] - span[0]) * k / fmts.length, span[0] + (span[1] - span[0]) * (k + 1) / fmts.length]; - const dir = w.writeProject(v, f), name = w.renderName(v, f); + if (job) { + job.span = [span[0] + (span[1] - span[0]) * k / fmts.length, span[0] + (span[1] - span[0]) * (k + 1) / fmts.length]; + job.step = { ...job.step, i: k, n: fmts.length, format: f }; + } + const dir = w.writeProject(v, f), name = w.renderName(v, f), out = join(w.p.renders, name); log(`Renderen naar ${name} (${f})…`); - await run('npx', ['--yes', hf, 'render', dir, '-o', `../renders/${name}`], { cwd: w.p.projects }, log); - if (toDownloads) { copyFileSync(join(w.p.renders, name), join(downloads, name)); log(`Gekopieerd naar Downloads\\${name}`); } + // A stopped render can leave half a file behind: remove it, but never an earlier finished render. + try { await run('npx', ['--yes', hf, 'render', dir, '-o', `../renders/${name}`], { cwd: w.p.projects }, log, job?.track); } + catch (e) { if (job?.cancelled && existsSync(out) && statSync(out).mtimeMs >= job.started) rmSync(out, { force: true }); throw e; } + if (toDownloads) { copyFileSync(out, join(downloads, name)); log(`Gekopieerd naar Downloads\\${name}`); } files.push(name); + outputs.push({ file: name, format: f, w: formats[f].w, h: formats[f].h, size: statSync(out).size }); } // Subtitle sidecar for platforms that take an uploaded .srt (YouTube, LinkedIn, TikTok ads); the same for every format. const srtName = w.renderName(v).replace(/\.mp4$/, '.srt'); @@ -152,7 +174,7 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } writeFileSync(join(w.p.renders, srtName), srt, 'utf8'); log(`Ondertitels: ${srtName}`); if (toDownloads) copyFileSync(join(w.p.renders, srtName), join(downloads, srtName)); } - return { file: files[0], files, srt: srt ? srtName : null }; + return { file: files[0], files, outputs, srt: srt ? srtName : null, dur: v.dur ?? 15 }; } // Beats of a music file (source time), detected once by `hyperframes beats` in a scratch project and cached // next to the TTS cache, keyed by size + mtime so a replaced file is analysed again. @@ -184,9 +206,34 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } beatJobs.set(cache, job); return job; } + // Filmstrip of a clip for the timeline: frames `step` seconds apart in one JPEG row, made once per file version + // (keyed by size + mtime) in /.cache/thumbs. + const thumbJobs = new Map(); + function thumbsOf(name) { + const file = join(ws.p.clips, basename(name)); + if (!existsSync(file) || IMAGE_EXT.includes(extname(file).toLowerCase())) return Promise.reject(new Error('Geen videoclip.')); + const st = statSync(file); + const key = `${slug(name)}-${createHash('sha1').update(`${name}:${st.size}:${st.mtimeMs}`).digest('hex').slice(0, 10)}`; + const dir = join(ws.root, '.cache', 'thumbs'), meta = join(dir, `${key}.json`); + if (existsSync(meta)) return Promise.resolve(JSON.parse(readFileSync(meta, 'utf8'))); + if (!thumbJobs.has(key)) thumbJobs.set(key, (async () => { + mkdirSync(dir, { recursive: true }); + const dur = +(await run('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file])).trim(); + if (!(dur > 0)) throw new Error('Onbekende clipduur.'); + const step = Math.max(0.25, dur / 120), n = Math.max(1, Math.ceil(dur / step)); + await run('ffmpeg', ['-y', '-hide_banner', '-loglevel', 'error', '-i', file, '-an', '-vf', `fps=${(1 / step).toFixed(5)},scale=-2:96,tile=${n}x1`, '-frames:v', '1', '-q:v', '5', join(dir, `${key}.jpg`)]); + const info = { src: `/thumbs/${key}.jpg`, n, step, dur }; + writeFileSync(meta, JSON.stringify(info)); + return info; + })().finally(() => thumbJobs.delete(key))); + return thumbJobs.get(key); + } + async function renderBatch(ids, log, job) { const results = []; for (const [i, id] of ids.entries()) { + if (job.cancelled) break; + job.step = { video: id, vi: i, vn: ids.length }; log(`▶ ${id} (${i + 1}/${ids.length})`); try { results.push({ id, ...(await renderVideo(id, log, job, [100 * i / ids.length, 100 * (i + 1) / ids.length])) }); } catch (e) { log(`✗ ${id}: ${e.message || e}`); results.push({ id, error: String(e.message || e) }); } @@ -260,7 +307,7 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } } const previewHtml = (v, fmt) => ws.html(v, fmt) - .replace('\n \n '); function state() { @@ -323,16 +370,20 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } ensureIcons().catch(e => console.warn('icons:', e.message)); return send(res, 200, previewHtml(ws.readSpec(m[1]), url.searchParams.get('f')), MIME['.html']); } + if (/^\/preview\/[a-z0-9-]+\/gsap\.min\.js$/.test(p)) return sendFile(req, res, GSAP_FILE); if ((m = /^\/(?:preview\/[a-z0-9-]+\/)?assets\/(.+)$/.exec(p))) { const file = join(ws.p.assets, m[1]); return inside(ws.p.assets, file) ? sendFile(req, res, file) : send(res, 403, 'no'); } if ((m = /^\/renders\/([^/]+)$/.exec(p))) return sendFile(req, res, join(ws.p.renders, basename(m[1]))); + if ((m = /^\/thumbs\/([^/]+\.jpg)$/.exec(p))) return sendFile(req, res, join(ws.root, '.cache', 'thumbs', basename(m[1]))); + if ((m = /^\/api\/thumbs\/([^/]+)$/.exec(p))) return send(res, 200, await thumbsOf(m[1])); if ((m = /^\/api\/videos\/([a-z0-9-]+)$/.exec(p))) { const id = m[1]; if (method === 'GET') return ws.hasSpec(id) ? send(res, 200, ws.readSpec(id)) : send(res, 404, { error: 'not found' }); - if (method === 'PUT') { ws.writeSpec(id, await readJsonBody(req)); return send(res, 200, { ok: true }); } + // POST too: navigator.sendBeacon (the last save when the page closes) can only post. + if (method === 'PUT' || method === 'POST') { ws.writeSpec(id, await readJsonBody(req)); return send(res, 200, { ok: true }); } if (method === 'DELETE') { ws.trashSpec(id); return send(res, 200, { ok: true }); } } if (p === '/api/videos' && method === 'POST') { @@ -348,7 +399,7 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } if ((m = /^\/api\/brands\/([a-z0-9-]+)$/.exec(p))) { const id = m[1]; - if (method === 'PUT') { ws.writeBrand(id, await readJsonBody(req)); return send(res, 200, { ok: true }); } + if (method === 'PUT' || method === 'POST') { ws.writeBrand(id, await readJsonBody(req)); return send(res, 200, { ok: true }); } } if (p === '/api/brands' && method === 'POST') { const { id, from, name } = await readJsonBody(req); @@ -403,6 +454,7 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } if (!ids.length) return send(res, 400, { error: 'Kies minstens één video.' }); return send(res, 200, startJob('batch', 'all', (log, job) => renderBatch(ids, log, job))); } + if (method === 'DELETE') jobs.get('batch:all')?.cancel(); return send(res, 200, jobs.get('batch:all') || { state: 'idle' }); } if ((m = /^\/api\/(render|vo)\/([a-z0-9-]+)$/.exec(p))) { @@ -411,6 +463,7 @@ export async function startServer({ port = 3400, host = '127.0.0.1', workspace } if (!ws.hasSpec(id)) return send(res, 404, { error: 'not found' }); return send(res, 200, startJob(kind, id, kind === 'render' ? (log, job) => renderVideo(id, log, job) : log => voiceOver(id, log))); } + if (method === 'DELETE') jobs.get(`${kind}:${id}`)?.cancel(); return send(res, 200, jobs.get(`${kind}:${id}`) || { state: 'idle' }); } diff --git a/src/template.mjs b/src/template.mjs index be29d64..79a08e5 100644 --- a/src/template.mjs +++ b/src/template.mjs @@ -278,7 +278,7 @@ export function build(v, brand, fmt = '9:16') { ${esc(brand.name)} — ${esc(v.overline)} - +