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..a3af5aa 100644
--- a/package.json
+++ b/package.json
@@ -22,15 +22,20 @@
"start": "electron .",
"serve": "node src/server.mjs",
"build": "node src/cli.mjs build",
- "pack": "electron-packager . \"Motion Studio\" --platform=win32 --arch=x64 --out=dist --overwrite --icon=resources/icon.ico --ignore=^/dist --ignore=^/scripts --ignore=^/docs --ignore=^/test --ignore=^/.git --ignore=^/.claude --no-asar",
+ "pack": "node scripts/pack.mjs",
"sign": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/sign.ps1",
"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/scripts/pack.mjs b/scripts/pack.mjs
new file mode 100644
index 0000000..4ef0a13
--- /dev/null
+++ b/scripts/pack.mjs
@@ -0,0 +1,18 @@
+// Packages the Windows app into dist/Motion Studio-win32-x64 (npm run pack).
+// The options live here instead of on the command line: npm runs scripts through cmd.exe on Windows, which eats the
+// `^` of `--ignore=^/dist`, and an unanchored /dist also threw away node_modules/gsap/dist.
+import { packager } from '@electron/packager';
+
+const [out] = await packager({
+ dir: '.',
+ name: 'Motion Studio',
+ platform: 'win32',
+ arch: 'x64',
+ out: 'dist',
+ overwrite: true,
+ icon: 'resources/icon.ico',
+ asar: false,
+ // Paths are relative to the project, starting with /.
+ ignore: [/^\/dist(\/|$)/, /^\/scripts(\/|$)/, /^\/docs(\/|$)/, /^\/test(\/|$)/, /^\/\.git/, /^\/\.claude(\/|$)/]
+});
+console.log(`Wrote ${out}`);
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