@biunow/agent-biutalk 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/server.js CHANGED
@@ -13,8 +13,21 @@ import {
13
13
  findLatestMp4,
14
14
  runCommand,
15
15
  } from '../lib/host.mjs';
16
+ import { findRecipe, loadRecipes, recipeView } from '../../_shared/studio/recipes.mjs';
16
17
 
17
18
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
19
+ const RECIPES = loadRecipes(path.join(root, '风格提示词.md'));
20
+
21
+ function presentLook(look) {
22
+ return {
23
+ ...look,
24
+ recipe: recipeView(findRecipe(RECIPES, [look.id, look.name, look.desc]), {
25
+ narration: 'required',
26
+ attachment: 'optional',
27
+ hint: '成片自带解说,不用上传录音。参考材料可以不附。',
28
+ }),
29
+ };
30
+ }
18
31
 
19
32
  const LOOKS = [
20
33
  { id: 'paper', name: 'Paper', desc: '手绘友好,默认' },
@@ -102,7 +115,7 @@ createAgentServer({
102
115
  agent: 'biutalk',
103
116
  name: manifest.name || 'BiuTalk',
104
117
  description: manifest.description || '',
105
- looks: LOOKS,
118
+ looks: LOOKS.map(presentLook),
106
119
  sizes: SIZES,
107
120
  canExport: cfg.canExport,
108
121
  enginePresent: !!(cfg.engineRoot && explainrooBin(cfg.engineRoot)),
package/lib/host.mjs CHANGED
@@ -300,10 +300,43 @@ export function seedSkillIntoProject(projectDir, packageRoot, skillId) {
300
300
  return dest;
301
301
  }
302
302
 
303
- /** Newest MP4 under a project (prefer out/, then recursive). */
304
- export function findLatestMp4(rootDir, { maxDepth = 4 } = {}) {
305
- if (!rootDir || !fs.existsSync(rootDir)) return null;
303
+ /** explainroo 的成片是 out/video.mp4。build/segments/seg-05.mp4 和 draft 渲完会删,不能当成片。 */
304
+ export function isIntermediateMp4(filePath) {
305
+ const base = path.basename(String(filePath || '')).toLowerCase();
306
+ if (/^seg[-_]\d+\.mp4$/.test(base)) return true;
307
+ if (/^draft([-.]|$)/.test(base)) return true;
308
+ const parts = String(filePath || '').split(/[/\\]/).map((part) => part.toLowerCase());
309
+ return parts.includes('build') || parts.includes('segments');
310
+ }
311
+
312
+ /** 记录里的文件被删掉或改名时,在同一目录找「原名开头」的现片。 */
313
+ export function rescueMissingFilm(filePath) {
314
+ const file = String(filePath || '');
315
+ if (!file) return '';
316
+ if (fs.existsSync(file) && !isIntermediateMp4(file)) return file;
317
+ const dir = path.dirname(file);
318
+ if (!fs.existsSync(dir)) return '';
319
+ const stem = path.basename(file, path.extname(file)).toLowerCase();
320
+ if (!stem) return '';
321
+ let best = null;
322
+ let names = [];
323
+ try { names = fs.readdirSync(dir); } catch { return ''; }
324
+ for (const name of names) {
325
+ if (!name.toLowerCase().endsWith('.mp4')) continue;
326
+ if (!name.toLowerCase().startsWith(stem)) continue;
327
+ const full = path.join(dir, name);
328
+ if (isIntermediateMp4(full)) continue;
329
+ let st;
330
+ try { st = fs.statSync(full); } catch { continue; }
331
+ if (!st.isFile()) continue;
332
+ if (!best || st.mtimeMs > best.mtimeMs) best = { path: full, mtimeMs: st.mtimeMs, size: st.size };
333
+ }
334
+ return best ? best.path : '';
335
+ }
336
+
337
+ function collectMp4(rootDir, maxDepth) {
306
338
  const found = [];
339
+ if (!rootDir || !fs.existsSync(rootDir)) return found;
307
340
  const walk = (dir, depth) => {
308
341
  if (depth > maxDepth) return;
309
342
  let entries;
@@ -313,7 +346,7 @@ export function findLatestMp4(rootDir, { maxDepth = 4 } = {}) {
313
346
  return;
314
347
  }
315
348
  for (const ent of entries) {
316
- if (ent.name === 'node_modules' || ent.name === '.git') continue;
349
+ if (ent.name === 'node_modules' || ent.name === '.git' || ent.name === '.venv') continue;
317
350
  const full = path.join(dir, ent.name);
318
351
  if (ent.isDirectory()) walk(full, depth + 1);
319
352
  else if (ent.isFile() && /\.mp4$/i.test(ent.name)) {
@@ -326,12 +359,59 @@ export function findLatestMp4(rootDir, { maxDepth = 4 } = {}) {
326
359
  }
327
360
  }
328
361
  };
329
- const outDir = path.join(rootDir, 'out');
330
- if (fs.existsSync(outDir)) walk(outDir, 0);
331
- if (!found.length) walk(rootDir, 0);
362
+ walk(rootDir, 0);
363
+ return found;
364
+ }
365
+
366
+ function pickFilm(found) {
332
367
  if (!found.length) return null;
333
- found.sort((a, b) => b.mtime - a.mtime);
334
- return found[0];
368
+ found.sort((a, b) => {
369
+ const ai = isIntermediateMp4(a.path) ? 1 : 0;
370
+ const bi = isIntermediateMp4(b.path) ? 1 : 0;
371
+ if (ai !== bi) return ai - bi;
372
+ return b.mtime - a.mtime;
373
+ });
374
+ const best = found[0];
375
+ if (!best || isIntermediateMp4(best.path)) return null;
376
+ return best;
377
+ }
378
+
379
+ /** Newest deliverable MP4. Root-level `<name>.mp4` wins over `out/video.mp4`. */
380
+ export function findLatestMp4(rootDir, { maxDepth = 6, sinceMs = 0 } = {}) {
381
+ const since = Number(sinceMs) || 0;
382
+ const found = collectMp4(rootDir, maxDepth).filter((hit) => !since || hit.mtime >= since);
383
+ return pickFilm(found);
384
+ }
385
+
386
+ /** roots: directory string, or { dir, sinceMs, maxDepth }. */
387
+ export function locateFilm(roots) {
388
+ const found = [];
389
+ for (const root of roots || []) {
390
+ const dir = typeof root === 'string' ? root : root?.dir;
391
+ const sinceMs = typeof root === 'string' ? 0 : Number(root?.sinceMs) || 0;
392
+ const maxDepth = typeof root === 'string' ? 6 : root?.maxDepth || 6;
393
+ found.push(...collectMp4(dir, maxDepth).filter((hit) => !sinceMs || hit.mtime >= sinceMs));
394
+ }
395
+ return pickFilm(found);
396
+ }
397
+
398
+ export function locateJobFilm(job, cfg) {
399
+ if (!job) return null;
400
+ const roots = Array.isArray(job.filmRoots) && job.filmRoots.length
401
+ ? [...job.filmRoots]
402
+ : [];
403
+ const dir = job.projectPath || (job.artifact && !String(job.artifact).toLowerCase().endsWith('.mp4') ? job.artifact : '');
404
+ if (dir && !roots.some((root) => (typeof root === 'string' ? root : root?.dir) === dir)) {
405
+ roots.unshift({ dir, sinceMs: 0 });
406
+ }
407
+ const sinceMs = Date.parse(job.createdAt);
408
+ if (cfg?.engineRoot && Number.isFinite(sinceMs)) {
409
+ const engineFilms = path.join(cfg.engineRoot, 'films');
410
+ if (!roots.some((root) => (typeof root === 'string' ? root : root?.dir) === engineFilms)) {
411
+ roots.push({ dir: engineFilms, sinceMs });
412
+ }
413
+ }
414
+ return locateFilm(roots);
335
415
  }
336
416
 
337
417
  /** Poll until an MP4 appears; updates job + panel progress. */
@@ -345,9 +425,36 @@ export function watchForFilm(cfg, jobs, jobId, {
345
425
  const tick = async () => {
346
426
  const job = jobs.get(jobId);
347
427
  if (!job || job.status === 'failed' || job.status === 'cancelled') return;
348
- if (job.outputMp4 && fs.existsSync(job.outputMp4)) return;
349
- const hit = findLatestMp4(projectPath || job.projectPath || job.artifact);
350
- if (hit) {
428
+ const current = String(job.outputMp4 || '');
429
+ if (current && fs.existsSync(current) && !isIntermediateMp4(current)) return;
430
+ if (current && !fs.existsSync(current)) {
431
+ const rescued = rescueMissingFilm(current);
432
+ if (rescued) {
433
+ const message = `成片已就绪 · ${path.basename(rescued)}`;
434
+ const size = fs.statSync(rescued).size;
435
+ jobs.update(jobId, {
436
+ status: 'done',
437
+ progress: 100,
438
+ phase: 'film',
439
+ message,
440
+ outputMp4: rescued,
441
+ artifact: rescued,
442
+ filmBytes: size,
443
+ filmAt: new Date().toISOString(),
444
+ });
445
+ await reportProgress(cfg, {
446
+ taskId: jobs.get(jobId)?.panelTaskId,
447
+ title: title || jobs.get(jobId)?.title,
448
+ progress: 100,
449
+ message,
450
+ done: true,
451
+ artifact: rescued,
452
+ });
453
+ return;
454
+ }
455
+ }
456
+ const hit = locateJobFilm({ ...job, projectPath: projectPath || job.projectPath, artifact: job.artifact }, cfg);
457
+ if (hit && !isIntermediateMp4(hit.path)) {
351
458
  const message = `成片已就绪 · ${path.basename(hit.path)}`;
352
459
  jobs.update(jobId, {
353
460
  status: 'done',
@@ -370,19 +477,41 @@ export function watchForFilm(cfg, jobs, jobId, {
370
477
  return;
371
478
  }
372
479
  if (Date.now() - started > timeoutMs) {
373
- jobs.update(jobId, {
374
- status: 'done',
375
- progress: 100,
376
- phase: 'stalled',
377
- message: '等待成片超时 · 可打开工程目录或 DSH 会话查看',
378
- });
379
- await reportProgress(cfg, {
380
- taskId: jobs.get(jobId)?.panelTaskId,
381
- progress: 100,
382
- message: '等待成片超时',
383
- done: true,
384
- artifact: projectPath,
385
- });
480
+ if (hit) {
481
+ const message = `成片已就绪 · ${path.basename(hit.path)}`;
482
+ jobs.update(jobId, {
483
+ status: 'done',
484
+ progress: 100,
485
+ phase: 'film',
486
+ message,
487
+ outputMp4: hit.path,
488
+ artifact: hit.path,
489
+ filmBytes: hit.size,
490
+ filmAt: new Date().toISOString(),
491
+ });
492
+ await reportProgress(cfg, {
493
+ taskId: jobs.get(jobId)?.panelTaskId,
494
+ title: title || jobs.get(jobId)?.title,
495
+ progress: 100,
496
+ message,
497
+ done: true,
498
+ artifact: hit.path,
499
+ });
500
+ } else {
501
+ jobs.update(jobId, {
502
+ status: 'done',
503
+ progress: 100,
504
+ phase: 'stalled',
505
+ message: '等待成片超时 · 可打开工程目录或 DSH 会话查看',
506
+ });
507
+ await reportProgress(cfg, {
508
+ taskId: jobs.get(jobId)?.panelTaskId,
509
+ progress: 100,
510
+ message: '等待成片超时',
511
+ done: true,
512
+ artifact: projectPath,
513
+ });
514
+ }
386
515
  return;
387
516
  }
388
517
  if (job.status === 'running' || job.phase === 'dsh') {
@@ -447,10 +576,33 @@ export function createAgentServer({ root, studioDir, api }) {
447
576
 
448
577
  // 进程重启后:已有成片则收口;否则恢复 watch,避免面板/Studio 任务永远「处理中」
449
578
  for (const j of jobs.list()) {
450
- if (j.status !== 'running') continue;
579
+ const filmMissing = j.outputMp4 && !fs.existsSync(j.outputMp4);
580
+ const filmBad = j.outputMp4 && isIntermediateMp4(j.outputMp4);
581
+ if (filmMissing || filmBad || (j.status === 'done' && !j.outputMp4)) {
582
+ const rescued = filmMissing ? rescueMissingFilm(j.outputMp4) : '';
583
+ const late = rescued
584
+ ? { path: rescued, size: fs.statSync(rescued).size }
585
+ : locateJobFilm(j, cfg);
586
+ if (late && late.path && fs.existsSync(late.path) && !isIntermediateMp4(late.path)) {
587
+ jobs.update(j.id, {
588
+ status: 'done',
589
+ progress: 100,
590
+ phase: 'film',
591
+ message: `成片已就绪 · ${path.basename(late.path)}`,
592
+ outputMp4: late.path,
593
+ artifact: late.path,
594
+ filmBytes: late.size,
595
+ filmAt: new Date().toISOString(),
596
+ });
597
+ continue;
598
+ }
599
+ if (j.status === 'done') continue;
600
+ }
601
+ const waiting = j.status === 'running' || (j.outputMp4 && isIntermediateMp4(j.outputMp4));
602
+ if (!waiting) continue;
451
603
  const projectPath = j.projectPath || (j.artifact && !String(j.artifact).endsWith('.mp4') ? j.artifact : null);
452
- const hit = findLatestMp4(projectPath || j.artifact);
453
- if (hit) {
604
+ const hit = locateJobFilm(j, cfg);
605
+ if (hit && !isIntermediateMp4(hit.path)) {
454
606
  jobs.update(j.id, {
455
607
  status: 'done',
456
608
  progress: 100,
@@ -525,8 +677,27 @@ export function createAgentServer({ root, studioDir, api }) {
525
677
  if (req.method === 'GET' && /^\/api\/jobs\/[^/]+\/film$/.test(pathname)) {
526
678
  const id = decodeURIComponent(pathname.slice('/api/jobs/'.length, -'/film'.length));
527
679
  const job = jobs.get(id);
528
- const file = job ? String(job.outputMp4 || '') : '';
529
- if (!file || !file.toLowerCase().endsWith('.mp4')) return sendJson(res, 404, { error: '成片还没有' });
680
+ let file = job ? String(job.outputMp4 || '') : '';
681
+ if (job && (!file || !fs.existsSync(file) || isIntermediateMp4(file))) {
682
+ const rescued = file && !fs.existsSync(file) ? rescueMissingFilm(file) : '';
683
+ const late = rescued
684
+ ? { path: rescued, size: fs.statSync(rescued).size }
685
+ : locateJobFilm(job, cfg);
686
+ if (late && late.path && fs.existsSync(late.path) && !isIntermediateMp4(late.path)) {
687
+ jobs.update(job.id, {
688
+ status: 'done',
689
+ progress: 100,
690
+ phase: 'film',
691
+ message: `成片已就绪 · ${path.basename(late.path)}`,
692
+ outputMp4: late.path,
693
+ artifact: late.path,
694
+ filmBytes: late.size,
695
+ filmAt: new Date().toISOString(),
696
+ });
697
+ file = late.path;
698
+ }
699
+ }
700
+ if (!file || !file.toLowerCase().endsWith('.mp4') || !fs.existsSync(file)) return sendJson(res, 404, { error: '成片还没有' });
530
701
  return serveLocalFile(req, res, file);
531
702
  }
532
703
  if (pathname.startsWith('/api/jobs/') && req.method === 'GET') {
package/manifest.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "schemaVersion": 1,
3
3
  "id": "biutalk",
4
4
  "name": "BiuTalk",
5
- "version": "1.1.3",
5
+ "version": "1.1.5",
6
6
  "publisher": "Biunow",
7
7
  "description": "BiuTalk 解说视频 Studio:模板、尺寸、附件与本地渲染引擎。",
8
8
  "entry": {
@@ -47,8 +47,8 @@
47
47
  "requiresEntitlement": "export"
48
48
  },
49
49
  "integrity": {
50
- "sha256": "f0522a456028f5ff10473092a3d8f0a7ab3f978c0751e775912be8eae395a01d",
51
- "signature": "+Sausjf8RQEhGqmvLVprLTu+5mXZaX3RfmRQA/ZBrCiGszlWNPT2m2s/mfuJHc3wHpztVSWcAjHQPyWTkRuSAw==",
50
+ "sha256": "3ff006fe6a6d6d5784e6486bf3850535fd3e3369653541dadd2a856f70b304bf",
51
+ "signature": "FdnginJChcHlCnFwc8bNvx0Cpv7LZsfHDE7sGqK9zNfOm34hwRu1LnDqFCkcgCQgoExV1ltPZS/hKkm9dkxmAw==",
52
52
  "signedBy": "publisher-key"
53
53
  }
54
54
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@biunow/agent-biutalk",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
4
4
  "description": "BiuTalk",
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
package/studio/app.js CHANGED
@@ -20,6 +20,12 @@
20
20
 
21
21
  const $ = (id) => document.getElementById(id);
22
22
 
23
+ function applyLookChoice(id, opts) {
24
+ state.look = id;
25
+ const look = (state.meta?.looks || []).find((item) => item.id === id);
26
+ if (look && look.recipe) Composer.paintRecipe(state, look.recipe, look.recipe.hint, opts && opts.keep);
27
+ }
28
+
23
29
  function renderAssets() {
24
30
  const box = $('assets');
25
31
  if (!state.urls.length && !state.files.length) {
@@ -84,8 +90,8 @@
84
90
  sizeMenu.setValue(job.size, true);
85
91
  }
86
92
  if (typeof job.look === 'string' && lookMenu) {
87
- state.look = job.look;
88
93
  lookMenu.setValue(job.look, true);
94
+ applyLookChoice(job.look, { keep: true });
89
95
  }
90
96
  if (job.pace != null && Number.isFinite(Number(job.pace))) {
91
97
  state.pace = Number(job.pace);
@@ -211,9 +217,13 @@
211
217
  },
212
218
  });
213
219
 
220
+ const looks = state.meta.looks || [];
221
+ const want = new URLSearchParams(location.search).get('style');
222
+ const picked = looks.find((item) => item.id === want) || looks.find((item) => item.id === state.look) || looks[0];
223
+ if (picked) state.look = picked.id;
214
224
  lookMenu = SelectMenu.mount($('lookPick'), {
215
225
  value: state.look,
216
- options: (state.meta.looks || []).map((l) => ({
226
+ options: looks.map((l) => ({
217
227
  value: l.id,
218
228
  label: l.name,
219
229
  hint: l.desc,
@@ -221,10 +231,9 @@
221
231
  desc: l.desc,
222
232
  })),
223
233
  size: 'sm',
224
- onChange: (v) => {
225
- state.look = v;
226
- },
234
+ onChange: (v) => applyLookChoice(v),
227
235
  });
236
+ if (picked) applyLookChoice(picked.id);
228
237
 
229
238
  syncPaceHint();
230
239
  await refreshJobs();
@@ -91,6 +91,13 @@ button:disabled { cursor: not-allowed; opacity: .5; }
91
91
  display: flex; flex-wrap: wrap; align-items: center; gap: 8px;
92
92
  padding: 12px 16px 8px;
93
93
  }
94
+ .need-flags { display: flex; flex-wrap: wrap; gap: 6px; margin-left: auto; }
95
+ .need-flag {
96
+ font-size: 11px; font-weight: 650; border-radius: 99px; padding: 2px 8px;
97
+ background: #f4f4ef; color: var(--ink);
98
+ }
99
+ .need-flag.required { background: var(--ink); color: var(--accent); }
100
+ .need-flag.off { color: var(--muted); }
94
101
  .link-input {
95
102
  flex: 1; min-width: 200px; border: 1px solid var(--line); border-radius: 10px;
96
103
  padding: 8px 12px; font-size: 12px; background: #fafaf7; color: var(--ink); outline: 0;
@@ -401,4 +408,38 @@ button:disabled { cursor: not-allowed; opacity: .5; }
401
408
  display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;
402
409
  }
403
410
 
411
+ .sm-panel.has-cats { padding: 0; overflow: hidden; }
412
+ .sm-cats {
413
+ display: flex; flex-wrap: wrap; gap: 6px 5px;
414
+ padding: 10px 10px 9px;
415
+ background: #f7f7f4;
416
+ border-bottom: 1px solid var(--line);
417
+ }
418
+ .sm-cat {
419
+ appearance: none; border: 1px solid var(--line-strong); background: #fff; color: var(--ink);
420
+ border-radius: 99px; padding: 4px 10px; font-size: 11px; font-weight: 600; line-height: 16px;
421
+ white-space: nowrap; cursor: pointer;
422
+ }
423
+ .sm-cat:hover { border-color: #b9b9b4; }
424
+ .sm-cat.on { background: var(--ink); color: var(--accent); border-color: var(--ink); }
425
+ .sm-cat.on:hover { background: #1b1b1b; }
426
+ .sm-panel.has-cats .sm-scroll.grid { margin: 0; padding: 8px; }
427
+ .sm-entry {
428
+ display: flex; flex-wrap: wrap; align-items: center; gap: 6px;
429
+ padding: 8px; border-top: 1px solid var(--line);
430
+ }
431
+ .sm-entry input {
432
+ flex: 1; min-width: 0; height: 30px; border: 1px solid var(--line-strong);
433
+ border-radius: 8px; padding: 0 10px; font-size: 12px; color: var(--ink); background: #fff; outline: none;
434
+ }
435
+ .sm-entry input:focus { border-color: var(--ink); }
436
+ .sm-entry input.bad { border-color: var(--danger); }
437
+ .sm-entry .unit { flex: none; font-size: 12px; color: var(--muted); }
438
+ .sm-entry button {
439
+ flex: none; height: 30px; border: 0; background: var(--ink); color: var(--accent);
440
+ border-radius: 99px; padding: 0 12px; font-size: 12px; font-weight: 700;
441
+ }
442
+ .sm-entry button:hover { background: #1b1b1b; }
443
+ .sm-entry-err { flex: 1 0 100%; margin: 0; font-size: 11px; line-height: 1.3; color: var(--danger); }
444
+
404
445
  .file-hidden { position: absolute; width: 0; height: 0; opacity: 0; pointer-events: none; }
@@ -282,6 +282,47 @@
282
282
  container.appendChild(c);
283
283
  }
284
284
 
285
+ const RECIPE_LEVEL = { off: '无', optional: '可选', required: '必须' };
286
+
287
+ function paintRecipe(state, recipe, hint, keepText) {
288
+ const prompt = document.getElementById('prompt');
289
+ let bar = document.getElementById('needBar');
290
+ if (!bar && prompt) {
291
+ bar = document.createElement('div');
292
+ bar.id = 'needBar';
293
+ bar.className = 'link-bar';
294
+ prompt.parentNode.insertBefore(bar, prompt);
295
+ }
296
+ if (!bar) return;
297
+ bar.hidden = false;
298
+ let hintEl = document.getElementById('needHint');
299
+ if (!hintEl) {
300
+ hintEl = document.createElement('span');
301
+ hintEl.id = 'needHint';
302
+ hintEl.className = 'muted';
303
+ bar.appendChild(hintEl);
304
+ }
305
+ hintEl.textContent = hint || (recipe && recipe.hint) || '';
306
+ let flags = document.getElementById('needFlags');
307
+ if (!flags) {
308
+ flags = document.createElement('div');
309
+ flags.id = 'needFlags';
310
+ flags.className = 'need-flags';
311
+ bar.appendChild(flags);
312
+ }
313
+ const narr = (recipe && recipe.narration) || 'optional';
314
+ const att = (recipe && recipe.attachment) || 'optional';
315
+ flags.innerHTML =
316
+ `<span class="need-flag ${narr}">旁白 · ${RECIPE_LEVEL[narr] || narr}</span>` +
317
+ `<span class="need-flag ${att}">附件 · ${RECIPE_LEVEL[att] || att}</span>`;
318
+ const text = String((recipe && recipe.prompt) || '').trim();
319
+ if (prompt && text && !keepText) {
320
+ prompt.value = text;
321
+ prompt.dispatchEvent(new Event('input'));
322
+ state.seed = text;
323
+ }
324
+ }
325
+
285
326
  function titleFromPrompt(prompt, fallback) {
286
327
  const line = String(prompt || '')
287
328
  .trim()
@@ -303,5 +344,6 @@
303
344
  renderJobs,
304
345
  addChip,
305
346
  titleFromPrompt,
347
+ paintRecipe,
306
348
  };
307
349
  })(window);
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs';
2
+
3
+ /** 从《风格提示词.md》读出每条模板的起步提示词。标题用 ## 或 ###。 */
4
+ export function loadRecipes(file) {
5
+ if (!file || !fs.existsSync(file)) return [];
6
+ const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
7
+ const recipes = [];
8
+ let section = '';
9
+ let title = '';
10
+ let blurb = [];
11
+ let buf = [];
12
+ let inCode = false;
13
+
14
+ const flush = () => {
15
+ const prompt = buf.join('\n').trim();
16
+ if (title && prompt) {
17
+ recipes.push({
18
+ section,
19
+ title: title.trim(),
20
+ blurb: blurb.join(' ').replace(/\s+/g, ' ').trim(),
21
+ prompt,
22
+ });
23
+ }
24
+ buf = [];
25
+ blurb = [];
26
+ };
27
+
28
+ for (const line of lines) {
29
+ if (line.startsWith('```')) {
30
+ if (inCode) {
31
+ inCode = false;
32
+ flush();
33
+ title = '';
34
+ } else {
35
+ inCode = true;
36
+ }
37
+ continue;
38
+ }
39
+ if (inCode) {
40
+ buf.push(line);
41
+ continue;
42
+ }
43
+ if (line.startsWith('### ')) {
44
+ title = line.slice(4).trim();
45
+ blurb = [];
46
+ continue;
47
+ }
48
+ if (line.startsWith('## ')) {
49
+ section = line.slice(3).trim();
50
+ title = section;
51
+ blurb = [];
52
+ continue;
53
+ }
54
+ if (line.startsWith('# ')) continue;
55
+ if (title && line.trim()) blurb.push(line.trim());
56
+ }
57
+ return recipes;
58
+ }
59
+
60
+ function norm(value) {
61
+ return String(value || '').trim().toLowerCase().replace(/\s+/g, '');
62
+ }
63
+
64
+ export function findRecipe(recipes, keys) {
65
+ const wants = [...new Set((keys || []).map(norm).filter(Boolean))];
66
+ for (const want of wants) {
67
+ const hit = (recipes || []).find((recipe) => {
68
+ const title = norm(recipe.title);
69
+ const head = norm(String(recipe.title).split('·')[0]);
70
+ return title === want || head === want;
71
+ });
72
+ if (hit) return hit;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export function recipeView(recipe, extras = {}) {
78
+ const prompt = String(recipe?.prompt || extras.prompt || '').trim();
79
+ return {
80
+ prompt,
81
+ blurb: recipe?.blurb || '',
82
+ narration: extras.narration || 'optional',
83
+ attachment: extras.attachment || 'optional',
84
+ hint: extras.hint || recipe?.blurb || '',
85
+ };
86
+ }
@@ -26,6 +26,13 @@
26
26
  this.pos = { left: 0, top: 0, bottom: 0, width: 0 };
27
27
  this.previewIndex = -1;
28
28
  this.hoverTop = 0;
29
+ this.cat = '';
30
+ this.entryLabel = '';
31
+ this.entrySeconds = null;
32
+ this.entryOpen = false;
33
+ this.entryDraft = '';
34
+ this.entryError = false;
35
+ this.valueBeforeEntry = '';
29
36
  this._previewTimer = null;
30
37
  this.root = null;
31
38
  this.trigger = null;
@@ -43,6 +50,23 @@
43
50
  return this.options.some((o) => !!o.thumb);
44
51
  };
45
52
 
53
+ SelectMenu.prototype.hasGroups = function () {
54
+ return this.options.some((o) => !!o.group);
55
+ };
56
+
57
+ SelectMenu.prototype.groups = function () {
58
+ const seen = [];
59
+ this.options.forEach((o) => {
60
+ if (o.group && !seen.includes(o.group)) seen.push(o.group);
61
+ });
62
+ return seen;
63
+ };
64
+
65
+ SelectMenu.prototype.visibleOptions = function () {
66
+ if (!this.hasGroups() || !this.cat) return this.options;
67
+ return this.options.filter((o) => o.group === this.cat);
68
+ };
69
+
46
70
  SelectMenu.prototype.selected = function () {
47
71
  return this.options.find((o) => o.value === this.value) || null;
48
72
  };
@@ -83,10 +107,10 @@
83
107
  if (this.open) this.renderPanel();
84
108
  };
85
109
 
86
- SelectMenu.prototype.setValue = function (value, silent) {
110
+ SelectMenu.prototype.setValue = function (value, silent, extra) {
87
111
  this.value = value;
88
112
  this.renderTrigger();
89
- if (!silent && typeof this.opts.onChange === 'function') this.opts.onChange(this.value);
113
+ if (!silent && typeof this.opts.onChange === 'function') this.opts.onChange(this.value, extra);
90
114
  };
91
115
 
92
116
  SelectMenu.prototype.renderTrigger = function () {
@@ -94,12 +118,14 @@
94
118
  const thumb = sel?.thumb
95
119
  ? `<span class="sm-thumb sm-thumb-trigger"><img src="${esc(sel.thumb)}" alt=""/></span>`
96
120
  : '';
97
- const hint = sel?.hint && !this.gridMode()
121
+ const customLabel = sel?.entry && this.entryLabel;
122
+ const hint = sel?.hint && !this.gridMode() && !customLabel
98
123
  ? `<span class="sm-hint">${esc(sel.hint)}</span>`
99
124
  : '';
125
+ const label = sel ? (customLabel || sel.label) : this.placeholder;
100
126
  this.trigger.classList.toggle('on', this.open);
101
127
  this.trigger.innerHTML = `${thumb}<span class="sm-value${sel ? '' : ' placeholder'}">${esc(
102
- sel ? sel.label : this.placeholder,
128
+ label,
103
129
  )}</span>${hint}<svg class="sm-chevron${this.open ? ' on' : ''}" viewBox="0 0 16 16" fill="none"><path d="M4 6l4 4 4-4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
104
130
  };
105
131
 
@@ -108,17 +134,37 @@
108
134
  const vw = window.innerWidth;
109
135
  const vh = window.innerHeight;
110
136
  const grid = this.gridMode();
137
+ const visible = this.visibleOptions();
111
138
  const minWidth = grid ? 404 : 210;
112
139
  const width = Math.min(Math.max(r.width, minWidth), vw - 24);
113
140
  const left = Math.min(Math.max(12, r.left), Math.max(12, vw - width - 12));
114
- const estHeight = grid
115
- ? Math.min(430, Math.ceil(this.options.length / 3) * 96 + 14)
116
- : Math.min(300, this.options.length * 38 + 12);
117
- this.dropUp = vh - r.bottom < estHeight + 14 && r.top > estHeight + 14;
118
- this.pos = { left, width, top: r.bottom + 6, bottom: vh - r.top + 6 };
141
+ const gap = 6;
142
+ const margin = 12;
143
+ const below = Math.max(0, vh - r.bottom - gap - margin);
144
+ const above = Math.max(0, r.top - gap - margin);
145
+ let chrome = 0;
119
146
  if (this.panel) {
120
147
  this.panel.style.left = `${left}px`;
121
148
  this.panel.style.width = `${width}px`;
149
+ const cats = this.panel.querySelector('.sm-cats');
150
+ const entry = this.panel.querySelector('.sm-entry');
151
+ chrome = (cats ? cats.offsetHeight : 0) + (entry ? entry.offsetHeight : 0);
152
+ }
153
+ const scrollCap = grid ? 430 : 292;
154
+ const naturalScroll = grid
155
+ ? Math.min(scrollCap, Math.ceil(Math.max(visible.length, 1) / 3) * 96 + 14)
156
+ : Math.min(scrollCap, visible.length * 38 + 12);
157
+ const want = Math.min(chrome + naturalScroll, 240);
158
+ this.dropUp = below < want && above > below;
159
+ const available = Math.max(0, this.dropUp ? above : below);
160
+ const room = Math.min(available, chrome + naturalScroll);
161
+ const scrollMax = Math.max(0, Math.min(scrollCap, room - chrome));
162
+ this.pos = { left, width, top: r.bottom + gap, bottom: vh - r.top + gap };
163
+ if (this.panel) {
164
+ this.panel.style.maxHeight = `${room}px`;
165
+ this.panel.style.overflow = scrollMax > 0 ? 'hidden' : 'auto';
166
+ const scroll = this.panel.querySelector('.sm-scroll');
167
+ if (scroll) scroll.style.maxHeight = `${scrollMax}px`;
122
168
  if (this.dropUp) {
123
169
  this.panel.style.bottom = `${this.pos.bottom}px`;
124
170
  this.panel.style.top = 'auto';
@@ -131,7 +177,11 @@
131
177
 
132
178
  SelectMenu.prototype.toggle = function () {
133
179
  if (this.open) this.close();
134
- else this.openAt(Math.max(0, this.options.findIndex((o) => o.value === this.value)));
180
+ else {
181
+ const visible = this.visibleOptions();
182
+ const idx = visible.findIndex((o) => o.value === this.value);
183
+ this.openAt(idx >= 0 ? idx : 0);
184
+ }
135
185
  };
136
186
 
137
187
  SelectMenu.prototype.openAt = function (index) {
@@ -146,6 +196,11 @@
146
196
  };
147
197
 
148
198
  SelectMenu.prototype.close = function () {
199
+ if (this.entryOpen) {
200
+ this.value = this.valueBeforeEntry;
201
+ this.entryOpen = false;
202
+ this.entryError = false;
203
+ }
149
204
  this.open = false;
150
205
  this.hidePreview();
151
206
  this.renderTrigger();
@@ -189,7 +244,7 @@
189
244
  }
190
245
  return;
191
246
  }
192
- const opt = this.options[this.previewIndex];
247
+ const opt = this.visibleOptions()[this.previewIndex];
193
248
  if (!opt) return;
194
249
  if (!this.previewEl) {
195
250
  this.previewEl = document.createElement('div');
@@ -223,9 +278,16 @@
223
278
  document.body.appendChild(this.panel);
224
279
  }
225
280
  const grid = this.gridMode();
281
+ const grouped = this.hasGroups();
282
+ const visible = this.visibleOptions();
283
+ this.panel.classList.toggle('has-cats', grouped);
226
284
  const scroll = document.createElement('div');
227
285
  scroll.className = 'sm-scroll' + (grid ? ' grid' : '');
228
- this.options.forEach((opt, i) => {
286
+ if (grid && grouped) {
287
+ const room = Math.max(168, window.innerHeight - 24 - 92);
288
+ scroll.style.maxHeight = `${Math.min(430, room)}px`;
289
+ }
290
+ visible.forEach((opt, i) => {
229
291
  const btn = document.createElement('button');
230
292
  btn.type = 'button';
231
293
  btn.className =
@@ -256,10 +318,130 @@
256
318
  });
257
319
  scroll.addEventListener('mouseleave', () => this.hidePreview());
258
320
  this.panel.innerHTML = '';
321
+ if (grouped) this.panel.appendChild(this.renderCats());
259
322
  this.panel.appendChild(scroll);
323
+ if (this.entryOpen) {
324
+ this.panel.appendChild(this.renderEntry());
325
+ const input = this.panel.querySelector('.sm-entry input');
326
+ setTimeout(() => input && input.focus(), 0);
327
+ }
328
+ };
329
+
330
+ SelectMenu.prototype.renderCats = function () {
331
+ const bar = document.createElement('div');
332
+ bar.className = 'sm-cats';
333
+ const items = [{ id: '', label: '全部' }].concat(
334
+ this.groups().map((name) => ({ id: name, label: name })),
335
+ );
336
+ items.forEach((item) => {
337
+ const btn = document.createElement('button');
338
+ btn.type = 'button';
339
+ btn.className = 'sm-cat' + (this.cat === item.id ? ' on' : '');
340
+ btn.textContent = item.label;
341
+ btn.setAttribute('aria-pressed', this.cat === item.id ? 'true' : 'false');
342
+ btn.addEventListener('click', (e) => {
343
+ e.preventDefault();
344
+ e.stopPropagation();
345
+ if (this.cat === item.id) return;
346
+ this.cat = item.id;
347
+ this.hidePreview();
348
+ const visible = this.visibleOptions();
349
+ const picked = visible.findIndex((o) => o.value === this.value);
350
+ this.activeIndex = picked >= 0 ? picked : 0;
351
+ this.renderPanel();
352
+ this.measure();
353
+ });
354
+ bar.appendChild(btn);
355
+ });
356
+ return bar;
357
+ };
358
+
359
+ SelectMenu.prototype.renderEntry = function () {
360
+ const box = document.createElement('div');
361
+ box.className = 'sm-entry';
362
+ const input = document.createElement('input');
363
+ input.setAttribute('inputmode', 'numeric');
364
+ input.setAttribute('maxlength', '3');
365
+ input.setAttribute('aria-label', '自定义秒数');
366
+ input.placeholder = '15–180';
367
+ input.value = this.entryDraft;
368
+ if (this.entryError) input.classList.add('bad');
369
+ const unit = document.createElement('span');
370
+ unit.className = 'unit';
371
+ unit.textContent = '秒';
372
+ const ok = document.createElement('button');
373
+ ok.type = 'button';
374
+ ok.textContent = '确定';
375
+ input.addEventListener('input', () => {
376
+ const next = input.value.replace(/[^\d]/g, '').slice(0, 3);
377
+ if (input.value !== next) input.value = next;
378
+ this.entryDraft = next;
379
+ this.entryError = false;
380
+ input.classList.remove('bad');
381
+ const err = box.querySelector('.sm-entry-err');
382
+ if (err) err.remove();
383
+ });
384
+ input.addEventListener('keydown', (e) => {
385
+ if (e.key === 'Enter') {
386
+ e.preventDefault();
387
+ this.commitEntry();
388
+ } else if (e.key === 'Escape') {
389
+ e.preventDefault();
390
+ this.close();
391
+ }
392
+ });
393
+ ok.addEventListener('click', (e) => {
394
+ e.preventDefault();
395
+ e.stopPropagation();
396
+ this.commitEntry();
397
+ });
398
+ box.appendChild(input);
399
+ box.appendChild(unit);
400
+ box.appendChild(ok);
401
+ if (this.entryError) {
402
+ const err = document.createElement('p');
403
+ err.className = 'sm-entry-err';
404
+ err.textContent = '请输入秒数';
405
+ box.appendChild(err);
406
+ }
407
+ return box;
408
+ };
409
+
410
+ SelectMenu.prototype.commitEntry = function () {
411
+ const input = this.panel?.querySelector('.sm-entry input');
412
+ if (input) this.entryDraft = input.value;
413
+ const parse = this.opts.parseEntry;
414
+ const n = typeof parse === 'function' ? parse(this.entryDraft) : null;
415
+ if (n == null) {
416
+ this.entryError = true;
417
+ this.renderPanel();
418
+ this.measure();
419
+ return;
420
+ }
421
+ this.entrySeconds = n;
422
+ this.entryLabel = this.opts.formatEntry ? this.opts.formatEntry(n) : String(n);
423
+ this.entryOpen = false;
424
+ this.entryError = false;
425
+ this.setValue(this.value, false, n);
426
+ this.close();
260
427
  };
261
428
 
262
429
  SelectMenu.prototype.pick = function (value) {
430
+ const opt = this.options.find((o) => o.value === value);
431
+ if (opt && opt.entry) {
432
+ if (!this.entryOpen) this.valueBeforeEntry = this.value;
433
+ this.entryOpen = true;
434
+ this.entryError = false;
435
+ this.entryDraft = this.entrySeconds != null ? String(this.entrySeconds) : '';
436
+ this.value = value;
437
+ this.renderTrigger();
438
+ this.renderPanel();
439
+ this.measure();
440
+ return;
441
+ }
442
+ this.entryOpen = false;
443
+ this.entryLabel = '';
444
+ this.entrySeconds = null;
263
445
  this.setValue(value);
264
446
  this.close();
265
447
  };
@@ -0,0 +1,51 @@
1
+ # BiuTalk 风格提示词
2
+
3
+ BiuTalk 做口播解说。先选画面气质,再选画幅,把提示词贴进需求框。它会写成讲稿,再配上解说。
4
+
5
+ ## Paper · 手绘纸面
6
+
7
+ 适合给普通人讲清楚一件事。默认气质,友好,不端着。
8
+
9
+ ```
10
+ 用纸面手绘讲「为什么飞机上要调成飞行模式」。先给一个让人好奇的开头,再分三步讲信号、规定和实际影响。横屏,语速适中,句子短。
11
+ ```
12
+
13
+ ## Clean · 简洁商务
14
+
15
+ 适合产品和商务说明。画面干净,重点是步骤和结论。
16
+
17
+ ```
18
+ 用简洁商务画面讲「一个新同事第一天怎么把公司邮箱、日历和共享盘连上」。按打开、登录、核对这三步讲,每步只留一个动作。横屏。
19
+ ```
20
+
21
+ ## Chalk · 教学黑板
22
+
23
+ 适合一堂课讲透一个概念。像老师在黑板上边写边讲。
24
+
25
+ ```
26
+ 用黑板粉笔讲「分数为什么要先通分再相加」。先写一个会算错的例子,再擦掉重写正确的一步,最后留一句能记住的话。竖屏,给抖音。
27
+ ```
28
+
29
+ ## Blueprint · 工程蓝图
30
+
31
+ 适合讲一个东西是怎么造出来、怎么接起来的。线条、标注、结构。
32
+
33
+ ```
34
+ 用工程蓝图讲「家里的路由器、猫和光猫各自管哪一段」。用标注线指出每台设备的入口和出口,不要堆术语。横屏。
35
+ ```
36
+
37
+ ## Midnight · 深色工具
38
+
39
+ 适合讲给会用电脑的人听。界面、命令、开发者工具。
40
+
41
+ ```
42
+ 用深色工具风讲「一条报错信息要先看哪三行」。画面像终端和代码面板,指出文件名、行号和真正的原因。横屏,节奏快一点。
43
+ ```
44
+
45
+ ## Editorial · 评论杂志
46
+
47
+ 适合评论、历史和财经。一篇短文的口气,不是步骤教程。
48
+
49
+ ```
50
+ 用杂志评论的口气讲「一次降息为什么不会立刻让物价降下来」。先抛判断,再给两个能核对的原因,结尾留一个问题。横屏。
51
+ ```